@vkontakte/videoplayer-core 2.0.139 → 2.0.140-dev.26e4b860.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +6 -6
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +9 -9
- package/es2024.cjs.js +10 -10
- package/es2024.esm.js +12 -12
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.140-dev.26e4b860.0
|
|
3
|
+
* Mon, 25 Aug 2025 17:43:24 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
|
|
5
5
|
*/
|
|
6
|
-
var io="2.0.139";var Se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Se||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(et||{});var Xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Xr||{}),xa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xa||{});var ka=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(ka||{}),Jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Jr||{});import{assertNever as uo,assertNonNullable as al,isNonNullable as Zr,ValueSubject as Aa,Subject as nl,Subscription as ol,merge as ul,observableFrom as dl,fromEvent as so,map as ao,tap as no,filterChanged as ll,isNullable as wa,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var es=class{constructor(e){this.connection$=new Aa(void 0);this.castState$=new Aa("NOT_AVAILABLE");this.errorEvent$=new nl;this.realCastState$=new Aa("NOT_AVAILABLE");this.subscription=new ol;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Zr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||ro("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Zr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(so(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uo(r.sessionState)}})).add(ul(so(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(no(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ao(r=>r.castState)),dl([i.getCastState()])).pipe(ll(),ao(cl),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Zr(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();al(u);let o=u.getCastDevice(),d=u.getMediaSession()?.media?.contentId;(wa(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Zr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:oo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},cl=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(n)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return n},pt=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var A=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as hl,Subject as ts,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new ts;this.transitionEnded$=new ts;this.transitionUpdated$=new ts;this.forceChanged$=new ts;this.stateChangeStarted$=co(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=co(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||hl(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as go}from"@vkontakte/videoplayer-shared/evergreen";var is=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,d=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||d||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Li=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var rs=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Li()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var ss=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var we=()=>window.ManagedMediaSource||window.MediaSource,Yt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),as=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var pl=document.createElement("video"),ml='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fl='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',bl='audio/mp4; codecs="mp4a.40.2"',gl='audio/webm; codecs="opus"',fo,Sl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};Sl().catch(n=>{console.log(pl),console.error(n)});var ns=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return fo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Yt(),mse:ho(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!we()?.isTypeSupported?.(ml),t=!!we()?.isTypeSupported?.(fl),i=!!we()?.isTypeSupported?.(bl);this._codecs={h264:e,h265:t,vp9:!!we()?.isTypeSupported?.(po),av1:!!we()?.isTypeSupported?.(mo),aac:i,opus:!!we()?.isTypeSupported?.(gl),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var bo="audio/mpeg",os=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(bo)},this._codecs={mp3:!!we()?.isTypeSupported?.(bo)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as vl}from"@vkontakte/videoplayer-shared/evergreen";var Pa=class{constructor(){this.isInited$=new vl(!1);this._displayChecker=new ss,this._deviceChecker=new rs(this._displayChecker),this._browserChecker=new is,this._videoChecker=new ns(this._deviceChecker,this._browserChecker),this._audioChecker=new os,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},D=new Pa;var La=n=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return n.filter(u=>{switch(u){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return go(u)}})},$a=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return go(n)}},yl=n=>{let t=Object.keys(n).filter(i=>!$a(i));return La(t).length>0};import{assertNever as Kt,assertNonNullable as $t,debounce as So,ErrorCategory as vo,fromEvent as Mt,isNonNullable as yo,map as To,merge as Io,observableFrom as Tl,Subject as Il,Subscription as Ma,timeout as El,getHighestQuality as xl}from"@vkontakte/videoplayer-shared/evergreen";var kl=5,Al=5,wl=500,Eo=7e3,$i=class{constructor(e){this.subscription=new Ma;this.loadMediaTimeoutSubscription=new Ma;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}default:Kt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($a(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Ma;this.subscription.add(e),this.subscription.add(Io(this.videoState.stateChangeStarted$.pipe(To(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(To(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Il;e.add(r.pipe(So(wl)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let u=a.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>kl)&&r.next(u),s=u})),e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,u=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Al&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Kt(a)}}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Io(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Tl(["init"])).pipe(So(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];$t(d);let l=xl(Object.keys(d));$t(l);let p=d[l];$t(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=t[e];$t(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];$t(d),i=ee(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kt(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(o)&&(a.metadata.subtitle=o),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(El(Eo).subscribe(()=>s(`timeout(${Eo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:vo.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ko}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Pl}from"@vkontakte/videoplayer-shared/evergreen";var xo=n=>{try{n.pause(),n.playbackRate=0,Pl(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Ll,Subscription as $l}from"@vkontakte/videoplayer-shared/evergreen";var Ra=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Da=window.WeakMap?new WeakMap:new Ra,Ba=window.WeakMap?new WeakMap:new Map,Ml=(n,e=20)=>{let t=0;return Ll(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ve=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?ko(i):(i=document.createElement("video"),n.appendChild(i)),Da.set(i,r);let s=new $l;return s.add(Ml(i,e)),Ba.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ye=n=>{Ba.get(n)?.unsubscribe(),Ba.delete(n);let t=Da.get(n);Da.delete(n),t?ko(n):xo(n)};import{assertNonNullable as Ri,isNonNullable as We,isNullable as Bl,fromEvent as Xt,merge as Ao,observableFrom as wo,filterChanged as Po,map as Di,Subject as Lo,Subscription as Vl,ValueSubject as Cl,ErrorCategory as Ol}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Va,isNullable as Rl,Subscription as Dl}from"@vkontakte/videoplayer-shared/evergreen";var us=(n,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=n.getState(),u=e(),o=Rl(r),d=new Dl;return r&&d.add(r.subscribe(l=>{let p=n.getState();i(l,p)&&n.setState(l)},s)),i(u,a)||(t(a),o&&n.setState(a)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),o&&n.setState(l.to)},s)),d},ze=(n,e,t)=>us(e,()=>n.loop,i=>{Va(i)&&(n.loop=i)},{onError:t}),Te=(n,e,t,i)=>us(e,()=>({muted:n.muted,volume:n.volume}),r=>{Va(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(n,e,t,i)=>us(e,()=>n.playbackRate,r=>{Va(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Mi=us;var Fl=n=>["__",n.language,n.label].join("|"),_l=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Ca=class n{constructor(e){this.available$=new Lo;this.current$=new Cl(void 0);this.error$=new Lo;this.subscription=new Vl;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Ol.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Mi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Mi(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Mi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ri(this.video);let{textTracks:e}=this.video;this.subscription.add(Xt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ao(Xt(e,"addtrack"),Xt(e,"removetrack"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Po((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Ao(Xt(e,"change"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Di(i=>i&&this.htmlTextTrackToITextTrack(i).id),Po()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Xt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Xt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;We(t.align)&&(r.align=t.align),We(t.position)&&(r.position=t.position),We(t.size)&&(r.size=t.size),We(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Fl(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Bl(e)||!_l(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ri(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ri(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=Ca;var Rt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var $o=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Oa=n=>{let e=$o(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Mo=n=>{let e=$o(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as me,map as Ge,merge as ds,filterChanged as Do,isNonNullable as Bo,Subject as Ul,filter as Fa,mapTo as _a,combine as Hl,once as jl,shareReplay as fe,throttle as Ql,ErrorCategory as ql,ValueSubject as Vo,Subscription as zl}from"@vkontakte/videoplayer-shared/evergreen";var Nl=3,Ro=(n,e,t=Nl)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),u=n.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)n.end(o)+t>=i&&(i=n.start(o));for(let o=s+1;o<n.length;o++)n.start(o)-t<=r&&(r=n.end(o))}}return{from:i,to:r}};var Ie=n=>{let e=y=>me(n,y).pipe(_a(void 0),fe(1)),t=new zl,i=()=>t.unsubscribe(),r=ds(me(n,"progress"),me(n,"timeupdate")).pipe(Ge(()=>Ro(n.buffered,n.currentTime)),fe(1)),s=D.browser.isSafari?Hl({play:e("play").pipe(jl()),playing:e("playing")}).pipe(_a(void 0),fe(1)):e("playing"),a=me(n,"volumechange").pipe(Ge(()=>({muted:n.muted,volume:n.volume})),fe(1)),u=me(n,"ratechange").pipe(Ge(()=>n.playbackRate),fe(1)),o=me(n,"error").pipe(Fa(()=>!!(n.error||n.played.length)),Ge(()=>{let y=n.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:ql.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:n.error??void 0}}),fe(1)),d=me(n,"timeupdate").pipe(Ge(()=>n.currentTime),fe(1)),l=["waiting","seeking","seeked","timeupdate"],p=new Ul,c=.3,h;t.add(ds(...l.map(y=>me(n,y))).subscribe(y=>{let _=n.currentTime;n.loop&&Bo(h)&&Bo(_)&&h>=n.duration-c&&_<=c&&p.next(h),h=_}));let m=e("pause").pipe(Fa(()=>!n.error&&h!==n.duration),fe(1)),f=me(n,"enterpictureinpicture").pipe(fe(1)),b=me(n,"leavepictureinpicture").pipe(fe(1)),g=new Vo(Mo(n));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let E=new Vo(Oa(n)),I=me(n,"fullscreenchange").pipe(fe(1));t.add(I.pipe(Ge(()=>Oa(n))).subscribe(E));let v=.1,x=1e3,R=me(n,"timeupdate").pipe(Ge(y=>n.duration-n.currentTime<v),Do(),fe(1)),L=ds(R.pipe(Fa(y=>!n.loop&&y)),me(n,"ended")).pipe(Ql(x),_a(void 0),fe(1)),P=ds(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>me(n,y)),R.pipe(Ge(y=>({type:y?"ended":"unknown"})))).pipe(Ge(y=>D.browser.isFirefox&&y.type==="ended"?n.readyState<2:n.readyState<3),Do(),fe(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:me(n,"durationchange").pipe(Ge(()=>n.duration),fe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:E,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=n=>{switch(n){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as G,isNullable as ms,now as qo,isHigher as fs,isHigherOrEqual as Zt,isInvariantQuality as bs,isLowerOrEqual as ei,videoSizeToQuality as zo,assertNotEmptyArray as gs,assertNonNullable as Wo}from"@vkontakte/videoplayer-shared/evergreen";var Na=!1,it={},Co=n=>{Na=n},Oo=()=>{it={}},Fo=n=>{n(it)},Bi=(n,e)=>{Na&&(it.meta=it.meta??{},it.meta[n]=e)},be=class{constructor(e){this.name=e}next(e){if(!Na)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Wl,isHigherOrEqual as Fb,isLower as _o,isLowerOrEqual as _b,isNonNullable as ls,isNullable as Gl,videoHeightToQuality as cs}from"@vkontakte/videoplayer-shared/evergreen";function Ua(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function hs(n,e,t){return!!n&&Ua(n,e,t)==="high_quality"}function Jt(n,e,t){return Gl(n)||ls(n.min)&&ls(n.max)&&_o(n.max,n.min)||ls(n.min)&&e&&Wl(n.min,e)||ls(n.max)&&t&&_o(n.max,t)}function No({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({max:n?.max?cs(n.max):void 0,min:n?.min?cs(n.min):void 0},e?cs(e):void 0,t?cs(t):void 0)}var Go=new be("best_bitrate"),Ss=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var ti=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vs='Assertion "ABR Tracks is empty array" failed',ps=new WeakMap,Uo=new WeakMap,Ho=new WeakMap,Vi=(n,e,t,i)=>{let r=[...e].sort(ti(1)),s=[...t].sort(ti(1)),a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Ci=(n,e,t,i)=>{let r=ps.get(e);r||(r=[...e].sort(ti(1)),ps.set(e,r));let s=ps.get(t);s||(s=[...t].sort(ti(1)),ps.set(t,s));let a=Ho.get(n);a||(a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),Ho.set(n,a));let u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},jo=n=>"quality"in n,ys=(n,e,t,i)=>{let r=G(i?.last?.bitrate)&&G(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&qo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=jo(a)?"video":"audio",o=jo(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var io="2.0.140-dev.26e4b860.0";var Se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Se||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(et||{});var Xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Xr||{}),xa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xa||{});var ka=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(ka||{}),Jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Jr||{});import{assertNever as uo,assertNonNullable as al,isNonNullable as Zr,ValueSubject as Aa,Subject as nl,Subscription as ol,merge as ul,observableFrom as dl,fromEvent as so,map as ao,tap as no,filterChanged as ll,isNullable as wa,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var es=class{constructor(e){this.connection$=new Aa(void 0);this.castState$=new Aa("NOT_AVAILABLE");this.errorEvent$=new nl;this.realCastState$=new Aa("NOT_AVAILABLE");this.subscription=new ol;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Zr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||ro("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Zr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(so(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uo(r.sessionState)}})).add(ul(so(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(no(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ao(r=>r.castState)),dl([i.getCastState()])).pipe(ll(),ao(cl),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Zr(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();al(u);let o=u.getCastDevice(),d=u.getMediaSession()?.media?.contentId;(wa(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Zr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:oo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},cl=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(n)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return n},pt=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var A=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as hl,Subject as ts,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new ts;this.transitionEnded$=new ts;this.transitionUpdated$=new ts;this.forceChanged$=new ts;this.stateChangeStarted$=co(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=co(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||hl(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as go}from"@vkontakte/videoplayer-shared/evergreen";var is=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,d=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||d||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Li=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var rs=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Li()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var ss=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var we=()=>window.ManagedMediaSource||window.MediaSource,Yt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),as=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var pl=document.createElement("video"),ml='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fl='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',bl='audio/mp4; codecs="mp4a.40.2"',gl='audio/webm; codecs="opus"',fo,Sl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};Sl().catch(n=>{console.log(pl),console.error(n)});var ns=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return fo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Yt(),mse:ho(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!we()?.isTypeSupported?.(ml),t=!!we()?.isTypeSupported?.(fl),i=!!we()?.isTypeSupported?.(bl);this._codecs={h264:e,h265:t,vp9:!!we()?.isTypeSupported?.(po),av1:!!we()?.isTypeSupported?.(mo),aac:i,opus:!!we()?.isTypeSupported?.(gl),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var bo="audio/mpeg",os=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(bo)},this._codecs={mp3:!!we()?.isTypeSupported?.(bo)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as vl}from"@vkontakte/videoplayer-shared/evergreen";var Pa=class{constructor(){this.isInited$=new vl(!1);this._displayChecker=new ss,this._deviceChecker=new rs(this._displayChecker),this._browserChecker=new is,this._videoChecker=new ns(this._deviceChecker,this._browserChecker),this._audioChecker=new os,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},D=new Pa;var La=n=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return n.filter(u=>{switch(u){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return go(u)}})},$a=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return go(n)}},yl=n=>{let t=Object.keys(n).filter(i=>!$a(i));return La(t).length>0};import{assertNever as Kt,assertNonNullable as $t,debounce as So,ErrorCategory as vo,fromEvent as Mt,isNonNullable as yo,map as To,merge as Io,observableFrom as Tl,Subject as Il,Subscription as Ma,timeout as El,getHighestQuality as xl}from"@vkontakte/videoplayer-shared/evergreen";var kl=5,Al=5,wl=500,Eo=7e3,$i=class{constructor(e){this.subscription=new Ma;this.loadMediaTimeoutSubscription=new Ma;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(e)}break}default:Kt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($a(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Ma;this.subscription.add(e),this.subscription.add(Io(this.videoState.stateChangeStarted$.pipe(To(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(To(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Il;e.add(r.pipe(So(wl)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let u=a.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>kl)&&r.next(u),s=u})),e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,u=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Al&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Kt(a)}}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Io(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Tl(["init"])).pipe(So(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];$t(d);let l=xl(Object.keys(d));$t(l);let p=d[l];$t(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=t[e];$t(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];$t(d),i=ee(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kt(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(o)&&(a.metadata.subtitle=o),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(El(Eo).subscribe(()=>s(`timeout(${Eo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:vo.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ko}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Pl}from"@vkontakte/videoplayer-shared/evergreen";var xo=n=>{try{n.pause(),n.playbackRate=0,Pl(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Ll,Subscription as $l}from"@vkontakte/videoplayer-shared/evergreen";var Ra=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Da=window.WeakMap?new WeakMap:new Ra,Ba=window.WeakMap?new WeakMap:new Map,Ml=(n,e=20)=>{let t=0;return Ll(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ve=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?ko(i):(i=document.createElement("video"),n.appendChild(i)),Da.set(i,r);let s=new $l;return s.add(Ml(i,e)),Ba.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ye=n=>{Ba.get(n)?.unsubscribe(),Ba.delete(n);let t=Da.get(n);Da.delete(n),t?ko(n):xo(n)};import{assertNonNullable as Ri,isNonNullable as We,isNullable as Bl,fromEvent as Xt,merge as Ao,observableFrom as wo,filterChanged as Po,map as Di,Subject as Lo,Subscription as Vl,ValueSubject as Cl,ErrorCategory as Ol}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Va,isNullable as Rl,Subscription as Dl}from"@vkontakte/videoplayer-shared/evergreen";var us=(n,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=n.getState(),u=e(),o=Rl(r),d=new Dl;return r&&d.add(r.subscribe(l=>{let p=n.getState();i(l,p)&&n.setState(l)},s)),i(u,a)||(t(a),o&&n.setState(a)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),o&&n.setState(l.to)},s)),d},ze=(n,e,t)=>us(e,()=>n.loop,i=>{Va(i)&&(n.loop=i)},{onError:t}),Te=(n,e,t,i)=>us(e,()=>({muted:n.muted,volume:n.volume}),r=>{Va(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(n,e,t,i)=>us(e,()=>n.playbackRate,r=>{Va(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Mi=us;var Fl=n=>["__",n.language,n.label].join("|"),_l=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Ca=class n{constructor(e){this.available$=new Lo;this.current$=new Cl(void 0);this.error$=new Lo;this.subscription=new Vl;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Ol.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Mi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Mi(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Mi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ri(this.video);let{textTracks:e}=this.video;this.subscription.add(Xt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ao(Xt(e,"addtrack"),Xt(e,"removetrack"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Po((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Ao(Xt(e,"change"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Di(i=>i&&this.htmlTextTrackToITextTrack(i).id),Po()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Xt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Xt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;We(t.align)&&(r.align=t.align),We(t.position)&&(r.position=t.position),We(t.size)&&(r.size=t.size),We(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Fl(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Bl(e)||!_l(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ri(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ri(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=Ca;var Rt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var $o=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Oa=n=>{let e=$o(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Mo=n=>{let e=$o(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as me,map as Ge,merge as ds,filterChanged as Do,isNonNullable as Bo,Subject as Ul,filter as Fa,mapTo as _a,combine as Hl,once as jl,shareReplay as fe,throttle as Ql,ErrorCategory as ql,ValueSubject as Vo,Subscription as zl}from"@vkontakte/videoplayer-shared/evergreen";var Nl=3,Ro=(n,e,t=Nl)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),u=n.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)n.end(o)+t>=i&&(i=n.start(o));for(let o=s+1;o<n.length;o++)n.start(o)-t<=r&&(r=n.end(o))}}return{from:i,to:r}};var Ie=n=>{let e=y=>me(n,y).pipe(_a(void 0),fe(1)),t=new zl,i=()=>t.unsubscribe(),r=ds(me(n,"progress"),me(n,"timeupdate")).pipe(Ge(()=>Ro(n.buffered,n.currentTime)),fe(1)),s=D.browser.isSafari?Hl({play:e("play").pipe(jl()),playing:e("playing")}).pipe(_a(void 0),fe(1)):e("playing"),a=me(n,"volumechange").pipe(Ge(()=>({muted:n.muted,volume:n.volume})),fe(1)),u=me(n,"ratechange").pipe(Ge(()=>n.playbackRate),fe(1)),o=me(n,"error").pipe(Fa(()=>!!(n.error||n.played.length)),Ge(()=>{let y=n.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:ql.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:n.error??void 0}}),fe(1)),d=me(n,"timeupdate").pipe(Ge(()=>n.currentTime),fe(1)),l=["waiting","seeking","seeked","timeupdate"],p=new Ul,c=.3,h;t.add(ds(...l.map(y=>me(n,y))).subscribe(y=>{let _=n.currentTime;n.loop&&Bo(h)&&Bo(_)&&h>=n.duration-c&&_<=c&&p.next(h),h=_}));let m=e("pause").pipe(Fa(()=>!n.error&&h!==n.duration),fe(1)),f=me(n,"enterpictureinpicture").pipe(fe(1)),b=me(n,"leavepictureinpicture").pipe(fe(1)),g=new Vo(Mo(n));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let E=new Vo(Oa(n)),I=me(n,"fullscreenchange").pipe(fe(1));t.add(I.pipe(Ge(()=>Oa(n))).subscribe(E));let v=.1,x=1e3,R=me(n,"timeupdate").pipe(Ge(y=>n.duration-n.currentTime<v),Do(),fe(1)),L=ds(R.pipe(Fa(y=>!n.loop&&y)),me(n,"ended")).pipe(Ql(x),_a(void 0),fe(1)),P=ds(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>me(n,y)),R.pipe(Ge(y=>({type:y?"ended":"unknown"})))).pipe(Ge(y=>D.browser.isFirefox&&y.type==="ended"?n.readyState<2:n.readyState<3),Do(),fe(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:me(n,"durationchange").pipe(Ge(()=>n.duration),fe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:E,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=n=>{switch(n){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as G,isNullable as ms,now as qo,isHigher as fs,isHigherOrEqual as Zt,isInvariantQuality as bs,isLowerOrEqual as ei,videoSizeToQuality as zo,assertNotEmptyArray as gs,assertNonNullable as Wo}from"@vkontakte/videoplayer-shared/evergreen";var Na=!1,it={},Co=n=>{Na=n},Oo=()=>{it={}},Fo=n=>{n(it)},Bi=(n,e)=>{Na&&(it.meta=it.meta??{},it.meta[n]=e)},be=class{constructor(e){this.name=e}next(e){if(!Na)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Wl,isHigherOrEqual as Fb,isLower as _o,isLowerOrEqual as _b,isNonNullable as ls,isNullable as Gl,videoHeightToQuality as cs}from"@vkontakte/videoplayer-shared/evergreen";function Ua(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function hs(n,e,t){return!!n&&Ua(n,e,t)==="high_quality"}function Jt(n,e,t){return Gl(n)||ls(n.min)&&ls(n.max)&&_o(n.max,n.min)||ls(n.min)&&e&&Wl(n.min,e)||ls(n.max)&&t&&_o(n.max,t)}function No({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({max:n?.max?cs(n.max):void 0,min:n?.min?cs(n.min):void 0},e?cs(e):void 0,t?cs(t):void 0)}var Go=new be("best_bitrate"),Ss=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var ti=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vs='Assertion "ABR Tracks is empty array" failed',ps=new WeakMap,Uo=new WeakMap,Ho=new WeakMap,Vi=(n,e,t,i)=>{let r=[...e].sort(ti(1)),s=[...t].sort(ti(1)),a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Ci=(n,e,t,i)=>{let r=ps.get(e);r||(r=[...e].sort(ti(1)),ps.set(e,r));let s=ps.get(t);s||(s=[...t].sort(ti(1)),ps.set(t,s));let a=Ho.get(n);a||(a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),Ho.set(n,a));let u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},jo=n=>"quality"in n,ys=(n,e,t,i)=>{let r=G(i?.last?.bitrate)&&G(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&qo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=jo(a)?"video":"audio",o=jo(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${u} selected] ${o}
|
|
8
8
|
`}),a}return i?.recordSwitch(t),t},Yl=(n,e)=>Math.log(e)/Math.log(n),Yo=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&D.display.pixelRatio){let s=D.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[u=0,o=0,d=0]=n.pixelRatioLogCoefficients,l=Yl(a,u*s+o)+d;Number.isFinite(l)&&(r*=l)}}return hs(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Qo=new WeakMap,Ye=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:o,history:d,visible:l,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{gs(n,vs);let{containerSizeFactor:b,containerSizeLimit:g}=Yo({container:e,tuning:i,limits:r,panelSize:f}),E=i.considerPlaybackRate&&G(u)?u:1,I=Qo.get(n);I||(I=n.filter(S=>!bs(S.quality)).sort((S,T)=>fs(S.quality,T.quality)?-1:1),Qo.set(n,I));let v=I.at(-1)?.quality,x=I.at(0)?.quality,R=Jt(r,x,v),L=E*Ss(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},P=null;for(let S of I){let T=!0;if(g)if(S.size)T=S.size.width<=g.width&&S.size.height<=g.height;else{let H=g&&zo(g);T=H?ei(S.quality,H):!0}if(!T){k[S.quality]="FitsContainer";continue}let z=h||t,M=G(z)&&isFinite(z)&&G(S.bitrate)?z-s>=S.bitrate*L:!0,U=hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===S.quality;if(!M&&!U){k[S.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&o&&!bs(o.quality)&&(a??0)<i.minBufferToSwitchUp&&fs(S.quality,o.quality)){k[S.quality]="Buffer";continue}if(!!p&&Zt(S.quality,p)&&!U){k[S.quality]="DroppedFramesLimit";continue}if(!!c&&Zt(S.quality,c)&&!U){k[S.quality]="StallsLimit";continue}let ne=R||(ms(r?.max)||ei(S.quality,r.max))&&(ms(r?.min)||Zt(S.quality,r.min)),oe=G(l)&&!l?ei(S.quality,i.backgroundVideoQualityLimit):!0;if(!ne||!oe){k[S.quality]="FitsQualityLimits";continue}P||(P=S)}P&&P.bitrate&&Go.next(P.bitrate);let y=P??I.at(-1)??n[0],_=d?.last,$=ys(i,m,y,d);return G(d)&&$.quality!==_?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
@@ -120,7 +120,7 @@ var io="2.0.139";var Se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="play
|
|
|
120
120
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
121
121
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
122
122
|
(?:-(?<privateuse>(?:${e})))?
|
|
123
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var Iu=n=>{if(!n?.startsWith("P"))return;let e=(a,u)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(u,o)=>Tu(s)?u:Tu(o)?s:s.padStart(parseInt(o,10),"0"))}return t},$s=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(P=>P.textContent?.trim()??""),u=a.at(0)??"",o=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],c=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:d?new Date(d).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,E=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],v=I.reduce((P,y)=>({...P,[y.id]:y.children}),{}),x=I.reduce((P,y)=>({...P,[y.id]:y.getAttribute("duration")}),{});E?g=Iu(E):Object.values(x).filter(P=>P).length&&!o?g=Object.values(x).reduce((P,y)=>P+(Iu(y)??0),0):f&&(g=parseInt(f,10));let R=0,L=s.getAttribute("profiles")?.split(",")??[];for(let P of I.map(y=>y.id))for(let y of v[P]){let _=y.getAttribute("id")??"id"+(R++).toString(10),$=y.getAttribute("mimeType")??"",S=y.getAttribute("codecs")??"",T=y.getAttribute("contentType")??$?.split("/")[0],z=y.getAttribute("profiles")?.split(",")??[],M=yu(y.getAttribute("lang")??"")??{},U=y.querySelector("Label")?.textContent?.trim()??void 0,Y=y.querySelectorAll("Representation"),Z=y.querySelector("SegmentTemplate"),ie=y.querySelector("Role")?.getAttribute("value")??void 0,ne=T,oe={id:_,language:M.language,isDefault:ie==="main",label:U,codecs:S,hdr:ne==="video"&&Ka(S),mime:$,representations:[]};for(let H of Y){let N=H.getAttribute("lang")??void 0,ge=U??y.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(he||u,e).toString(),Me=H.getAttribute("mimeType")??$,dt=H.getAttribute("codecs")??S??"",He;if(T==="text"){let Ae=H.getAttribute("id")||"",lt=M.privateuse?.includes("x-auto")||Ae.includes("_auto"),je=H.querySelector("SegmentTemplate");if(je){let ki={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=parseInt(je.getAttribute("startNumber")??"",10)??1,jt=parseInt(je.getAttribute("timescale")??"",10),Ia=je.querySelectorAll("SegmentTimeline S")??[],Qt=je.getAttribute("media");if(!Qt)continue;let qr=[],zr=0,Wr="",qt=0,Ai=Qr,pe=0;for(let Ce of Ia){let wt=parseInt(Ce.getAttribute("d")??"",10),Re=parseInt(Ce.getAttribute("r")??"",10)||0,ct=parseInt(Ce.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let Pt=wt/jt*1e3,zt=pe/jt*1e3;for(let Qe=0;Qe<Re+1;Qe++){let ht=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:(pe+Qe*wt).toString(10)}),Wt=(zt??0)+Qe*Pt,Pi=Wt+Pt;Ai++,qr.push({time:{from:Wt,to:Pi},url:ht})}pe+=(Re+1)*wt,zr+=(Re+1)*Pt}qt=pe/jt*1e3,Wr=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:pe.toString(10)});let wi={time:{from:qt,to:1/0},url:Wr},Ze={type:"template",baseUrl:re,segmentTemplateUrl:Qt,initUrl:"",totalSegmentsDurationMs:zr,segments:qr,nextSegmentBeyondManifest:wi,timescale:jt};He={id:Ae,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:jr,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else He={id:Ae,isAuto:lt,kind:"text",url:re}}else{let Ae=H.getAttribute("contentType")??Me?.split("/")[0]??T,lt=y.getAttribute("profiles")?.split(",")??[],je=parseInt(H.getAttribute("width")??"",10),ki=parseInt(H.getAttribute("height")??"",10),jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=H.getAttribute("frameRate")??"",jt=H.getAttribute("quality")??void 0,Ia=Qr?vu(Qr):void 0,Qt=H.getAttribute("id")??"id"+(R++).toString(10),qr=Ae==="video"?`${ki}p`:Ae==="audio"?`${jr}Kbps`:dt,zr=`${Qt}@${qr}`,Wr=[...L,...z,...lt],qt,Ai=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(Ai){let Ze=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ce,wt]=Ze.split("-").map(ht=>parseInt(ht,10)),Re={from:Ce,to:wt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Pt,zt]=ct?ct.split("-").map(ht=>parseInt(ht,10)):[],Qe=ct?{from:Pt,to:zt}:void 0;qt={type:"byteRange",url:re,initRange:Re,indexRange:Qe}}else if(pe){let Ze={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ce=parseInt(pe.getAttribute("timescale")??"",10),wt=pe.getAttribute("initialization")??"",Re=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,Pt=_e(wt,Ze);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let zt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],ht=0,Wt="",Pi=0;if(zt.length){let Gr=ct,Oe=0;for(let Gt of zt){let qe=parseInt(Gt.getAttribute("d")??"",10),Lt=parseInt(Gt.getAttribute("r")??"",10)||0,Yr=parseInt(Gt.getAttribute("t")??"",10);Oe=Number.isFinite(Yr)?Yr:Oe;let Ea=qe/Ce*1e3,il=Oe/Ce*1e3;for(let Kr=0;Kr<Lt+1;Kr++){let rl=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:(Oe+Kr*qe).toString(10)}),to=(il??0)+Kr*Ea,sl=to+Ea;Gr++,Qe.push({time:{from:to,to:sl},url:rl})}Oe+=(Lt+1)*qe,ht+=(Lt+1)*Ea}Pi=Oe/Ce*1e3,Wt=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:Oe.toString(10)})}else if(Wc(g)){let Oe=parseInt(pe.getAttribute("duration")??"",10)/Ce*1e3,Gt=Math.ceil(g/Oe),qe=0;for(let Lt=1;Lt<Gt;Lt++){let Yr=_e(Re,{...Ze,segmentNumber:Lt.toString(10),segmentTime:qe.toString(10)});Qe.push({time:{from:qe,to:qe+Oe},url:Yr}),qe+=Oe}Pi=qe,Wt=_e(Re,{...Ze,segmentNumber:Gt.toString(10),segmentTime:qe.toString(10)})}let tl={time:{from:Pi,to:1/0},url:Wt};qt={type:"template",baseUrl:re,segmentTemplateUrl:Re,initUrl:Pt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:tl,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ae||!Me)continue;let wi={video:"video",audio:"audio",text:"text"}[Ae];if(!wi)continue;ne||=wi,He={id:zr,kind:wi,segmentReference:qt,profiles:Wr,duration:g,bitrate:jr,mime:Me,codecs:dt,width:je,height:ki,fps:Ia,quality:jt}}oe.language||=N,oe.label||=ge,oe.mime||=Me,oe.codecs||=dt,oe.hdr||=ne==="video"&&Ka(dt),oe.representations.push(He)}if(ne){let H=r[ne].find(N=>N.id===oe.id);if(H&&oe.representations.every(N=>N.segmentReference.type==="template"))for(let N of H.representations){let he=oe.representations.find(Me=>Me.id===N.id)?.segmentReference,re=N.segmentReference;re.segments.push(...he.segments),re.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Gc}from"@vkontakte/videoplayer-shared/evergreen";var Eu=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Gc({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},xu=({id:n,bitrate:e})=>({id:n,bitrate:e}),ku=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Au=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Xa=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ja=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Za=n=>"url"in n,Pe=n=>n.type==="template";import{isNonNullable as wu}from"@vkontakte/videoplayer-shared/evergreen";var B=(n,e)=>wu(n)&&wu(e)&&n.readyState==="open"&&Yc(n,e);function Yc(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var fr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Vt(0);this.currentLowLatencySegmentLength$=new Vt(0);this.currentSegmentLength$=new Vt(0);this.onLastSegment$=new Vt(!1);this.fullyBuffered$=new Vt(!1);this.playingRepresentation$=new Vt(void 0);this.playingRepresentationInit$=new Vt(void 0);this.error$=new Xc;this.gaps=[];this.subscription=new Jc;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=St(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cu(this.sourceBuffer),this.subscription.add(en(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(en(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:st.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,si(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let d=this.getForwardBufferDuration(u),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<l).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();ui(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();ui(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=St(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let d=t.find(c=>c.id===o);d&&this.representations.set(o,d);let l=this.representations.get(o);if(!l||!Pe(l.segmentReference))return;let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!d?.live,this.baseUrls=d?.baseUrls??[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,St(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(le(u)||le(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),xe(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();ui(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!le(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);ui(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+a&&(s=p)}if(isFinite(this.bufferLimit)&&si(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ui(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Pe(r))return;let s=this.segments.get(i.id)??[],a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),d=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,g=h>i||b||f===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+E||r<E&&m-h>=E||m<=i+E;return(c==="none"||c==="partially_ejected"&&g&&I&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(de(this.sourceBuffer.buffered,h)&&de(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,d=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=l||o<=p);c++){let h=a[c];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")d.push(h);else break}return d}async loadSegments(e,t,i="auto"){Pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:o,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await St(u,async function*(){let l=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,l))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ms(),!l)return;let p=new DataView(l),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(p,f)}o&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xe(l)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await St(a,async function*(){let o=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,o),en(window,"online").pipe(Kc()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ms(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Pe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms();let p=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=Ke(a.mime).parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(o.status="partially_fed",u.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:d}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let l=d.byte.from-i,p=d.byte.to-i,c=p-l+1,h=l<r,m=p<=r;if(!h)continue;let f=Ke(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,c);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-l),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===c?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(d.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(de(this.sourceBuffer.buffered,e.segment.time.from,100)&&de(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:st.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Za(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?St(this.destroyAbortController.signal,async function*(){let u=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let c=l;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:st.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||le(e))return!1;let r=[],s=0,a=o=>{o.sort((l,p)=>l.from-p.from);let d=[o[0]];for(let l=1;l<o.length;l++){let{from:p,to:c}=o[l],h=d[d.length-1];h.to>=p?h.to=Math.max(h.to,c):d.push(o[l])}return d},u=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let d=Za(o)?o.size??0:o.byte.to-o.byte.from;s+=d};for(let o of this.segments.values())for(let d of o){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&d.status==="fed"&&u(d)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let d=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let h of c)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:d,to:l},url:"",status:"none"};u(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+o&&l.status==="fed"&&u(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||le(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(l=>l.from-t<=a&&l.to+t>=u),d=e.filter(l=>a>=l.from&&a<l.to-t||u>l.from+t&&u<=l.to);o||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:st.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var vt=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Rs=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as br,assertNever as Pu,fromEvent as Lu,merge as Zc,now as gr,Subscription as eh,Subject as di,ValueSubject as rn,flattenObject as li,ErrorCategory as Sr}from"@vkontakte/videoplayer-shared/evergreen";var Ds=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Vs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new di;this.manifestReceived=new di;this.firstBytesRequested=new di;this.firstBytesReceived=new di;this.lastConnectionType$=new rn(void 0);this.lastConnectionReused$=new rn(void 0);this.lastRequestFirstBytes$=new rn(void 0);this.recoverableError$=new di;this.error$=new di;this.abortAllController=new AbortController;this.subscription=new eh;this.fetchManifest=br(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ds(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Bs);return r?(t.log("success",li({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",li({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=br(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:d=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),l=S.toString();break}default:Pu(t)}this.requestQuic&&(l=vt(l));let h=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Zc(Lu(this.abortAllController.signal,"abort"),Lu(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){Bs(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){Bs(T)}h=S.signal}let f=0,b=gr();c.log("startRequest",li({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(l,{priority:s,headers:p,signal:h}),E=gr();if(!g)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(E-b),!g.ok||!g.body){m?.unsubscribe();let S=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){m?.unsubscribe();let S=gr(),T={requestStartedAt:b,requestEndedAt:S,duration:S-b};return c.log("endRequest",li(T)),c.end(),g.arrayBuffer()}let I=g.body;if(u){let S;[I,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=I.getReader(),x,R=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(R)&&(x=R),!x&&i&&(x=i.to-i.from+1);let L=x?new Uint8Array(x):new Uint8Array(0),k=!1,P=S=>{m?.unsubscribe(),k=!0,Bs(S)},y=br(h,async function*({done:S,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(gr()-b),this.firstBytesReceived.next()),h.aborted){m?.unsubscribe();return}if(!S&&T){if(d&&x)L.set(T,f),f+=T.byteLength;else{let z=new Uint8Array(L.length+T.length);z.set(L),z.set(T,L.length),L=z,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(y,P)}}.bind(this));yield v?.read().then(y,P),m?.unsubscribe();let _=gr(),$={failed:k,requestStartedAt:b,requestEndedAt:_,duration:_-b};return k?(c.error("endRequest",li($)),c.end(),null):(c.log("endRequest",li($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=br(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,o=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,o=s+1===d,o&&(a=Math.min(d,r),u=Math.max(l,s))),a=Math.min(a,0);let p=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!p)return null;let c=new DataView(p,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(p,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(p),segments:b}}.bind(this));this.fetchTemplateRepresentation=br(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Pu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Sr.FATAL})}}},Bs=n=>{if(!Xe(n))throw n};var at=(n,e,t)=>t*e+(1-t)*n,sn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,$u=(n,e,t,i)=>{let r=0,s=t,a=sn(n,e),u=e<i?e:i;for(let o=0;o<u;o++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===u};import{isNullable as th,ValueSubject as Mu}from"@vkontakte/videoplayer-shared/evergreen";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mu(e.initial),this.debounced$=new Mu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(th(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Cs=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=at(this.slow,e,this.params.emaAlphaSlow),this.fast=at(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Os=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=sn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=$u(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Fs=class extends yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?at(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Os({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Fs({initial:e,label:"liveEdgeDelay",...t})}};var ci=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as ih,ValueSubject as rh}from"@vkontakte/videoplayer-shared/evergreen";var vr=class n{constructor(e,t){this.currentRepresentation$=new rh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!ih(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let o=r.segments.find(d=>d.time.from<=e&&d.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};import{assertNever as Ns}from"@vkontakte/videoplayer-shared/evergreen";var _s=n=>{let{webmDecodingInfo:e}=D.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Ns(n)}return[t,i]},Ru=({webmCodec:n,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],..._s(n),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(D.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",..._s(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(n),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(n),...s,"HLS","HLS_ONDEMAND"];default:Ns(e)}if(D.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Ns(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Du=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],u,o=D.device.isMac&&D.browser.isSafari;if(D.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=a;break}default:Ns(n)}else D.video.nativeHlsSupported&&!o?u=a:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},an=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Us=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)},Hs=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return oh().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},js=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return uh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=n=>n.split(".")[0].replace("0",""),oh=()=>["av1","vp9","hev1","avc1"],uh=()=>["opus","mp4a"];var mh=["timeupdate","progress","play","seeked","stalled","waiting"],fh=["timeupdate","progress","loadeddata","playing","seeked"];var qs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cu;this.representationSubscription=new Cu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Tt;this.manifestRequested=new Tt;this.manifestReceived=new Tt;this.firstBytesRequested=new Tt;this.firstBytesReceived=new Tt;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Tt;this.fetcherError$=new Tt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=on(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ne.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=$s(e??"",this.manifestUrlString)}catch(o){let d=Ps(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(d)}if(!t)return null;let i=(o,d,l)=>!!(this.element?.canPlayType?.(d)&&we()?.isTypeSupported?.(`${d}; codecs="${l}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:d,streamIsUnpublished:l,streamIsAlive:p}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((d-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=l?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:h})=>h);o==="audio"&&(a=js(c),p=a[0]),o==="video"&&(s=Hs(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=l.filter(({codecs:h})=>hi(h)===p))}else{let c=new Set(l.map(({codecs:h})=>h));p=Us(c),p&&(r[o]=l.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&h?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Tr(u)),u}.bind(this));this.initRepresentations=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Tr({initialVideo:e,initialAudio:t,sourceHls:i})),pi(this.manifest),pi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(ot(c,"error").pipe(Qs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=as();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Yt())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new fr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Ir(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new fr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}vr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new vr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ct(...fh.map(c=>ot(this.element,c))).pipe(fi(c=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),yr(),hh(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ct(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(yr()).subscribe(h=>this.liveStreamEndTimestamp=dn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=un(1e3).subscribe(h=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(mi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fi(({isActiveLive:h,isLowLatency:m})=>h&&m),yr()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ci(this.element,1)})),this.representationSubscription.add(mi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qs(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(mi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qs(({isLive:h})=>h),yr((h,m)=>m.bufferLength<h.bufferLength),fi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(mi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*E),ci(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(mi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ph(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(R?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+v&&(k="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=c-(E+I),y=this.normolizeLiveOffset(Math.trunc(b+P/f)),_=Math.abs(y-b),$=0;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?$=b:y>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&($=y),this.manifestUrlString=ee(this.manifestUrlString,$,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let d=Ct(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(fi(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Ct(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(fi(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=mi({allBuffersFull:d,someBufferEnded:l}).pipe(yr(),fi(({allBuffersFull:c,someBufferEnded:h})=>c&&h),Qs(c=>c));if(this.representationSubscription.add(Ct(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ct(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Pe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Ir(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=un(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Vs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){pi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?dn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){pi(this.element),this.state$.setState("running"),this.subscription.add(Ct(...mh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&de(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=dn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,l=o<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",Tr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=un(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){pi(this.element),pi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),de(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Vu(this.element)||Vu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Tr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ir(this.element)&&Ir(this.source)&&Ir(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=ch(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-a<=r&&o.to+a>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Tr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var zs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ws=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Fu=`attribute vec2 a_vertex;
|
|
123
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var Iu=n=>{if(!n?.startsWith("P"))return;let e=(a,u)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(u,o)=>Tu(s)?u:Tu(o)?s:s.padStart(parseInt(o,10),"0"))}return t},$s=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(P=>P.textContent?.trim()??""),u=a.at(0)??"",o=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],c=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:d?new Date(d).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,E=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],v=I.reduce((P,y)=>({...P,[y.id]:y.children}),{}),x=I.reduce((P,y)=>({...P,[y.id]:y.getAttribute("duration")}),{});E?g=Iu(E):Object.values(x).filter(P=>P).length&&!o?g=Object.values(x).reduce((P,y)=>P+(Iu(y)??0),0):f&&(g=parseInt(f,10));let R=0,L=s.getAttribute("profiles")?.split(",")??[];for(let P of I.map(y=>y.id))for(let y of v[P]){let _=y.getAttribute("id")??"id"+(R++).toString(10),$=y.getAttribute("mimeType")??"",S=y.getAttribute("codecs")??"",T=y.getAttribute("contentType")??$?.split("/")[0],z=y.getAttribute("profiles")?.split(",")??[],M=yu(y.getAttribute("lang")??"")??{},U=y.querySelector("Label")?.textContent?.trim()??void 0,Y=y.querySelectorAll("Representation"),Z=y.querySelector("SegmentTemplate"),ie=y.querySelector("Role")?.getAttribute("value")??void 0,ne=T,oe={id:_,language:M.language,isDefault:ie==="main",label:U,codecs:S,hdr:ne==="video"&&Ka(S),mime:$,representations:[]};for(let H of Y){let N=H.getAttribute("lang")??void 0,ge=U??y.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(he||u,e).toString(),Me=H.getAttribute("mimeType")??$,dt=H.getAttribute("codecs")??S??"",He;if(T==="text"){let Ae=H.getAttribute("id")||"",lt=M.privateuse?.includes("x-auto")||Ae.includes("_auto"),je=H.querySelector("SegmentTemplate");if(je){let ki={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=parseInt(je.getAttribute("startNumber")??"",10)??1,jt=parseInt(je.getAttribute("timescale")??"",10),Ia=je.querySelectorAll("SegmentTimeline S")??[],Qt=je.getAttribute("media");if(!Qt)continue;let qr=[],zr=0,Wr="",qt=0,Ai=Qr,pe=0;for(let Ce of Ia){let wt=parseInt(Ce.getAttribute("d")??"",10),Re=parseInt(Ce.getAttribute("r")??"",10)||0,ct=parseInt(Ce.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let Pt=wt/jt*1e3,zt=pe/jt*1e3;for(let Qe=0;Qe<Re+1;Qe++){let ht=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:(pe+Qe*wt).toString(10)}),Wt=(zt??0)+Qe*Pt,Pi=Wt+Pt;Ai++,qr.push({time:{from:Wt,to:Pi},url:ht})}pe+=(Re+1)*wt,zr+=(Re+1)*Pt}qt=pe/jt*1e3,Wr=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:pe.toString(10)});let wi={time:{from:qt,to:1/0},url:Wr},Ze={type:"template",baseUrl:re,segmentTemplateUrl:Qt,initUrl:"",totalSegmentsDurationMs:zr,segments:qr,nextSegmentBeyondManifest:wi,timescale:jt};He={id:Ae,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:jr,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else He={id:Ae,isAuto:lt,kind:"text",url:re}}else{let Ae=H.getAttribute("contentType")??Me?.split("/")[0]??T,lt=y.getAttribute("profiles")?.split(",")??[],je=parseInt(H.getAttribute("width")??"",10),ki=parseInt(H.getAttribute("height")??"",10),jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=H.getAttribute("frameRate")??"",jt=H.getAttribute("quality")??void 0,Ia=Qr?vu(Qr):void 0,Qt=H.getAttribute("id")??"id"+(R++).toString(10),qr=Ae==="video"?`${ki}p`:Ae==="audio"?`${jr}Kbps`:dt,zr=`${Qt}@${qr}`,Wr=[...L,...z,...lt],qt,Ai=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(Ai){let Ze=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ce,wt]=Ze.split("-").map(ht=>parseInt(ht,10)),Re={from:Ce,to:wt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Pt,zt]=ct?ct.split("-").map(ht=>parseInt(ht,10)):[],Qe=ct?{from:Pt,to:zt}:void 0;qt={type:"byteRange",url:re,initRange:Re,indexRange:Qe}}else if(pe){let Ze={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ce=parseInt(pe.getAttribute("timescale")??"",10),wt=pe.getAttribute("initialization")??"",Re=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,Pt=_e(wt,Ze);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let zt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],ht=0,Wt="",Pi=0;if(zt.length){let Gr=ct,Oe=0;for(let Gt of zt){let qe=parseInt(Gt.getAttribute("d")??"",10),Lt=parseInt(Gt.getAttribute("r")??"",10)||0,Yr=parseInt(Gt.getAttribute("t")??"",10);Oe=Number.isFinite(Yr)?Yr:Oe;let Ea=qe/Ce*1e3,il=Oe/Ce*1e3;for(let Kr=0;Kr<Lt+1;Kr++){let rl=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:(Oe+Kr*qe).toString(10)}),to=(il??0)+Kr*Ea,sl=to+Ea;Gr++,Qe.push({time:{from:to,to:sl},url:rl})}Oe+=(Lt+1)*qe,ht+=(Lt+1)*Ea}Pi=Oe/Ce*1e3,Wt=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:Oe.toString(10)})}else if(Wc(g)){let Oe=parseInt(pe.getAttribute("duration")??"",10)/Ce*1e3,Gt=Math.ceil(g/Oe),qe=0;for(let Lt=1;Lt<Gt;Lt++){let Yr=_e(Re,{...Ze,segmentNumber:Lt.toString(10),segmentTime:qe.toString(10)});Qe.push({time:{from:qe,to:qe+Oe},url:Yr}),qe+=Oe}Pi=qe,Wt=_e(Re,{...Ze,segmentNumber:Gt.toString(10),segmentTime:qe.toString(10)})}let tl={time:{from:Pi,to:1/0},url:Wt};qt={type:"template",baseUrl:re,segmentTemplateUrl:Re,initUrl:Pt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:tl,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ae||!Me)continue;let wi={video:"video",audio:"audio",text:"text"}[Ae];if(!wi)continue;ne||=wi,He={id:zr,kind:wi,segmentReference:qt,profiles:Wr,duration:g,bitrate:jr,mime:Me,codecs:dt,width:je,height:ki,fps:Ia,quality:jt}}oe.language||=N,oe.label||=ge,oe.mime||=Me,oe.codecs||=dt,oe.hdr||=ne==="video"&&Ka(dt),oe.representations.push(He)}if(ne){let H=r[ne].find(N=>N.id===oe.id);if(H&&oe.representations.every(N=>N.segmentReference.type==="template"))for(let N of H.representations){let he=oe.representations.find(Me=>Me.id===N.id)?.segmentReference,re=N.segmentReference;re.segments.push(...he.segments),re.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Gc}from"@vkontakte/videoplayer-shared/evergreen";var Eu=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Gc({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},xu=({id:n,bitrate:e})=>({id:n,bitrate:e}),ku=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Au=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Xa=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ja=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Za=n=>"url"in n,Pe=n=>n.type==="template";import{isNonNullable as wu}from"@vkontakte/videoplayer-shared/evergreen";var B=(n,e)=>wu(n)&&wu(e)&&n.readyState==="open"&&Yc(n,e);function Yc(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var fr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Vt(0);this.currentLowLatencySegmentLength$=new Vt(0);this.currentSegmentLength$=new Vt(0);this.onLastSegment$=new Vt(!1);this.fullyBuffered$=new Vt(!1);this.playingRepresentation$=new Vt(void 0);this.playingRepresentationInit$=new Vt(void 0);this.error$=new Xc;this.gaps=[];this.subscription=new Jc;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=St(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cu(this.sourceBuffer),this.subscription.add(en(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(en(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:st.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,si(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let d=this.getForwardBufferDuration(u),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<l).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();ui(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();ui(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=St(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let d=t.find(c=>c.id===o);d&&this.representations.set(o,d);let l=this.representations.get(o);if(!l||!Pe(l.segmentReference))return;let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!d?.live,this.baseUrls=d?.baseUrls??[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,St(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(le(u)||le(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),xe(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();ui(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!le(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);ui(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+a&&(s=p)}if(isFinite(this.bufferLimit)&&si(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ui(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Pe(r))return;let s=this.segments.get(i.id)??[],a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),d=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,g=h>i||b||f===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+E||r<E&&m-h>=E||m<=i+E;return(c==="none"||c==="partially_ejected"&&g&&I&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(de(this.sourceBuffer.buffered,h)&&de(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,d=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=l||o<=p);c++){let h=a[c];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")d.push(h);else break}return d}async loadSegments(e,t,i="auto"){Pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:o,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await St(u,async function*(){let l=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,l))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ms(),!l)return;let p=new DataView(l),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(p,f)}o&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xe(l)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await St(a,async function*(){let o=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,o),en(window,"online").pipe(Kc()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ms(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Pe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms();let p=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=Ke(a.mime).parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(o.status="partially_fed",u.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:d}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let l=d.byte.from-i,p=d.byte.to-i,c=p-l+1,h=l<r,m=p<=r;if(!h)continue;let f=Ke(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,c);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-l),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===c?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(d.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(de(this.sourceBuffer.buffered,e.segment.time.from,100)&&de(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:st.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Za(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?St(this.destroyAbortController.signal,async function*(){let u=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let c=l;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:st.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||le(e))return!1;let r=[],s=0,a=o=>{o.sort((l,p)=>l.from-p.from);let d=[o[0]];for(let l=1;l<o.length;l++){let{from:p,to:c}=o[l],h=d[d.length-1];h.to>=p?h.to=Math.max(h.to,c):d.push(o[l])}return d},u=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let d=Za(o)?o.size??0:o.byte.to-o.byte.from;s+=d};for(let o of this.segments.values())for(let d of o){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&d.status==="fed"&&u(d)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let d=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let h of c)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:d,to:l},url:"",status:"none"};u(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+o&&l.status==="fed"&&u(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||le(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(l=>l.from-t<=a&&l.to+t>=u),d=e.filter(l=>a>=l.from&&a<l.to-t||u>l.from+t&&u<=l.to);o||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:st.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var vt=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Rs=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as br,assertNever as Pu,fromEvent as Lu,merge as Zc,now as gr,Subject as di,ValueSubject as rn,flattenObject as li,ErrorCategory as Sr,SubscriptionRemovable as eh}from"@vkontakte/videoplayer-shared/evergreen";var Ds=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Vs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new di;this.manifestReceived=new di;this.firstBytesRequested=new di;this.firstBytesReceived=new di;this.lastConnectionType$=new rn(void 0);this.lastConnectionReused$=new rn(void 0);this.lastRequestFirstBytes$=new rn(void 0);this.recoverableError$=new di;this.error$=new di;this.abortAllController=new AbortController;this.subscription=new eh;this.fetchManifest=br(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ds(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Bs);return r?(t.log("success",li({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",li({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=br(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:d=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),l=S.toString();break}default:Pu(t)}this.requestQuic&&(l=vt(l));let h=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Zc(Lu(this.abortAllController.signal,"abort"),Lu(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){Bs(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){Bs(T)}h=S.signal}let f=0,b=gr();c.log("startRequest",li({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(l,{priority:s,headers:p,signal:h}),E=gr();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(E-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=gr(),T={requestStartedAt:b,requestEndedAt:S,duration:S-b};return c.log("endRequest",li(T)),c.end(),g.arrayBuffer()}let I=g.body;if(u){let S;[I,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=I.getReader(),x,R=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(R)&&(x=R),!x&&i&&(x=i.to-i.from+1);let L=x?new Uint8Array(x):new Uint8Array(0),k=!1,P=S=>{this.unsubscribeAbortSubscription(m),k=!0,Bs(S)},y=br(h,async function*({done:S,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(gr()-b),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&T){if(d&&x)L.set(T,f),f+=T.byteLength;else{let z=new Uint8Array(L.length+T.length);z.set(L),z.set(T,L.length),L=z,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(y,P)}}.bind(this));yield v?.read().then(y,P),this.unsubscribeAbortSubscription(m);let _=gr(),$={failed:k,requestStartedAt:b,requestEndedAt:_,duration:_-b};return k?(c.error("endRequest",li($)),c.end(),null):(c.log("endRequest",li($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=br(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,o=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,o=s+1===d,o&&(a=Math.min(d,r),u=Math.max(l,s))),a=Math.min(a,0);let p=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!p)return null;let c=new DataView(p,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(p,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(p),segments:b}}.bind(this));this.fetchTemplateRepresentation=br(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Pu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Sr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Bs=n=>{if(!Xe(n))throw n};var at=(n,e,t)=>t*e+(1-t)*n,sn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,$u=(n,e,t,i)=>{let r=0,s=t,a=sn(n,e),u=e<i?e:i;for(let o=0;o<u;o++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===u};import{isNullable as th,ValueSubject as Mu}from"@vkontakte/videoplayer-shared/evergreen";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mu(e.initial),this.debounced$=new Mu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(th(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Cs=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=at(this.slow,e,this.params.emaAlphaSlow),this.fast=at(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Os=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=sn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=$u(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Fs=class extends yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?at(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Os({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Fs({initial:e,label:"liveEdgeDelay",...t})}};var ci=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as ih,ValueSubject as rh}from"@vkontakte/videoplayer-shared/evergreen";var vr=class n{constructor(e,t){this.currentRepresentation$=new rh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!ih(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let o=r.segments.find(d=>d.time.from<=e&&d.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};import{assertNever as Ns}from"@vkontakte/videoplayer-shared/evergreen";var _s=n=>{let{webmDecodingInfo:e}=D.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Ns(n)}return[t,i]},Ru=({webmCodec:n,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],..._s(n),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(D.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",..._s(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(n),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(n),...s,"HLS","HLS_ONDEMAND"];default:Ns(e)}if(D.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Ns(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Du=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],u,o=D.device.isMac&&D.browser.isSafari;if(D.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=a;break}default:Ns(n)}else D.video.nativeHlsSupported&&!o?u=a:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},an=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Us=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)},Hs=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return oh().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},js=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return uh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=n=>n.split(".")[0].replace("0",""),oh=()=>["av1","vp9","hev1","avc1"],uh=()=>["opus","mp4a"];var mh=["timeupdate","progress","play","seeked","stalled","waiting"],fh=["timeupdate","progress","loadeddata","playing","seeked"];var qs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cu;this.representationSubscription=new Cu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Tt;this.manifestRequested=new Tt;this.manifestReceived=new Tt;this.firstBytesRequested=new Tt;this.firstBytesReceived=new Tt;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Tt;this.fetcherError$=new Tt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=on(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ne.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=$s(e??"",this.manifestUrlString)}catch(o){let d=Ps(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(d)}if(!t)return null;let i=(o,d,l)=>!!(this.element?.canPlayType?.(d)&&we()?.isTypeSupported?.(`${d}; codecs="${l}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:d,streamIsUnpublished:l,streamIsAlive:p}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((d-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=l?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:h})=>h);o==="audio"&&(a=js(c),p=a[0]),o==="video"&&(s=Hs(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=l.filter(({codecs:h})=>hi(h)===p))}else{let c=new Set(l.map(({codecs:h})=>h));p=Us(c),p&&(r[o]=l.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&h?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Tr(u)),u}.bind(this));this.initRepresentations=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Tr({initialVideo:e,initialAudio:t,sourceHls:i})),pi(this.manifest),pi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(ot(c,"error").pipe(Qs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=as();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Yt())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new fr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Ir(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new fr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}vr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new vr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ct(...fh.map(c=>ot(this.element,c))).pipe(fi(c=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),yr(),hh(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ct(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(yr()).subscribe(h=>this.liveStreamEndTimestamp=dn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=un(1e3).subscribe(h=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(mi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fi(({isActiveLive:h,isLowLatency:m})=>h&&m),yr()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ci(this.element,1)})),this.representationSubscription.add(mi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qs(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(mi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qs(({isLive:h})=>h),yr((h,m)=>m.bufferLength<h.bufferLength),fi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(mi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*E),ci(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(mi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ph(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(R?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+v&&(k="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=c-(E+I),y=this.normolizeLiveOffset(Math.trunc(b+P/f)),_=Math.abs(y-b),$=0;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?$=b:y>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&($=y),this.manifestUrlString=ee(this.manifestUrlString,$,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let d=Ct(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(fi(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Ct(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(fi(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=mi({allBuffersFull:d,someBufferEnded:l}).pipe(yr(),fi(({allBuffersFull:c,someBufferEnded:h})=>c&&h),Qs(c=>c));if(this.representationSubscription.add(Ct(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ct(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Pe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Ir(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=un(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Vs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){pi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?dn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){pi(this.element),this.state$.setState("running"),this.subscription.add(Ct(...mh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&de(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=dn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,l=o<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",Tr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=un(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){pi(this.element),pi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),de(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Vu(this.element)||Vu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Tr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ir(this.element)&&Ir(this.source)&&Ir(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=ch(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-a<=r&&o.to+a>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Tr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var zs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ws=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Fu=`attribute vec2 a_vertex;
|
|
124
124
|
attribute vec2 a_texel;
|
|
125
125
|
|
|
126
126
|
varying vec2 v_texel;
|