@vkontakte/videoplayer-core 2.0.150-dev.10447541.0 → 2.0.150-dev.169e8a40.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 +44 -44
- package/es2015.esm.js +42 -42
- package/es2018.cjs +34 -34
- package/es2018.esm.js +39 -39
- package/es2024.cjs +55 -55
- package/es2024.esm.js +46 -46
- package/esnext.cjs +55 -55
- package/esnext.esm.js +46 -46
- package/evergreen.esm.js +62 -62
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +4 -4
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +0 -61
- package/types/providers/DashProviderNew/consts.d.ts +0 -3
- package/types/providers/DashProviderNew/index.d.ts +0 -2
- package/types/providers/DashProviderNew/lib/ElementSizeManager.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +0 -23
- package/types/providers/DashProviderNew/lib/buffer.d.ts +0 -130
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +0 -64
- package/types/providers/DashProviderNew/lib/player.d.ts +0 -107
- package/types/providers/DashProviderNew/lib/sourceBufferBufferedDiff.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +0 -20
- package/types/providers/DashProviderNew/lib/types.d.ts +0 -29
- package/types/providers/DashProviderNew/lib/utils.d.ts +0 -24
- package/types/providers/DashProviderNew/newDashCmafLiveProvider.d.ts +0 -8
- package/types/providers/DashProviderNew/newDashProvider.d.ts +0 -6
package/evergreen.esm.js
CHANGED
|
@@ -1,119 +1,119 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.150-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.150-dev.169e8a40.0
|
|
3
|
+
* Thu, 15 Jan 2026 09:31:09 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-150/doc/
|
|
5
5
|
*/
|
|
6
|
-
var $u="2.0.150-dev.10447541.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),dt=(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))(dt||{});var pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(pr||{}),$n=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))($n||{});var Mn=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Mn||{}),ta=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ta||{});import{assertNever as Cu,assertNonNullable as nh,isNonNullable as ia,ValueSubject as Rn,Subject as oh,Subscription as uh,merge as ch,observableFrom as dh,fromEvent as Ru,map as Lu,tap as Bu,filterChanged as lh,isNullable as Ln,ErrorCategory as Du}from"@vkontakte/videoplayer-shared/evergreen";var Mu=u=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",u),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ra=class{constructor(e){this.connection$=new Rn(void 0);this.castState$=new Rn("NOT_AVAILABLE");this.errorEvent$=new oh;this.realCastState$=new Rn("NOT_AVAILABLE");this.subscription=new uh;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=ia(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Mu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Du.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(){ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ln(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ln(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(Ru(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 Cu(r.sessionState)}})).add(ch(Ru(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Bu(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Lu(r=>r.castState)),dh([i.getCastState()])).pipe(lh(),Lu(hh),Bu(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=ia(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();nh(n);let o=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(Ln(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?ia(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:Du.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},hh=u=>{switch(u){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 Cu(u)}};import{assertNonNullable as Nn,combine as Fn,debounce as _n,ErrorCategory as Rh,filter as Ei,filterChanged as Wu,isNonNullable as Un,isNullable as Gu,map as Lh,Subscription as Bh,ValueSubject as Hn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as ph,assertNonNullable as Xt,ErrorCategory as mh,getHighestQuality as fh,isNonNullable as Ou}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Vu}from"@vkontakte/videoplayer-shared/evergreen";var te=(u,e=0,t=0)=>{switch(t){case 0:return u.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return u;let i=new URL(u);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(u);return!i.searchParams.get("offset_p")&&e===0?u:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vu(t)}return u},$t=(u,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(u);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(u);return Number(t.searchParams.get("offset_p")??0)}default:Vu(e)}};var aa=u=>{let{source:e,format:t,meta:i,output:r}=u,s,a,n;switch(t){case"MPEG":{let d=e[t];Xt(d);let l=fh(Object.keys(d));Xt(l);let p=d[l];Xt(p),s=p,a="video/mp4",n=sa();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=e[t];Xt(d),s=d.url,a="application/x-mpegurl",n=sa();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=sa();break}case"DASH_LIVE_CMAF":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=Nu();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=e[t];Xt(d),s=te(d.url),a="application/x-mpegurl",n=Nu();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:mh.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return ph(t)}let o=bh(i.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=gh();let{title:c,subtitle:h}=i;return Ou(c)&&(o.metadata.title=c),Ou(h)&&(o.metadata.subtitle=h),o};function sa(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Nu(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function bh(u,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(u,e):{contentId:u,contentType:e,metadata:{title:"",subtitle:""},streamType:sa()}}function gh(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var x=(u,e,t=!1)=>{let i=u.getTransition();(t||!i||i.to===e)&&u.setState(e)};var na=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as qu}from"@vkontakte/videoplayer-shared/evergreen";import{isBrowserWindow as Ah,ValueSubject as $h}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as Sh}from"@vkontakte/videoplayer-shared/evergreen";var oa=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,n=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||c||r||s||n||"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}=Sh().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+)/)}};import{getWindow as Bn,isBrowserWindow as Dn}from"@vkontakte/videoplayer-shared/evergreen";var Jt=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var ua=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=Bn();if(!Dn(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Jt()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=Bn();if(!Dn(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}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,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||a||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r.length>0,n=r.length>1,o="Unknown",c="Unknown";if(a){let h=r[0];typeof h=="number"?h<s.length&&s[h]!==void 0&&(o=s[h]):o=h}if(n){let h=r[1];typeof h=="number"?h<s.length&&s[h]!==void 0&&(c=s[h]):h!==void 0&&(c=h)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&a&&typeof r[0]=="string"&&(c=s[1]);o=this.normalizeOSName(o),c=this.normalizeOSVersion(c,o),o==="iOS"&&/ipad/i.test(e)?o="iPadOS":o==="iPadOS"&&/ip(hone|od)/i.test(e)&&(o="iOS"),this._os={name:o,version:c||"Unknown",full:c&&c!=="Unknown"?`${o} ${c}`:o};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r[0],n=r[1],o=typeof a=="number"?s[a]!==void 0?this.normalizeVendorName(s[a]):"Unknown":this.normalizeVendorName(a),c="Unknown";typeof n=="number"?c=s[n]!==void 0?s[n]:"Unknown":n!==void 0?c=n:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,o),this.details.vendor=o,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=Bn();if(!Dn(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as Fu,isBrowserWindow as vh}from"@vkontakte/videoplayer-shared/evergreen";var ca=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Fu()}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 e=Fu();if(!vh(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(s){console.error(s)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(s){console.error(s)}}};import{getWindow as Cn,isBrowserWindow as Uu}from"@vkontakte/videoplayer-shared/evergreen";var xe=()=>window.ManagedMediaSource||window.MediaSource,Mt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),_u=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ii=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var yh=Cn().document?.createElement("video"),Th='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ih='video/mp4; codecs="hev1.1.6.L93.B0"',Hu='video/webm; codecs="vp09.00.10.08"',ju='video/webm; codecs="av01.0.00M.08"',Eh='audio/mp4; codecs="mp4a.40.2"',wh='audio/webm; codecs="opus"',zu,kh=async()=>{let u=Cn();if(!Uu(u))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:ju}}),u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Hu}})]);zu={DASH_WEBM_AV1:t,DASH_WEBM:i}};kh().catch(u=>{console.log(yh),console.error(u)});var da=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 zu}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=Cn();if(!Uu(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:Mt(),mse:_u(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!xe()?.isTypeSupported?.(Th),r=!!xe()?.isTypeSupported?.(Ih),s=!!xe()?.isTypeSupported?.(Eh);this._codecs={h264:i,h265:r,vp9:!!xe()?.isTypeSupported?.(Hu),av1:!!xe()?.isTypeSupported?.(ju),aac:s,opus:!!xe()?.isTypeSupported?.(wh),mpeg:(i||r)&&s},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}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}};import{getWindow as xh,isBrowserWindow as Ph}from"@vkontakte/videoplayer-shared/evergreen";var Qu="audio/mpeg",la=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=xh();if(!Ph(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Qu)},this._codecs={mp3:!!xe()?.isTypeSupported?.(Qu)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}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}};var Vn=class{constructor(){this.isInited$=new $h(!1);this._displayChecker=new ca,this._deviceChecker=new ua(this._displayChecker),this._browserChecker=new oa,this._videoChecker=new da(this._deviceChecker,this._browserChecker),this._audioChecker=new la,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(){Ah()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},$=new Vn;var On=u=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return u.filter(n=>{switch(n){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 qu(n)}})},mr=u=>{switch(u){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 qu(u)}},Mh=u=>{let t=Object.keys(u).filter(i=>!mr(i));return On(t).length>0};var fr=class{constructor(e){this.subscription=new Bh;this.sessionId$=new Hn(null);this.mediaSessionId$=new Hn(null);this.contentId$=new Hn(null);this.isMobile=Jt();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Gu(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;Un(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Un(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let a=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!a?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new na(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:Rh.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Ei(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Ei(Un),Wu(),_n(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Wu(),Lh(Boolean));this.subscription.add(Fn({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Ei(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Fn({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Ei(({mediaLoaded:r})=>r),_n(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Ei(({mediaLoaded:r,playbackState:{from:s,to:a}})=>!r&&s==="stopped"&&a==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Fn({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(_n(30)),mediaLoaded:t}).pipe(Ei(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:a}=r.to;this.setVolume(a,s)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=aa(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),a=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:a,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Nn(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Nn(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Nn(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":x(this.params.desiredState.playbackState,"paused");break;case"PLAYING":x(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),x(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):x(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Gu(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as Dh,ErrorCategory as jn,filter as Ch,Subject as Vh,Subscription as zn,tap as Oh,ValueSubject as wi,fromEvent as br}from"@vkontakte/videoplayer-shared/evergreen";var Yu=u=>({castDevice:{friendlyName:u},remotePlayer:{},remotePlayerController:{},session:{}}),Ku=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var gr=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new wi(null);this.sessionId$=new wi(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new zn;this.subscriptionEvents=new zn;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new wi(!1);this.presentationConnection$=new wi(null);this.message$=new wi(null);this.friendlyName$=new wi(null);this.errorEvent$=new Vh;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(br(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();Dh(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:jn.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(br(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(Oh(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Ch(e=>!!e)).subscribe(e=>{let t=br(e,"message").subscribe(s=>{let a=JSON.parse(s.data);a.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(a),this.message$.next(a))}),i=br(e,"connect").subscribe(()=>{this.send("client_connect")}),r=br(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:jn.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:jn.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Ku()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new zn}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as Xu,Subject as Nh,map as Fh,Subscription as _h,combine as Uh,filterChanged as Ju,assertNonNullable as Hh}from"@vkontakte/videoplayer-shared/evergreen";var lt=class u{constructor(e){this.subscription=new _h;this.connection$=new Xu(void 0);this.castState$=new Xu("NOT_AVAILABLE");this.errorEvent$=new Nh;let t=u.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new gr({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){Hh(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Uh({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Ju())});this.subscription.add(e.pipe(Fh(({connection:t,friendlyName:i})=>!!(t&&i)),Ju()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Yu(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};import{isNonNullable as jh,Subject as ha,merge as Zu}from"@vkontakte/videoplayer-shared/evergreen";var V=class{constructor(e){this.transitionStarted$=new ha;this.transitionEnded$=new ha;this.transitionUpdated$=new ha;this.forceChanged$=new ha;this.stateChangeStarted$=Zu(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zu(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||jh(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 Sr,debounce as ec,ErrorCategory as zh,fromEvent as Zt,map as tc,merge as ic,observableFrom as Qh,Subject as qh,Subscription as Qn,timeout as Wh}from"@vkontakte/videoplayer-shared/evergreen";var Gh=5,Yh=5,Kh=500,rc=7e3,vr=class{constructor(e){this.subscription=new Qn;this.loadMediaTimeoutSubscription=new Qn;this.videoState=new V("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(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:Sr(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:Sr(e)}break}default:Sr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(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 Qn;this.subscription.add(e),this.subscription.add(ic(this.videoState.stateChangeStarted$.pipe(tc(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(tc(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 qh;e.add(r.pipe(ec(Kh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let n=a.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-s)>Gh)&&r.next(n),s=n})),e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Yh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:Sr(a)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ic(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Qh(["init"])).pipe(ec(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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=aa(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(Wh(rc).subscribe(()=>s(`timeout(${rc})`)))});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:zh.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ac,getWindow as Jh}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Xh}from"@vkontakte/videoplayer-shared/evergreen";var sc=u=>{try{u.pause(),u.playbackRate=0,Xh(u),u.remove()}catch(e){console.error(e)}};import{fromEvent as Zh,Subscription as ep}from"@vkontakte/videoplayer-shared/evergreen";var qn=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)}},pa=Jh(),Wn=pa.WeakMap?new pa.WeakMap:new qn,Gn=pa.WeakMap?new pa.WeakMap:new Map,tp=(u,e=20)=>{let t=0;return Zh(u,"ratechange").subscribe(i=>{t++,t>=e&&(u.currentTime=u.currentTime,t=0)})},ge=(u,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=u.querySelector("video"),r=!!i;i?ac(i):(i=document.createElement("video"),u.appendChild(i)),Wn.set(i,r);let s=new ep;return s.add(tp(i,e)),Gn.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},Se=u=>{Gn.get(u)?.unsubscribe(),Gn.delete(u);let t=Wn.get(u);Wn.delete(u),t?ac(u):sc(u)};import{assertNonNullable as Tr,isNonNullable as st,isNullable as sp,fromEvent as ki,merge as nc,observableFrom as oc,filterChanged as uc,map as Ir,Subject as cc,Subscription as ap,ValueSubject as np,ErrorCategory as op}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Yn,isNullable as ip,Subscription as rp}from"@vkontakte/videoplayer-shared/evergreen";var ma=(u,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=u.getState(),n=e(),o=ip(r),c=new rp;return r&&c.add(r.subscribe(h=>{let d=u.getState();i(h,d)&&u.setState(h)},s)),i(n,a)||(t(a),o&&u.setState(a)),c.add(u.stateChangeStarted$.subscribe(h=>{t(h.to),o&&u.setState(h.to)},s)),c},je=(u,e,t)=>ma(e,()=>u.loop,i=>{Yn(i)&&(u.loop=i)},{onError:t}),ve=(u,e,t,i)=>ma(e,()=>({muted:u.muted,volume:u.volume}),r=>{Yn(r)&&(u.muted=r.muted,u.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),Be=(u,e,t,i)=>ma(e,()=>u.playbackRate,r=>{Yn(r)&&(u.playbackRate=r)},{changed$:t,onError:i}),yr=ma;var up=u=>["__",u.language,u.label].join("|"),cp=(u,e)=>{if(u.id===e)return!0;let[t,i,r]=e.split("|");return u.language===i&&u.label===r},Kn=class u{constructor(e){this.available$=new cc;this.current$=new np(void 0);this.error$=new cc;this.subscription=new ap;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:op.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(yr(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(yr(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(yr(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(yr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Tr(this.video);let{textTracks:e}=this.video;this.subscription.add(ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(nc(ki(e,"addtrack"),ki(e,"removetrack"),oc(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),uc((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(nc(ki(e,"change"),oc(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ir(i=>i&&this.htmlTextTrackToITextTrack(i).id),uc()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ki(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(ki(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;st(t.align)&&(r.align=t.align),st(t.position)&&(r.position=t.position),st(t.size)&&(r.size=t.size),st(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Tr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(u.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:up(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){Tr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(sp(e)||!cp(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){Tr(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){Tr(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)}},De=Kn;var ei=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 dc=u=>{let e=u;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Xn=u=>{let e=dc(u);return!!(e&&e.fullscreenElement&&e.fullscreenElement===u)},lc=u=>{let e=dc(u);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===u)};import{fromEvent as Pe,map as at,merge as fa,filterChanged as pc,isNonNullable as mc,Subject as lp,filter as Jn,mapTo as Zn,combine as hp,once as pp,shareReplay as Ae,throttle as mp,ErrorCategory as fp,ValueSubject as fc,Subscription as bp}from"@vkontakte/videoplayer-shared/evergreen";var dp=3,hc=(u,e,t=dp)=>{let i=0,r=0;for(let s=0;s<u.length;s++){let a=u.start(s),n=u.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)u.end(o)+t>=i&&(i=u.start(o));for(let o=s+1;o<u.length;o++)u.start(o)-t<=r&&(r=u.end(o))}}return{from:i,to:r}};var ye=u=>{let e=k=>Pe(u,k).pipe(Zn(void 0),Ae(1)),t=new bp,i=()=>t.unsubscribe(),r=fa(Pe(u,"progress"),Pe(u,"timeupdate")).pipe(at(()=>hc(u.buffered,u.currentTime)),Ae(1)),s=$.browser.isSafari?hp({play:e("play").pipe(pp()),playing:e("playing")}).pipe(Zn(void 0),Ae(1)):e("playing"),a=Pe(u,"volumechange").pipe(at(()=>({muted:u.muted,volume:u.volume})),Ae(1)),n=Pe(u,"ratechange").pipe(at(()=>u.playbackRate),Ae(1)),o=Pe(u,"error").pipe(Jn(()=>!!(u.error||u.played.length)),at(()=>{let k=u.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:fp.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:u.error??void 0}}),Ae(1)),c=Pe(u,"timeupdate").pipe(at(()=>u.currentTime),Ae(1)),h=["waiting","seeking","seeked","timeupdate"],d=new lp,l=.3,p;t.add(fa(...h.map(k=>Pe(u,k))).subscribe(k=>{let N=u.currentTime;u.loop&&mc(p)&&mc(N)&&p>=u.duration-l&&N<=l&&d.next(p),p=N}));let m=e("pause").pipe(Jn(()=>!u.error&&p!==u.duration),Ae(1)),f=Pe(u,"enterpictureinpicture").pipe(Ae(1)),b=Pe(u,"leavepictureinpicture").pipe(Ae(1)),g=new fc(lc(u));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new fc(Xn(u)),y=Pe(u,"fullscreenchange").pipe(Ae(1));t.add(y.pipe(at(()=>Xn(u))).subscribe(S));let v=.1,w=1e3,P=Pe(u,"timeupdate").pipe(at(k=>u.duration-u.currentTime<v),pc(),Ae(1)),A=fa(P.pipe(Jn(k=>!u.loop&&k)),Pe(u,"ended")).pipe(mp(w),Zn(void 0),Ae(1)),L=fa(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Pe(u,k)),P.pipe(at(k=>({type:k?"ended":"unknown"})))).pipe(at(k=>$.browser.isFirefox&&k.type==="ended"?u.readyState<2:u.readyState<3),pc(),Ae(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:A,looped$:d,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Pe(u,"durationchange").pipe(at(()=>u.duration),Ae(1)),isBuffering$:L,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Rt}from"@vkontakte/videoplayer-shared/evergreen";var nt=u=>{switch(u){case"mobile":return Rt.Q_144P;case"lowest":return Rt.Q_240P;case"low":return Rt.Q_360P;case"sd":case"medium":return Rt.Q_480P;case"hd":case"high":return Rt.Q_720P;case"fullhd":case"full":return Rt.Q_1080P;case"quadhd":case"quad":return Rt.Q_1440P;case"ultrahd":case"ultra":return Rt.Q_2160P}};import{isNonNullable as W,isNullable as va,now as xc,isHigher as ya,isHigherOrEqual as ti,isInvariantQuality as Ta,isLowerOrEqual as Pi,videoSizeToQuality as Pc,assertNotEmptyArray as Ia,assertNonNullable as Ac}from"@vkontakte/videoplayer-shared/evergreen";var eo=!1,ht={},bc=u=>{eo=u},gc=()=>{ht={}},Sc=u=>{u(ht)},Er=(u,e)=>{eo&&(ht.meta=ht.meta??{},ht.meta[u]=e)},$e=class{constructor(e){this.name=e}next(e){if(!eo)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as gp,isHigherOrEqual as mT,isLower as vc,isLowerOrEqual as fT,isNonNullable as ba,isNullable as Sp,videoHeightToQuality as ga}from"@vkontakte/videoplayer-shared/evergreen";function yc(u,e,t){return!u.max&&u.min===e?"high_quality":!u.min&&u.max===t?"traffic_saving":"unknown"}function xi(u,e,t){return Sp(u)||ba(u.min)&&ba(u.max)&&vc(u.max,u.min)||ba(u.min)&&e&&gp(u.min,e)||ba(u.max)&&t&&vc(u.max,t)}function Tc({limits:u,highestAvailableHeight:e,lowestAvailableHeight:t}){return xi({max:u?.max?ga(u.max):void 0,min:u?.min?ga(u.min):void 0},e?ga(e):void 0,t?ga(t):void 0)}var $c=new $e("best_bitrate"),Ea=(u,e,t)=>(e-t)*Math.pow(2,-10*u)+t;var Ai=u=>(e,t)=>u*(Number(e.bitrate)-Number(t.bitrate)),Je=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xc()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wa='Assertion "ABR Tracks is empty array" failed',Sa=new WeakMap,Ic=new WeakMap,Ec=new WeakMap,ii=(u,e,t,i)=>{let r=[...e].sort(Ai(1)),s=[...t].sort(Ai(1)),a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},ri=(u,e,t,i)=>{let r=Sa.get(e);r||(r=[...e].sort(Ai(1)),Sa.set(e,r));let s=Sa.get(t);s||(s=[...t].sort(Ai(1)),Sa.set(t,s));let a=Ec.get(u);a||(a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),Ec.set(u,a));let n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},wc=u=>"quality"in u,ka=(u,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?u.trackCooldownIncreaseQuality:u.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&xc()-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 n=wc(a)?"video":"audio",o=wc(a)?a.quality:a.bitrate;return e({message:`
|
|
7
|
-
[last ${
|
|
8
|
-
`}),
|
|
6
|
+
var wo="2.0.150-dev.169e8a40.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(fe||{}),Je=(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))(Je||{});var $i=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))($i||{}),Ns=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ns||{});var _s=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(_s||{}),na=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(na||{});import{assertNever as Mo,assertNonNullable as Cl,isNonNullable as oa,ValueSubject as Fs,Subject as Bl,Subscription as Vl,merge as Ol,observableFrom as Nl,fromEvent as ko,map as Po,tap as Ao,filterChanged as _l,isNullable as Us,ErrorCategory as $o}from"@vkontakte/videoplayer-shared/evergreen";var xo=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 ua=class{constructor(e){this.connection$=new Fs(void 0);this.castState$=new Fs("NOT_AVAILABLE");this.errorEvent$=new Bl;this.realCastState$=new Fs("NOT_AVAILABLE");this.subscription=new Vl;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=oa(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||xo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:$o.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(){oa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Us(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Us(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(ko(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 Mo(r.sessionState)}})).add(Ol(ko(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ao(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Po(r=>r.castState)),Nl([i.getCastState()])).pipe(_l(),Po(Fl),Ao(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=oa(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Cl(o);let u=o.getCastDevice(),c=o.getMediaSession()?.media?.contentId;(Us(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?oa(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:$o.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Fl=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 Mo(n)}};import{assertNonNullable as Ws,combine as Gs,debounce as Ys,ErrorCategory as sd,filter as ei,filterChanged as Ho,isNonNullable as Ks,isNullable as Qo,map as nd,Subscription as od,ValueSubject as Xs}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Ul,assertNonNullable as Lt,ErrorCategory as Hl,getHighestQuality as Ql,isNonNullable as Do}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Ro}from"@vkontakte/videoplayer-shared/evergreen";var de=(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:Ro(t)}return n},ca=(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:Ro(e)}};var da=n=>{let{source:e,format:t,meta:i,output:r}=n,a,s,o;switch(t){case"MPEG":{let l=e[t];Lt(l);let p=Ql(Object.keys(l));Lt(p);let h=l[p];Lt(h),a=h,s="video/mp4",o=la();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];Lt(l),a=l.url,s="application/x-mpegurl",o=la();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];Lt(l),a=l.url,s="application/dash+xml",o=la();break}case"DASH_LIVE_CMAF":{let l=e[t];Lt(l),a=l.url,s="application/dash+xml",o=Lo();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];Lt(l),a=de(l.url),s="application/x-mpegurl",o=Lo();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Hl.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return Ul(t)}let u=jl(i.videoId??a,s);u.contentUrl=a,u.streamType=o,u.metadata=zl();let{title:c,subtitle:d}=i;return Do(c)&&(u.metadata.title=c),Do(d)&&(u.metadata.subtitle=d),u};function la(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Lo(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function jl(n,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(n,e):{contentId:n,contentType:e,metadata:{title:"",subtitle:""},streamType:la()}}function zl(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var w=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};var pa=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Uo}from"@vkontakte/videoplayer-shared/evergreen";import{isBrowserWindow as id,ValueSubject as rd}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as ql}from"@vkontakte/videoplayer-shared/evergreen";var ha=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,s=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||s||u||c||r||a||o||"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}=ql().navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}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+)/)}};import{getWindow as Hs,isBrowserWindow as Qs}from"@vkontakte/videoplayer-shared/evergreen";var Ct=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var ma=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=Hs();if(!Qs(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Ct()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=Hs();if(!Qs(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}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,a=/ipod/i.test(e)?"iPod":void 0,s=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||s||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let s=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(s){let d=r[0];typeof d=="number"?d<a.length&&a[d]!==void 0&&(u=a[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<a.length&&a[d]!==void 0&&(c=a[d]):d!==void 0&&(c=d)}else a[2]!==void 0?c=a[2]:a[1]!==void 0&&s&&typeof r[0]=="string"&&(c=a[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let a=e.match(i);if(a){let s=r[0],o=r[1],u=typeof s=="number"?a[s]!==void 0?this.normalizeVendorName(a[s]):"Unknown":this.normalizeVendorName(s),c="Unknown";typeof o=="number"?c=a[o]!==void 0?a[o]:"Unknown":o!==void 0?c=o:a[1]!==void 0?c=a[1]:a[0]!==void 0&&(c=a[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=Hs();if(!Qs(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as Co,isBrowserWindow as Wl}from"@vkontakte/videoplayer-shared/evergreen";var fa=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Co()}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 e=Co();if(!Wl(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(a){console.error(a)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(a){console.error(a)}}};import{getWindow as js,isBrowserWindow as Vo}from"@vkontakte/videoplayer-shared/evergreen";var Pe=()=>window.ManagedMediaSource||window.MediaSource,Zt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Bo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ba=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Gl=js().document?.createElement("video"),Yl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Kl='video/mp4; codecs="hev1.1.6.L93.B0"',Oo='video/webm; codecs="vp09.00.10.08"',No='video/webm; codecs="av01.0.00M.08"',Xl='audio/mp4; codecs="mp4a.40.2"',Jl='audio/webm; codecs="opus"',_o,Zl=async()=>{let n=js();if(!Vo(n))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([n.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:No}}),n.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Oo}})]);_o={DASH_WEBM_AV1:t,DASH_WEBM:i}};Zl().catch(n=>{console.log(Gl),console.error(n)});var ga=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 _o}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=js();if(!Vo(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:Zt(),mse:Bo(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!Pe()?.isTypeSupported?.(Yl),r=!!Pe()?.isTypeSupported?.(Kl),a=!!Pe()?.isTypeSupported?.(Xl);this._codecs={h264:i,h265:r,vp9:!!Pe()?.isTypeSupported?.(Oo),av1:!!Pe()?.isTypeSupported?.(No),aac:a,opus:!!Pe()?.isTypeSupported?.(Jl),mpeg:(i||r)&&a},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}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}};import{getWindow as ed,isBrowserWindow as td}from"@vkontakte/videoplayer-shared/evergreen";var Fo="audio/mpeg",Sa=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=ed();if(!td(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Fo)},this._codecs={mp3:!!Pe()?.isTypeSupported?.(Fo)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}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}};var zs=class{constructor(){this.isInited$=new rd(!1);this._displayChecker=new fa,this._deviceChecker=new ma(this._displayChecker),this._browserChecker=new ha,this._videoChecker=new ga(this._deviceChecker,this._browserChecker),this._audioChecker=new Sa,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(){id()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},M=new zs;var qs=n=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=M.video,a=(i.h264||i.h265)&&i.aac,s=t.mse||t.mms;return n.filter(o=>{switch(o){case"DASH_SEP":return s&&e.mp4&&a;case"DASH_WEBM":return s&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return s&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return s&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return s&&e.mp4&&a;case"DASH_LIVE_CMAF":return s&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return s&&e.mp4&&a;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 Uo(o)}})},Mi=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 Uo(n)}},ad=n=>{let t=Object.keys(n).filter(i=>!Mi(i));return qs(t).length>0};var Ri=class{constructor(e){this.subscription=new od;this.sessionId$=new Xs(null);this.mediaSessionId$=new Xs(null);this.contentId$=new Xs(null);this.isMobile=Ct();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Qo(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;Ks(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Ks(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let s=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!s?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new pa(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Mi(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:sd.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ei(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(ei(Ks),Ho(),Ys(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Ho(),nd(Boolean));this.subscription.add(Gs({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ei(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Gs({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(ei(({mediaLoaded:r})=>r),Ys(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(ei(({mediaLoaded:r,playbackState:{from:a,to:s}})=>!r&&a==="stopped"&&s==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Gs({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Ys(30)),mediaLoaded:t}).pipe(ei(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:s}=r.to;this.setVolume(s,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=da(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),s=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:s,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Ws(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Ws(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Ws(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":w(this.params.desiredState.playbackState,"paused");break;case"PLAYING":w(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),w(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):w(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Qo(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as ud,ErrorCategory as Js,filter as cd,Subject as ld,Subscription as Zs,tap as dd,ValueSubject as ti,fromEvent as Di}from"@vkontakte/videoplayer-shared/evergreen";var jo=n=>({castDevice:{friendlyName:n},remotePlayer:{},remotePlayerController:{},session:{}}),zo=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Li=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new ti(null);this.sessionId$=new ti(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Zs;this.subscriptionEvents=new Zs;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new ti(!1);this.presentationConnection$=new ti(null);this.message$=new ti(null);this.friendlyName$=new ti(null);this.errorEvent$=new ld;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Di(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();ud(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Js.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Di(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(dd(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),cd(e=>!!e)).subscribe(e=>{let t=Di(e,"message").subscribe(a=>{let s=JSON.parse(a.data);s.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(s),this.message$.next(s))}),i=Di(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Di(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:Js.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:Js.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||zo()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Zs}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as qo,Subject as pd,map as hd,Subscription as md,combine as fd,filterChanged as Wo,assertNonNullable as bd}from"@vkontakte/videoplayer-shared/evergreen";var Ze=class n{constructor(e){this.subscription=new md;this.connection$=new qo(void 0);this.castState$=new qo("NOT_AVAILABLE");this.errorEvent$=new pd;let t=n.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Li({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){bd(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=fd({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Wo())});this.subscription.add(e.pipe(hd(({connection:t,friendlyName:i})=>!!(t&&i)),Wo()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?jo(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};import{isNonNullable as gd,Subject as va,merge as Go}from"@vkontakte/videoplayer-shared/evergreen";var V=class{constructor(e){this.transitionStarted$=new va;this.transitionEnded$=new va;this.transitionUpdated$=new va;this.forceChanged$=new va;this.stateChangeStarted$=Go(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Go(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||gd(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 Ci,debounce as Yo,ErrorCategory as Sd,fromEvent as Bt,map as Ko,merge as Xo,observableFrom as vd,Subject as yd,Subscription as en,timeout as Td}from"@vkontakte/videoplayer-shared/evergreen";var Id=5,Ed=5,wd=500,Jo=7e3,Bi=class{constructor(e){this.subscription=new en;this.loadMediaTimeoutSubscription=new en;this.videoState=new V("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ci(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:Ci(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:Ci(e)}break}default:Ci(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Mi(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 en;this.subscription.add(e),this.subscription.add(Xo(this.videoState.stateChangeStarted$.pipe(Ko(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ko(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new yd;e.add(r.pipe(Yo(wd)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>Id)&&r.next(o),a=o})),e.add(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Ed&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ci(s)}}),t(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vd(["init"])).pipe(Yo(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=da(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Td(Jo).subscribe(()=>a(`timeout(${Jo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Sd.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as eu,getWindow as kd}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as xd}from"@vkontakte/videoplayer-shared/evergreen";var Zo=n=>{try{n.pause(),n.playbackRate=0,xd(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Pd,Subscription as Ad}from"@vkontakte/videoplayer-shared/evergreen";var tn=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)}},ya=kd(),rn=ya.WeakMap?new ya.WeakMap:new tn,an=ya.WeakMap?new ya.WeakMap:new Map,$d=(n,e=20)=>{let t=0;return Pd(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},Te=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?eu(i):(i=document.createElement("video"),n.appendChild(i)),rn.set(i,r);let a=new Ad;return a.add($d(i,e)),an.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=n=>{an.get(n)?.unsubscribe(),an.delete(n);let t=rn.get(n);rn.delete(n),t?eu(n):Zo(n)};import{assertNonNullable as Oi,isNonNullable as We,isNullable as Dd,fromEvent as ii,merge as tu,observableFrom as iu,filterChanged as ru,map as Ni,Subject as au,Subscription as Ld,ValueSubject as Cd,ErrorCategory as Bd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as sn,isNullable as Md,Subscription as Rd}from"@vkontakte/videoplayer-shared/evergreen";var Ta=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=Md(r),c=new Rd;return r&&c.add(r.subscribe(d=>{let l=n.getState();i(d,l)&&n.setState(d)},a)),i(o,s)||(t(s),u&&n.setState(s)),c.add(n.stateChangeStarted$.subscribe(d=>{t(d.to),u&&n.setState(d.to)},a)),c},qe=(n,e,t)=>Ta(e,()=>n.loop,i=>{sn(i)&&(n.loop=i)},{onError:t}),Ee=(n,e,t,i)=>Ta(e,()=>({muted:n.muted,volume:n.volume}),r=>{sn(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),De=(n,e,t,i)=>Ta(e,()=>n.playbackRate,r=>{sn(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Vi=Ta;var Vd=n=>["__",n.language,n.label].join("|"),Od=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},nn=class n{constructor(e){this.available$=new au;this.current$=new Cd(void 0);this.error$=new au;this.subscription=new Ld;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=a=>{this.error$.next({id:"TextTracksManager",category:Bd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Vi(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{We(a)&&this.setInternal(a)},{equal:(a,s)=>We(a)&&We(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Ni(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Vi(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{We(a)&&this.setExternal(a)},{equal:(a,s)=>We(a)&&We(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Ni(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Vi(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Vi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Oi(this.video);let{textTracks:e}=this.video;this.subscription.add(ii(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(tu(ii(e,"addtrack"),ii(e,"removetrack"),iu(["init"])).pipe(Ni(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ru((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(tu(ii(e,"change"),iu(["init"])).pipe(Ni(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ni(i=>i&&this.htmlTextTrackToITextTrack(i).id),ru()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ii(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ii(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;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){Oi(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:Vd(e),a=this.externalTracks.has(r),s=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,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:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Oi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Dd(e)||!Od(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){Oi(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){Oi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=nn;var Vt=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 su=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},on=n=>{let e=su(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},nu=n=>{let e=su(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as be,map as Ge,merge as Ia,filterChanged as uu,isNonNullable as cu,Subject as _d,filter as un,mapTo as cn,combine as Fd,once as Ud,shareReplay as ge,throttle as Hd,ErrorCategory as Qd,ValueSubject as lu,Subscription as jd}from"@vkontakte/videoplayer-shared/evergreen";var Nd=3,ou=(n,e,t=Nd)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var we=n=>{let e=E=>be(n,E).pipe(cn(void 0),ge(1)),t=new jd,i=()=>t.unsubscribe(),r=Ia(be(n,"progress"),be(n,"timeupdate")).pipe(Ge(()=>ou(n.buffered,n.currentTime)),ge(1)),a=M.browser.isSafari?Fd({play:e("play").pipe(Ud()),playing:e("playing")}).pipe(cn(void 0),ge(1)):e("playing"),s=be(n,"volumechange").pipe(Ge(()=>({muted:n.muted,volume:n.volume})),ge(1)),o=be(n,"ratechange").pipe(Ge(()=>n.playbackRate),ge(1)),u=be(n,"error").pipe(un(()=>!!(n.error||n.played.length)),Ge(()=>{let E=n.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:Qd.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:n.error??void 0}}),ge(1)),c=be(n,"timeupdate").pipe(Ge(()=>n.currentTime),ge(1)),d=["waiting","seeking","seeked","timeupdate"],l=new _d,p=.3,h;t.add(Ia(...d.map(E=>be(n,E))).subscribe(E=>{let _=n.currentTime;n.loop&&cu(h)&&cu(_)&&h>=n.duration-p&&_<=p&&l.next(h),h=_}));let m=e("pause").pipe(un(()=>!n.error&&h!==n.duration),ge(1)),f=be(n,"enterpictureinpicture").pipe(ge(1)),g=be(n,"leavepictureinpicture").pipe(ge(1)),b=new lu(nu(n));t.add(f.subscribe(()=>b.next(!0))),t.add(g.subscribe(()=>b.next(!1)));let S=new lu(on(n)),I=be(n,"fullscreenchange").pipe(ge(1));t.add(I.pipe(Ge(()=>on(n))).subscribe(S));let v=.1,x=1e3,A=be(n,"timeupdate").pipe(Ge(E=>n.duration-n.currentTime<v),uu(),ge(1)),R=Ia(A.pipe(un(E=>!n.loop&&E)),be(n,"ended")).pipe(Hd(x),cn(void 0),ge(1)),D=Ia(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>be(n,E)),A.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>M.browser.isFirefox&&E.type==="ended"?n.readyState<2:n.readyState<3),uu(),ge(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:R,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:be(n,"durationchange").pipe(Ge(()=>n.duration),ge(1)),isBuffering$:D,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:b,inFullscreen$:S,enterPip$:f,leavePip$:g,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 q,isNullable as ka,now as Tu,isHigher as Pa,isHigherOrEqual as Ot,isInvariantQuality as Aa,isLowerOrEqual as ai,videoSizeToQuality as Iu,assertNotEmptyArray as $a,assertNonNullable as Eu}from"@vkontakte/videoplayer-shared/evergreen";var ln=!1,et={},du=n=>{ln=n},pu=()=>{et={}},hu=n=>{n(et)},_i=(n,e)=>{ln&&(et.meta=et.meta??{},et.meta[n]=e)},Se=class{constructor(e){this.name=e}next(e){if(!ln)return;et.series=et.series??{};let t=et.series[this.name]??[];t.push([Date.now(),e]),et.series[this.name]=t}};import{isHigher as zd,isHigherOrEqual as ov,isLower as mu,isLowerOrEqual as uv,isNonNullable as Ea,isNullable as qd,videoHeightToQuality as wa}from"@vkontakte/videoplayer-shared/evergreen";function fu(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function ri(n,e,t){return qd(n)||Ea(n.min)&&Ea(n.max)&&mu(n.max,n.min)||Ea(n.min)&&e&&zd(n.min,e)||Ea(n.max)&&t&&mu(n.max,t)}function bu({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return ri({max:n?.max?wa(n.max):void 0,min:n?.min?wa(n.min):void 0},e?wa(e):void 0,t?wa(t):void 0)}var wu=new Se("best_bitrate"),Ma=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var si=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Tu()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ra='Assertion "ABR Tracks is empty array" failed',xa=new WeakMap,gu=new WeakMap,Su=new WeakMap,Fi=(n,e,t,i)=>{let r=[...e].sort(si(1)),a=[...t].sort(si(1)),s=a.filter(u=>q(u.bitrate)&&q(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},Ui=(n,e,t,i)=>{let r=xa.get(e);r||(r=[...e].sort(si(1)),xa.set(e,r));let a=xa.get(t);a||(a=[...t].sort(si(1)),xa.set(t,a));let s=Su.get(n);s||(s=a.filter(u=>q(u.bitrate)&&q(n.bitrate)?n.bitrate/u.bitrate>i:!0),Su.set(n,s));let o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},vu=n=>"quality"in n,Da=(n,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Tu()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let s=i.last;i?.recordSwitch(s);let o=vu(s)?"video":"audio",u=vu(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
+
[last ${o} selected] ${u}
|
|
8
|
+
`}),s}return i?.recordSwitch(t),t},Wd=(n,e)=>Math.log(e)/Math.log(n),xu=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&M.display.pixelRatio){let a=M.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(a-1)+1;else{let s=n.pixelRatioLogBase,[o=0,u=0,c=0]=n.pixelRatioLogCoefficients,d=Wd(s,o*a+u)+c;Number.isFinite(d)&&(r*=d)}}return q(t?.min)&&Ot(t.min,n.highQualityLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},yu=new WeakMap,Ye=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{$a(n,Ra);let{containerSizeFactor:g,containerSizeLimit:b}=xu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(o)?o:1,I=yu.get(n);I||(I=n.filter(T=>!Aa(T.quality)).sort((T,y)=>Pa(T.quality,y.quality)?-1:1),yu.set(n,I));let v=I.at(-1)?.quality,x=I.at(0)?.quality,A=ri(r,x,v),R=S*Ma(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},D=null;for(let T of I){let y=!0;if(b)if(T.size)y=T.size.width<=b.width&&T.size.height<=b.height;else{let U=b&&Iu(b);y=U?ai(T.quality,U):!0}if(!y){k[T.quality]="FitsContainer";continue}let O=h||t,$=q(O)&&isFinite(O)&&q(T.bitrate)?O-a>=T.bitrate*R:!0,F=r?.min===T.quality;if(!$&&!F){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&u&&!Aa(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Pa(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!l&&Ot(T.quality,l)&&!F){k[T.quality]="DroppedFramesLimit";continue}if(!!p&&Ot(T.quality,p)&&!F){k[T.quality]="StallsLimit";continue}let ue=A||(ka(r?.max)||ai(T.quality,r.max))&&(ka(r?.min)||Ot(T.quality,r.min)),ce=q(d)&&!d?ai(T.quality,i.backgroundVideoQualityLimit):!0;if(!ue||!ce){k[T.quality]="FitsQualityLimits";continue}D||(D=T)}D&&D.bitrate&&wu.next(D.bitrate);let E=D??I.at(-1)??n[0],_=c?.last,C=Da(i,m,E,c);return q(c)&&C.quality!==_?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${
|
|
11
|
+
${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i??{}).map(([
|
|
15
|
+
${Object.entries(i??{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
19
|
-
containerSizeFactor: ${
|
|
20
|
-
containerSizeLimit: ${
|
|
19
|
+
containerSizeFactor: ${g},
|
|
20
|
+
containerSizeLimit: ${b?.width??0} x ${b?.height??0},
|
|
21
21
|
estimatedThroughput: ${t},
|
|
22
|
-
stallsPredictedThroughput: ${
|
|
23
|
-
reserve: ${
|
|
24
|
-
playbackRate: ${
|
|
22
|
+
stallsPredictedThroughput: ${h},
|
|
23
|
+
reserve: ${a},
|
|
24
|
+
playbackRate: ${o},
|
|
25
25
|
playbackRateFactor: ${S},
|
|
26
|
-
forwardBufferHealth: ${
|
|
27
|
-
bitrateFactor: ${
|
|
26
|
+
forwardBufferHealth: ${s},
|
|
27
|
+
bitrateFactor: ${R},
|
|
28
28
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
29
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
-
stallsVideoMaxQualityLimit: ${
|
|
31
|
-
limitsAreInvalid: ${
|
|
29
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
30
|
+
stallsVideoMaxQualityLimit: ${p},
|
|
31
|
+
limitsAreInvalid: ${A},
|
|
32
32
|
maxQualityLimit: ${r?.max},
|
|
33
33
|
minQualityLimit: ${r?.min},
|
|
34
34
|
|
|
35
35
|
[limited video tracks]
|
|
36
|
-
${Object.entries(
|
|
36
|
+
${Object.entries(k).map(([T,y])=>`${T}: ${y}`).join(`
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
|
-
[best video track] ${
|
|
40
|
-
[selected video track] ${
|
|
41
|
-
`}),
|
|
39
|
+
[best video track] ${D?.quality}
|
|
40
|
+
[selected video track] ${C?.quality}
|
|
41
|
+
`}),C},La=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{$a(n,Ra);let{containerSizeFactor:g,containerSizeLimit:b}=xu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(o)?o:1,I=n.filter(y=>!Aa(y.quality)).sort((y,O)=>Pa(y.quality,O.quality)?-1:1),v=I.at(-1)?.quality,x=I.at(0)?.quality,A=ri(r,x,v),R=S*Ma(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},E=I.filter(y=>{let O=!0;if(b)if(y.size)O=y.size.width<=b.width&&y.size.height<=b.height;else{let N=b&&Iu(b);O=N?ai(y.quality,N):!0}if(!O)return k[y.quality]="FitsContainer",!1;let $=h||t,F=q($)&&isFinite($)&&q(y.bitrate)?$-a>=y.bitrate*R:!0,W=r?.min===y.quality;if(!F&&!W)return k[y.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&u&&!Aa(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Pa(y.quality,u.quality))return k[y.quality]="Buffer",!1;if(!!l&&Ot(y.quality,l)&&!W)return k[y.quality]="DroppedFramesLimit",!1;if(!!p&&Ot(y.quality,p)&&!W)return k[y.quality]="StallsLimit",!1;let ce=A||(ka(r?.max)||ai(y.quality,r.max))&&(ka(r?.min)||Ot(y.quality,r.min)),U=q(d)&&!d?ai(y.quality,i.backgroundVideoQualityLimit):!0;return!ce||!U?(k[y.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&wu.next(E.bitrate);let _=E??I.at(-1)??n[0],C=c?.last,T=Da(i,m,_,c);return q(c)&&T.quality!==C?.quality&&m({message:`
|
|
42
42
|
[VIDEO TRACKS ABR]
|
|
43
43
|
[available video tracks]
|
|
44
|
-
${
|
|
44
|
+
${n.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate}, size: ${y.size?.width}:${y.size?.height} }`).join(`
|
|
45
45
|
`)}
|
|
46
46
|
|
|
47
47
|
[tuning]
|
|
48
|
-
${Object.entries(i??{}).map(([
|
|
48
|
+
${Object.entries(i??{}).map(([y,O])=>`${y}: ${O}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
[limit params]
|
|
52
|
-
containerSizeFactor: ${
|
|
53
|
-
containerSizeLimit: ${
|
|
52
|
+
containerSizeFactor: ${g},
|
|
53
|
+
containerSizeLimit: ${b?.width??0} x ${b?.height??0},
|
|
54
54
|
estimatedThroughput: ${t},
|
|
55
|
-
stallsPredictedThroughput: ${
|
|
56
|
-
reserve: ${
|
|
57
|
-
playbackRate: ${
|
|
55
|
+
stallsPredictedThroughput: ${h},
|
|
56
|
+
reserve: ${a},
|
|
57
|
+
playbackRate: ${o},
|
|
58
58
|
playbackRateFactor: ${S},
|
|
59
|
-
forwardBufferHealth: ${
|
|
60
|
-
bitrateFactor: ${
|
|
59
|
+
forwardBufferHealth: ${s},
|
|
60
|
+
bitrateFactor: ${R},
|
|
61
61
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
62
|
-
droppedVideoMaxQualityLimit: ${
|
|
63
|
-
stallsVideoMaxQualityLimit: ${
|
|
64
|
-
limitsAreInvalid: ${
|
|
62
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
63
|
+
stallsVideoMaxQualityLimit: ${p},
|
|
64
|
+
limitsAreInvalid: ${A},
|
|
65
65
|
maxQualityLimit: ${r?.max},
|
|
66
66
|
minQualityLimit: ${r?.min},
|
|
67
67
|
|
|
68
68
|
[limited video tracks]
|
|
69
|
-
${Object.entries(
|
|
69
|
+
${Object.entries(k).map(([y,O])=>`${y}: ${O}`).join(`
|
|
70
70
|
`)||"All tracks are available"}
|
|
71
71
|
|
|
72
|
-
[best video track] ${
|
|
73
|
-
[selected video track] ${
|
|
74
|
-
`}),
|
|
72
|
+
[best video track] ${E?.quality}
|
|
73
|
+
[selected video track] ${T?.quality}
|
|
74
|
+
`}),T},Ca=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{$a(t,Ra);let d=r.considerPlaybackRate&&q(a)?a:1,l=[...t].sort(si(-1)),p=n.bitrate;Eu(p);let h=d*Ma(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Fi(n,e,t,r.minVideoAudioRatio),g=c||i;q(g)&&isFinite(g)&&(m=l.find(I=>q(I.bitrate)&&q(f?.bitrate)?g-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let b=o?.last,S=m&&Da(r,u,m,o);return q(o)&&S?.bitrate!==b?.bitrate&&u({message:`
|
|
75
75
|
[AUDIO TRACKS ABR]
|
|
76
76
|
[available audio tracks]
|
|
77
|
-
${t.map(
|
|
77
|
+
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
78
78
|
`)}
|
|
79
79
|
|
|
80
80
|
[tuning]
|
|
81
|
-
${Object.entries(r??{}).map(([
|
|
81
|
+
${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
|
|
82
82
|
`)}
|
|
83
83
|
|
|
84
84
|
[limit params]
|
|
85
85
|
estimatedThroughput: ${i},
|
|
86
86
|
stallsPredictedThroughput: ${c},
|
|
87
|
-
reserve: ${
|
|
88
|
-
playbackRate: ${
|
|
89
|
-
playbackRateFactor: ${
|
|
90
|
-
forwardBufferHealth: ${
|
|
91
|
-
bitrateFactor: ${
|
|
87
|
+
reserve: ${p},
|
|
88
|
+
playbackRate: ${a},
|
|
89
|
+
playbackRateFactor: ${d},
|
|
90
|
+
forwardBufferHealth: ${s},
|
|
91
|
+
bitrateFactor: ${h},
|
|
92
92
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
93
93
|
|
|
94
94
|
[selected audio track] ${S?.id}
|
|
95
|
-
`}),S},
|
|
95
|
+
`}),S},Ba=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{$a(t,Ra);let d=r.considerPlaybackRate&&q(a)?a:1,l=gu.get(t);l||(l=[...t].sort(si(-1)),gu.set(t,l));let p=n.bitrate;Eu(p);let h=d*Ma(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Ui(n,e,t,r.minVideoAudioRatio),g=c||i;q(g)&&isFinite(g)&&(m=l.find(I=>q(I.bitrate)&&q(f?.bitrate)?g-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let b=o?.last,S=m&&Da(r,u,m,o);return q(o)&&S?.bitrate!==b?.bitrate&&u({message:`
|
|
96
96
|
[AUDIO TRACKS ABR]
|
|
97
97
|
[available audio tracks]
|
|
98
|
-
${t.map(
|
|
98
|
+
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
99
99
|
`)}
|
|
100
100
|
|
|
101
101
|
[tuning]
|
|
102
|
-
${Object.entries(r??{}).map(([
|
|
102
|
+
${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
|
|
103
103
|
`)}
|
|
104
104
|
|
|
105
105
|
[limit params]
|
|
106
106
|
estimatedThroughput: ${i},
|
|
107
107
|
stallsPredictedThroughput: ${c},
|
|
108
|
-
reserve: ${
|
|
109
|
-
playbackRate: ${
|
|
110
|
-
playbackRateFactor: ${
|
|
111
|
-
forwardBufferHealth: ${
|
|
112
|
-
bitrateFactor: ${
|
|
108
|
+
reserve: ${p},
|
|
109
|
+
playbackRate: ${a},
|
|
110
|
+
playbackRateFactor: ${d},
|
|
111
|
+
forwardBufferHealth: ${s},
|
|
112
|
+
bitrateFactor: ${h},
|
|
113
113
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
114
114
|
|
|
115
115
|
[selected audio track] ${S?.id}
|
|
116
|
-
`}),S};var se=u=>new URL(u).hostname;import{assertNever as Oc,assertNonNullable as Nc,combine as zp,debounce as Qp,ErrorCategory as Fc,filter as _c,filterChanged as qp,isNonNullable as no,map as $a,merge as Uc,observableFrom as Wp,once as Gp,Subscription as Yp,ValueSubject as oo,videoQualityToHeight as Hc,videoSizeToQuality as Kp}from"@vkontakte/videoplayer-shared/evergreen";var Rc=u=>{if(u instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(u.message))throw u;return!(u instanceof DOMException&&(u.code===20||u.name==="AbortError"))},Te=async(u,e)=>{let t=u.muted;try{await u.play()}catch(i){if(!Rc(i))return!1;if(e&&e(),t)return console.warn(i),!1;u.muted=!0;try{await u.play()}catch(r){return Rc(r)&&(u.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Pa,isNullable as xp,assertNonNullable as xr}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Lc,assertNonNullable as xa,now as yp}from"@vkontakte/videoplayer-shared/evergreen";function de(){return yp()}function to(u){return de()-u}function io(u){let e=u.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,o=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let c=a.indexOf("?")>-1?"&":"?";return o&&(a+=c+"lowLat=1",c="&"),n&&(a+=c+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Bc(u,e,t){let i=(...r)=>{t.apply(null,r),u.removeEventListener(e,i)};u.addEventListener(e,i)}function Li(u,e,t,i){let r=window.XMLHttpRequest,s,a,n,o=!1,c=0,h,d,l=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;xa(h);let B=to(h),I;if(B<f){I=f-B,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,P()},g=B=>(s=B,N),S=B=>(d=B,N),y=()=>(p="json",N),v=()=>{if(!o){if(--c>=0){b(),i&&i();return}o=!0,d&&d(),t&&t()}},w=B=>(l=B,N),P=()=>{h=de(),a=new r,a.open("get",u);let B=0,I,T=0,O=()=>(xa(h),Math.max(h,Math.max(I||0,T||0)));if(s&&a.addEventListener("progress",R=>{let U=de();s.updateChunk&&R.loaded>B&&(s.updateChunk(O(),R.loaded-B),B=R.loaded,I=U)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;xa(a);let R=a.status;if(R>=200&&R<300){let{response:U,responseType:G}=a,ee=U?.byteLength;if(typeof ee=="number"&&s){let re=ee-B;re&&s.updateChunk&&s.updateChunk(O(),re)}G==="json"&&(!U||!Object.values(U).length)?v():(d&&d(),e(U))}else v()}),a.addEventListener("error",()=>{v()}),l){let R=()=>{xa(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=de(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),N},N={withBitrateReporting:g,withParallel:w,withJSONResponse:y,withRetryCount:B=>(c=B,N),withRetryInterval:(B,I)=>(Lc(B)&&(f=B),Lc(I)&&(m=I),N),withTimeout:B=>(n=B,N),withFinally:S,send:P,abort:()=>{a&&(a.abort(),a=void 0),o=!0,d&&d()}};return N}var wr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,n=s.end-s.start;i+=a;let o=s.bytes*a/n;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var kr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=de(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=de()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Li(t,s,()=>r("error"),n),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Pp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Dc}from"@vkontakte/videoplayer-shared/evergreen";var D=(u,e)=>Dc(u)&&Dc(e)&&u.readyState==="open"&&Tp(u,e);function Tp(u,e){for(let t=0;t<u.activeSourceBuffers.length;++t)if(u.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Ip,safeStorage as Ep}from"@vkontakte/videoplayer-shared/evergreen";var ro=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=Object.entries(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},wp=(u,e="warn")=>{let t=Ip(),i=[];function r(s,a=!1){let n=t.performance?.timing?.navigationStart??0,o=new ro(u,Math.round((Date.now()-n)/1e3),s,a?new Error().stack:void 0);i.push(o),e&&t.console[e](o.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},C=wp("vp_dash_live_debug",Ep.get("vp_dev_null_console_method")??!1);var Aa=1e4,so=3;var Ap=6e4,$p=10,Mp=1,Rp=500,Pr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Pp,this.chunkRateEstimator=new wr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=io(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(C({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",C({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(C({m:"ldp.play.1"}),this._playVideoElement()):(C({m:"ldp.play.2"}),this._notifyBuffering(!0))):(C({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,C({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=io(e),C({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;C({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(C({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),C({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:o,min:c}=this.autoQualityLimits||{};!Tc({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(o&&s.video.height>o||c&&s.video.height<c)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Pa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(C({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",n=>{C({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{C({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{Bc(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new kr(so,Aa,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,n=null,o=null,c=null,h=!1,d=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},l=(v,w,P)=>{o&&o.abort(),o=Li(this.urlResolver.resolve(v,!1),w,P,()=>this._retryCallback()).withTimeout(Aa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(so).withFinally(()=>{o=null}).send()},p=(v,w,P)=>{xr(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),w,P,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let w=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${w}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let P=de()-1e4,A=0;for(let L=0;L<this.bufferStates.length;L++){let k=this.bufferStates[L];v=Math.min(v,k.buf),k.ts<P&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${v} drop=${A} jitter=${this.sourceJitter}`);let E=v-Mp;this.sourceJitter>=0?E-=this.sourceJitter/2:this.sourceJitter-=1,E>3?m(1.15):E>1?m(1.1):E>.3?m(1.05):m(1)}},g=v=>{let w,P=()=>w&&w.start?w.start.length:0,A=R=>w.start[R]/1e3,E=R=>w.dur[R]/1e3,L=R=>w.fragIndex+R,k=(R,U)=>({chunkIdx:L(R),startTS:A(R),dur:E(R),discontinuity:U}),N=()=>{let R=0;if(w&&w.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=U;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let re=w.dur.length-1;for(;re>=0&&(ee-=w.dur[re],!(ee<=0));--re);R=Math.min(re,w.dur.length-1-G),R=Math.max(R,0)}return k(R,!0)},B=R=>{let U=P();if(!(U<=0)){if(Pa(R)){for(let G=0;G<U;G++)if(A(G)>R)return k(G)}return N()}},I=R=>{let U=P(),G=R?R.chunkIdx+1:0,ee=G-w.fragIndex;if(!(U<=0)){if(!R||ee<0||ee-U>$p)return t(`Resync: offset=${ee} bChunks=${U} chunk=`+JSON.stringify(R)),N();if(!(ee>=U))return k(G-w.fragIndex,!1)}},T=(R,U,G)=>{c&&c.abort(),c=Li(this.urlResolver.resolve(R,!0,this.lowLatency),U,G,()=>this._retryCallback()).withTimeout(Aa).withRetryCount(so).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(R,U)=>{T(v,G=>{if(!d())return;w=G;let ee=!!w.lowLatency;ee!==this.lowLatency&&f(ee);let re=0;for(let pe=0;pe<w.dur.length;++pe)re+=w.dur[pe];re>0&&(xr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(B(U))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,n&&n.abort(),o&&o.abort(),c&&c.abort(),xr(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:w,logger:P}=this.params,A=g(e.jidxUrl),E,L,k,N,B=0,I,T,O,R=()=>{I&&(clearTimeout(I),I=void 0);let _=Math.max(Rp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),fe=B+_,we=de(),ce=Math.min(1e4,fe-we);B=we;let Ue=()=>{c||d()&&A.seek(()=>{d()&&(B=de(),U(),R())})};ce>0?I=window.setTimeout(()=>{this.paused?R():Ue()},ce):Ue()},U=()=>{let _;for(;_=A.nextChunk(N);)N=_,me(_);let fe=A.nextChunk(k);if(fe){if(k&&fe.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?R():(S(),C({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}pe(fe)}else R()},G=(_,fe)=>{if(!d()||!this.sourceBuffer){C({m:"ab.0",c:[!d(),!this.sourceBuffer]});return}let we,ce,Ue,kt=We=>{C({m:"ldp.postpone",t:We}),window.setTimeout(()=>{d()&&G(_,fe)},We)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),C({m:"ldp.ab.1"}),kt(100);else{let We=de(),Ve=w.currentTime;!this.paused&&w.buffered.length>1&&T===Ve&&We-O>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),T!==Ve&&(T=Ve,O=We);let xt=this._getBufferSizeSec();if(xt>30)C({m:"ldp.ab.3"}),P(`Buffered ${xt} seconds; delaying appendBuffer`),kt(2e3);else try{if(this.params.config.useInvalidBufferFix&&D(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(C({m:"ldp.ab.5"}),this.bufferStates.push({ts:We,buf:xt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(C({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),fe&&fe()}catch(Ge){if(C({m:"ldp.ab.err",e:Ge.name}),Ge.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Ue=this.sourceBuffer.buffered.length,Ue!==0&&(we=this.sourceBuffer.buffered.start(0),ce=Ve,ce-we>4&&this.sourceBuffer.remove(we,ce-3)),kt(1e3);else throw Ge}}},ee=()=>{L&&E&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(k)]),G(L,function(){L=null,U()}))},re=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),pe=_=>{d()&&p(re(_),(fe,we)=>{if(d()){if(we/=1e3,L=fe,k=_,a=_.startTS,we){let ce=Math.min(10,_.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}ee()}},()=>this._handleNetworkError())},me=_=>{d()&&(xr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(_),!1)))},H=_=>{d()&&(e.cachedHeader=_,G(_,()=>{E=!0,ee()}))};s=!0,A.seek(_=>{if(d()){if(B=de(),!_){R();return}N=_,!xp(v)||_.startTS>v?pe(_):(k=_,U())}},v),e.cachedHeader?H(e.cachedHeader):l(e.headerUrl,H,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},h}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Pa(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,xr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Pa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let l,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}l=this._selectQuality(d),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(l,p)=>{let m=de();if(this.chunkRateEstimator.addInterval(l,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-l,speed:b}),!0}},get:()=>{let l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}},a=-1/0,n,o=!0,c=()=>{let d=s.get();if(d&&n&&this.autoQuality){if(o&&d>n&&to(a)<3e4)return;i(d)}o=this.autoQuality};return{updateChunk:(d,l)=>{let p=s.updateChunk(d,l);return p&&c(),p},notifySwitch:d=>{let l=de();d<n&&(a=l),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=Li(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Aa).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Te(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{C({m:"ldp.pve.1"}),t||(C({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let n=[];return a?.length?(a.forEach((o,c)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=c,n.push(o))}),n.sort(function(o,c){return o.video&&c.video?c.video.height-o.video.height:c.bitrate-o.bitrate}),n):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ap))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Lp,filter as Cc,fromEvent as Bp,interval as Dp,isHigher as Cp,isInvariantQuality as Vp,isLower as Op,merge as Np,Subject as Vc,Subscription as Fp}from"@vkontakte/videoplayer-shared/evergreen";var ao=class{constructor(){this.onDroopedVideoFramesLimit$=new Vc;this.subscription=new Fp;this.playing=!1;this.tracks=[];this.forceChecker$=new Vc;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Vp(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Cp(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Bp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Dp(this.droppedFramesChecker.checkTime).pipe(Cc(()=>this.playing),Cc(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Lp(this.droppedFramesChecker.checkTime)),i=Np(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Op(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Lt=ao;import{map as _p,Observable as Up}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Hp}from"@vkontakte/videoplayer-shared/evergreen";var Ar=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var jp=(u,e)=>new Up(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(o=>t.next(o.isIntersecting||Ar()))},{...i,...e});r.observe(u);let s=Hp(document,"visibilitychange").pipe(_p(a=>!document.hidden||Ar())).subscribe(a=>t.next(a));return()=>{r.unobserve(u),s.unsubscribe()}}),Ce=jp;var Xp=["paused","playing","ready"],Jp=["paused","playing","ready"],$r=class{constructor(e){this.subscription=new Yp;this.videoState=new V("stopped");this.representations$=new oo([]);this.droppedFramesManager=new Lt;this.maxSeekBackTime$=new oo(1/0);this.zeroTime$=new oo(void 0);this.liveOffset=new ei;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Fc.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=nt(r.name)??Kp(r.video),n=r.bitrate/1e3,o={...r.video};if(!a)continue;let c={id:s,quality:a,bitrate:n,size:o};i.push({track:c,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),no(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Jp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Xp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){C({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&(C({m:"dlp.sync.2"}),this.dash.catchUp()),C({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(te(this.params.source.url,o))}return;default:return Oc(e)}};this.textTracksManager=new De(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Fc.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Uc(this.videoState.stateChangeStarted$.pipe($a(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($a(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{C({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ye(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe($a(r=>r.map(({track:s})=>s)),_c(r=>!!r.length),Gp()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(qp(),$a(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(zp({zeroTime:this.zeroTime$.pipe(_c(no)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(je(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Hc(r),min:s&&Hc(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),C({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(C({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":C({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":C({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Oc(r.to)}},t)).add(Uc(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Wp(["init"])).pipe(Qp(0)).subscribe(this.syncPlayback,t))}destroy(){C({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Se(this.video)}createLiveDashPlayer(){let e=new Pr({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&no(t)?t:ze(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==n){let c=e.find(({track:h})=>h.id===s)?.representation;Nc(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Nc(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),C({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(te(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var jc=$r;import{filterChanged as Pf}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as mm,assertNonNullable as fm,debounce as bm,ErrorCategory as Zc,filter as bo,filterChanged as go,fromEvent as gm,isNonNullable as ed,isNullable as Sm,map as So,merge as Ca,observableFrom as vo,once as td,Subscription as vm,throttle as ym}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Zp}from"@vkontakte/videoplayer-shared/evergreen";var zc=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Zp({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Qc=({id:u,bitrate:e})=>({id:u,bitrate:e}),qc=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e});var uo=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ma=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var Me=u=>u.type==="template";var Ra=class{constructor(e,t){this.fov=e,this.orientation=t}};var La=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 Wc=`attribute vec2 a_vertex;
|
|
116
|
+
`}),S};var pe=n=>new URL(n).hostname;import{assertNever as Du,assertNonNullable as Lu,combine as Sp,debounce as vp,ErrorCategory as Cu,filter as Bu,filterChanged as yp,isNonNullable as bn,map as _a,merge as Vu,observableFrom as Tp,once as Ip,Subscription as Ep,ValueSubject as gn,videoQualityToHeight as Ou,videoSizeToQuality as wp}from"@vkontakte/videoplayer-shared/evergreen";var ku=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},xe=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!ku(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return ku(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Oa,isNullable as ep,assertNonNullable as ji}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Pu,assertNonNullable as Va,now as Gd}from"@vkontakte/videoplayer-shared/evergreen";function se(){return Gd()}function dn(n){return se()-n}function pn(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let c=s.indexOf("?")>-1?"&":"?";return u&&(s+=c+"lowLat=1",c="&"),o&&(s+=c+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Au(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function ni(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,c=0,d,l,p=!1,h="arraybuffer",m=7e3,f=2e3,g=()=>{if(u)return;Va(d);let C=dn(d),T;if(C<f){T=f-C,setTimeout(g,T);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,A()},b=C=>(a=C,_),S=C=>(l=C,_),I=()=>(h="json",_),v=()=>{if(!u){if(--c>=0){g(),i&&i();return}u=!0,l&&l(),t&&t()}},x=C=>(p=C,_),A=()=>{d=se(),s=new r,s.open("get",n);let C=0,T,y=0,O=()=>(Va(d),Math.max(d,Math.max(T||0,y||0)));if(a&&s.addEventListener("progress",$=>{let F=se();a.updateChunk&&$.loaded>C&&(a.updateChunk(O(),$.loaded-C),C=$.loaded,T=F)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>v())),s.addEventListener("load",()=>{if(u)return;Va(s);let $=s.status;if($>=200&&$<300){let{response:F,responseType:W}=s,Z=F?.byteLength;if(typeof Z=="number"&&a){let te=Z-C;te&&a.updateChunk&&a.updateChunk(O(),te)}W==="json"&&(!F||!Object.values(F).length)?v():(l&&l(),e(F))}else v()}),s.addEventListener("error",()=>{v()}),p){let $=()=>{Va(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(y=se(),s.removeEventListener("readystatechange",$))};s.addEventListener("readystatechange",$)}return s.responseType=h,s.send(),_},_={withBitrateReporting:b,withParallel:x,withJSONResponse:I,withRetryCount:C=>(c=C,_),withRetryInterval:(C,T)=>(Pu(C)&&(f=C),Pu(T)&&(m=T),_),withTimeout:C=>(o=C,_),withFinally:S,send:A,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return _}var Hi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qi=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=se(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=se()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ni(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=se()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=se();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as tp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as $u}from"@vkontakte/videoplayer-shared/evergreen";var G=(n,e)=>$u(n)&&$u(e)&&n.readyState==="open"&&Yd(n,e);function Yd(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Kd,safeStorage as Xd}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=Object.entries(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},Jd=(n,e="warn")=>{let t=Kd(),i=[];function r(a,s=!1){let o=t.performance?.timing?.navigationStart??0,u=new hn(n,Math.round((Date.now()-o)/1e3),a,s?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let a=i;return i=[],a},r},L=Jd("vp_dash_live_debug",Xd.get("vp_dev_null_console_method")??!1);var Na=1e4,mn=3;var ip=6e4,rp=10,ap=1,sp=500,zi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new tp,this.chunkRateEstimator=new Hi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=pn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(L({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",L({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(L({m:"ldp.play.1"}),this._playVideoElement()):(L({m:"ldp.play.2"}),this._notifyBuffering(!0))):(L({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,L({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=pn(e),L({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;L({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(L({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),L({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(M.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:c}=this.autoQualityLimits||{};!bu({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&a.video.height>u||c&&a.video.height<c)||(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Oa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(L({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",o=>{L({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{L({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Au(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):s()})};this.waitingForFirstBufferAfterSrcChange=!0,s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qi(mn,Na,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,c=null,d=!1,l=()=>{let v=a&&(!d||d===this.rep);return v||t("Not running!"),v},p=(v,x,A)=>{u&&u.abort(),u=ni(this.urlResolver.resolve(v,!1),x,A,()=>this._retryCallback()).withTimeout(Na).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mn).withFinally(()=>{u=null}).send()},h=(v,x,A)=>{ji(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),x,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=v=>{let x=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${x}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let A=se()-1e4,R=0;for(let D=0;D<this.bufferStates.length;D++){let E=this.bufferStates[D];v=Math.min(v,E.buf),E.ts<A&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${v} drop=${R} jitter=${this.sourceJitter}`);let k=v-ap;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},b=v=>{let x,A=()=>x&&x.start?x.start.length:0,R=$=>x.start[$]/1e3,k=$=>x.dur[$]/1e3,D=$=>x.fragIndex+$,E=($,F)=>({chunkIdx:D($),startTS:R($),dur:k($),discontinuity:F}),_=()=>{let $=0;if(x&&x.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=F;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let te=x.dur.length-1;for(;te>=0&&(Z-=x.dur[te],!(Z<=0));--te);$=Math.min(te,x.dur.length-1-W),$=Math.max($,0)}return E($,!0)},C=$=>{let F=A();if(!(F<=0)){if(Oa($)){for(let W=0;W<F;W++)if(R(W)>$)return E(W)}return _()}},T=$=>{let F=A(),W=$?$.chunkIdx+1:0,Z=W-x.fragIndex;if(!(F<=0)){if(!$||Z<0||Z-F>rp)return t(`Resync: offset=${Z} bChunks=${F} chunk=`+JSON.stringify($)),_();if(!(Z>=F))return E(W-x.fragIndex,!1)}},y=($,F,W)=>{c&&c.abort(),c=ni(this.urlResolver.resolve($,!0,this.lowLatency),F,W,()=>this._retryCallback()).withTimeout(Na).withRetryCount(mn).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:($,F)=>{y(v,W=>{if(!l())return;x=W;let Z=!!x.lowLatency;Z!==this.lowLatency&&f(Z);let te=0;for(let ue=0;ue<x.dur.length;++ue)te+=x.dur[ue];te>0&&(ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,$(C(F))},()=>this._handleNetworkError())},nextChunk:T}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),ji(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:v=>{let{videoElement:x,logger:A}=this.params,R=b(e.jidxUrl),k,D,E,_,C=0,T,y,O,$=()=>{T&&(clearTimeout(T),T=void 0);let N=Math.max(sp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=C+N,he=se(),ae=Math.min(1e4,le-he);C=he;let Me=()=>{c||l()&&R.seek(()=>{l()&&(C=se(),F(),$())})};ae>0?T=window.setTimeout(()=>{this.paused?$():Me()},ae):Me()},F=()=>{let N;for(;N=R.nextChunk(_);)_=N,ce(N);let le=R.nextChunk(E);if(le){if(E&&le.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?$():(S(),L({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}ue(le)}else $()},W=(N,le)=>{if(!l()||!this.sourceBuffer){L({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let he,ae,Me,lt=Ve=>{L({m:"ldp.postpone",t:Ve}),window.setTimeout(()=>{l()&&W(N,le)},Ve)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),L({m:"ldp.ab.1"}),lt(100);else{let Ve=se(),ke=x.currentTime;!this.paused&&x.buffered.length>1&&y===ke&&Ve-O>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),y!==ke&&(y=ke,O=Ve);let dt=this._getBufferSizeSec();if(dt>30)L({m:"ldp.ab.3"}),A(`Buffered ${dt} seconds; delaying appendBuffer`),lt(2e3);else try{if(this.params.config.useInvalidBufferFix&&G(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(L({m:"ldp.ab.5"}),this.bufferStates.push({ts:Ve,buf:dt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(L({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(Oe){if(L({m:"ldp.ab.err",e:Oe.name}),Oe.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(he=this.sourceBuffer.buffered.start(0),ae=ke,ae-he>4&&this.sourceBuffer.remove(he,ae-3)),lt(1e3);else throw Oe}}},Z=()=>{D&&k&&(A([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(E)]),W(D,function(){D=null,F()}))},te=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),ue=N=>{l()&&h(te(N),(le,he)=>{if(l()){if(he/=1e3,D=le,E=N,s=N.startTS,he){let ae=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ae:ae}Z()}},()=>this._handleNetworkError())},ce=N=>{l()&&(ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(N),!1)))},U=N=>{l()&&(e.cachedHeader=N,W(N,()=>{k=!0,Z()}))};a=!0,R.seek(N=>{if(l()){if(C=se(),!N){$();return}_=N,!ep(v)||N.startTS>v?ue(N):(E=N,F())}},v),e.cachedHeader?U(e.cachedHeader):p(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>s},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Oa(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Oa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(p,h)=>{let m=se();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,u=!0,c=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&dn(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=se();l<o&&(s=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=ni(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Na).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{L({m:"ldp.pve.1"}),t||(L({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,c)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ip))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as np,filter as Mu,fromEvent as op,interval as up,isHigher as cp,isInvariantQuality as lp,isLower as dp,merge as pp,Subject as Ru,Subscription as hp}from"@vkontakte/videoplayer-shared/evergreen";var fn=class{constructor(){this.onDroopedVideoFramesLimit$=new Ru;this.subscription=new hp;this.playing=!1;this.tracks=[];this.forceChecker$=new Ru;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!lp(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&cp(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(op(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=up(this.droppedFramesChecker.checkTime).pipe(Mu(()=>this.playing),Mu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(np(this.droppedFramesChecker.checkTime)),i=pp(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>dp(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},oi=fn;import{map as mp,Observable as fp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as bp}from"@vkontakte/videoplayer-shared/evergreen";var qi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var gp=(n,e)=>new fp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||qi()))},{...i,...e});r.observe(n);let a=bp(document,"visibilitychange").pipe(mp(s=>!document.hidden||qi())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe()}}),Ce=gp;var xp=["paused","playing","ready"],kp=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new Ep;this.videoState=new V("stopped");this.representations$=new gn([]);this.droppedFramesManager=new oi;this.maxSeekBackTime$=new gn(1/0);this.zeroTime$=new gn(void 0);this.liveOffset=new Vt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Cu.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=ft(r.name)??wp(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let c={id:a,quality:s,bitrate:o,size:u};i.push({track:c,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),bn(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(kp.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&xp.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){L({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&(L({m:"dlp.sync.2"}),this.dash.catchUp()),L({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(de(this.params.source.url,u))}return;default:return Du(e)}};this.textTracksManager=new Le(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Cu.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Vu(this.videoState.stateChangeStarted$.pipe(_a(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_a(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{L({m:"dlp.s.1",t:a+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=we(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(_a(r=>r.map(({track:a})=>a)),Bu(r=>!!r.length),Ip()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(yp(),_a(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Sp({zeroTime:this.zeroTime$.pipe(Bu(bn)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(qe(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ou(r),min:a&&Ou(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),L({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(L({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":L({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":L({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Du(r.to)}},t)).add(Vu(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Tp(["init"])).pipe(vp(0)).subscribe(this.syncPlayback,t))}destroy(){L({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}createLiveDashPlayer(){let e=new zi({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&bn(t)?t:Ye(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let c=e.find(({track:d})=>d.id===a)?.representation;Lu(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Lu(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),L({m:"dlp.seek",p:e,no:s,url:this.params.source.url}),this.dash.reinit(de(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Nu=Wi;import{filterChanged as em}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Hp,assertNonNullable as Qp,debounce as jp,ErrorCategory as Gu,filter as xn,filterChanged as kn,fromEvent as zp,isNonNullable as Yu,isNullable as qp,map as Pn,merge as qa,observableFrom as An,once as Ku,Subscription as Wp,throttle as Gp}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Pp}from"@vkontakte/videoplayer-shared/evergreen";var _u=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?ft(a):void 0)??Pp({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},Fu=({id:n,bitrate:e})=>({id:n,bitrate:e}),Uu=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e});var Sn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Fa=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var ve=n=>n.type==="template";var Ua=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ha=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??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 Hu=`attribute vec2 a_vertex;
|
|
117
117
|
attribute vec2 a_texel;
|
|
118
118
|
|
|
119
119
|
varying vec2 v_texel;
|
|
@@ -124,7 +124,7 @@ void main(void) {
|
|
|
124
124
|
// save texel vector to pass to fragment shader
|
|
125
125
|
v_texel = a_texel;
|
|
126
126
|
}
|
|
127
|
-
`;var
|
|
127
|
+
`;var Qu=`#ifdef GL_ES
|
|
128
128
|
precision highp float;
|
|
129
129
|
precision highp int;
|
|
130
130
|
#else
|
|
@@ -167,17 +167,17 @@ void main(void) {
|
|
|
167
167
|
// sample using new coordinates
|
|
168
168
|
gl_FragColor = texture2D(u_texture, tc);
|
|
169
169
|
}
|
|
170
|
-
`;var Dt=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ra(this.params.fov,this.params.orientation),this.cameraRotationManager=new La(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Wc,this.gl.VERTEX_SHADER),i=this.createShader(Gc,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,n=e+i,o=t-r,c=e+i,h=t+r,d=e-i,l=t+r;return[s,a,n,o,c,h,d,l]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as im,now as Mr,once as rm,Subscription as sm,ValueSubject as lo,isNonNullable as am,safeStorage as ho,filterChanged as nm}from"@vkontakte/videoplayer-shared/evergreen";var pt=(u,e,t)=>t*e+(1-t)*u,co=(u,e)=>u.reduce((t,i)=>t+i,0)/e,Yc=(u,e,t,i)=>{let r=0,s=t,a=co(u,e),n=e<i?e:i;for(let o=0;o<n;o++)u[s]>a?r++:r--,s=(u.length+s-1)%u.length;return Math.abs(r)===n};var Ba="stalls_manager_metrics",po="stalls_manager_abr_params",Kc="stalls_manager_default_tuning_abr_params",mo=class{constructor(){this.isSeeked$=new lo(!1);this.isBuffering$=new lo(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new sm;this.severeStallOccurred$=new lo(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(po):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Kc)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(po),this.setStoredData(Kc,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ba,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ba,[]),this.setStoredData(po,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n}=this.tuning,o=a*Math.min(t/n,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(ho.get(e)??t)}setStoredData(e,t){ho.set(e,JSON.stringify(t))}removeStoredData(e){ho.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ba,"[]"),r=t/e,s=i.length?pt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ba,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(rm()).subscribe(t=>this.providerStartWatchingTimestamp=Mr())),this.subscription.add(this.currentStallDuration$.pipe(nm()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(im(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),o=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),h=Mr(),d=r&&this.currentStallsCount>=r,l=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&h-c>=i+n&&t>=i;(d||l)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,am(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Bi=mo;import{combine as om,map as um,observeElementSize as cm,Subscription as dm,ValueSubject as fo,noop as lm}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.subscription=new dm;this.pipSize$=new fo(void 0);this.videoSize$=new fo(void 0);this.elementSize$=new fo(void 0);this.pictureInPictureWindowRemoveEventListener=lm}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(cm(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(om({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(um(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Xc,map as hm,once as Jc}from"@vkontakte/videoplayer-shared/evergreen";var Ct=({subscription:u,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,s=!1;u.add(e.volume.stateChangeStarted$.pipe(hm(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),Xc(a=>!!a),Jc()).subscribe(()=>{r=performance.now(),s=!0})),u.add(i.playbackRateState$.pipe(Xc(()=>s),Jc()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var Rr=class{constructor(e){this.subscription=new vm;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Bi;this.elementSizeManager=new Da;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return mm(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Dt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Sm(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Zc.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bo(d=>!!d.length),td()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(So(d=>d.to.state!=="none"),go());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(bo(ed),td()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(So(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(fm(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(uo(b));let g=[];for(let S of b.representations){let y=Qc(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(Ma(f));let b=[];for(let g of f.representations){let S=zc({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=qc(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Ca(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,gm(this.video,"progress")).pipe(bo(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(ym(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition(),p=t.autoVideoTrackSwitching.getState();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,b]=m,g=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===f.id);ed(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready"?await this.player.initRepresentations(f.id,b?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,p),b&&await this.player.switchRepresentation("audio",b.id,p))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(go()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(uo(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(So(({to:d})=>d==="ready"),go());this.subscription.add(Ca(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,vo(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ca(c,this.player.state$.stateChangeEnded$,vo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Ca(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vo(["init"])).pipe(bm(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:E})=>E===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:E})=>E===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:E})=>E===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};import{ErrorCategory as Lr}from"@vkontakte/videoplayer-shared/evergreen";var Di=u=>{if(!u)return{id:"EmptyResponse",category:Lr.PARSER,message:"Empty response"};if(u.length<=2&&u.match(/^\d+$/))return{id:`UVError#${u}`,category:Lr.NETWORK,message:`UV Error ${u}`};let e=u.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Lr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(u,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Lr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Lr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as Ad,assertNonNullable as gt,ErrorCategory as ni,filter as Ro,filterChanged as bf,flattenObject as za,fromEvent as oi,getTraceSubscriptionMethod as gf,getWindow as ds,interval as Sf,isNonNullable as Ft,isNullable as ls,map as Lo,merge as hs,now as vf,Subject as _t,Subscription as $d,SubscriptionRemovable as yf,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";var Ze=u=>{let e=new URL(u);return e.searchParams.set("quic","1"),e.toString()};var Ci=u=>{let e=u.get("X-Delivery-Type"),t=u.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 id,ErrorCategory as Dr,flattenObject as Oi,fromEvent as rd,getWindow as Tm,merge as Im,now as Cr,Subject as Ni,Subscription as Em,ValueSubject as yo}from"@vkontakte/videoplayer-shared/evergreen";var Ie=u=>u instanceof DOMException&&(u.name==="AbortError"||u.code===20);var Vi=u=>{let e=new URL(u);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Oa=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Ni;this.manifestReceived=new Ni;this.firstBytesRequested=new Ni;this.firstBytesReceived=new Ni;this.lastConnectionType$=new yo(void 0);this.lastConnectionReused$=new yo(void 0);this.lastRequestFirstBytes$=new yo(void 0);this.recoverableError$=new Ni;this.error$=new Ni;this.abortAllController=new AbortController;this.subscription=new Em;this.fetchManifest=Br(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Va);return r?(t.log("success",Oi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Oi({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:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,Tm().location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:id(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=Im(rd(this.abortAllController.signal,"abort"),rd(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){Va(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){Va(T)}p=I.signal}let f=0,b=Cr();l.log("startRequest",Oi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=Cr();if(!g)return l.error("error",{message:"No response in request"}),l.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){m?.unsubscribe();let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){m?.unsubscribe();let I=Cr(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",Oi(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),w,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(w=P),!w&&i&&(w=i.to-i.from+1);let A=w?new Uint8Array(w):new Uint8Array(0),E=!1,L=I=>{m?.unsubscribe(),E=!0,Va(I)},k=Br(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Cr()-b),this.firstBytesReceived.next()),p.aborted){m?.unsubscribe();return}if(!I&&T){if(c&&w)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),m?.unsubscribe();let N=Cr(),B={failed:E,requestStartedAt:b,requestEndedAt:N,duration:N-b};return E?(l.error("endRequest",Oi(B)),l.end(),null):(l.log("endRequest",Oi(B)),l.end(),A.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,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:p,initDataView:new DataView(d),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});if(!r)return null;let s=e.segments.map(a=>({...a,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.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}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:id(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:Dr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Dr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Dr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Dr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Dr.FATAL})}}},Va=u=>{if(!Ie(u))throw u};var Io=u=>{let e=u.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as km,isNullable as nd}from"@vkontakte/videoplayer-shared/evergreen";var sd=u=>{if(u.includes("/")){let e=u.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(u)};var ad=u=>{try{let e=wm(),t=u.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let n=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(n||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(n=>n!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(n=>{let o=a[n];(typeof o>"u"||o==="")&&delete a[n]}),a}return null}catch{return null}};function wm(){let u="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",h=`^(?:(?<langtag>${`
|
|
171
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${
|
|
170
|
+
`;var ui=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ua(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ha(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Hu,this.gl.VERTEX_SHADER),i=this.createShader(Qu,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[a,s,o,u,c,d,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as Mp,now as Yi,once as Rp,Subscription as Dp,ValueSubject as yn,isNonNullable as Lp,safeStorage as Tn,filterChanged as Cp}from"@vkontakte/videoplayer-shared/evergreen";var tt=(n,e,t)=>t*e+(1-t)*n,vn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,ju=(n,e,t,i)=>{let r=0,a=t,s=vn(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};var Qa="stalls_manager_metrics",In="stalls_manager_abr_params",zu="stalls_manager_default_tuning_abr_params",En=class{constructor(){this.isSeeked$=new yn(!1);this.isBuffering$=new yn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Dp;this.severeStallOccurred$=new yn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(In):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Yi(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Yi()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(zu)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:s}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===s||(this.removeStoredData(In),this.setStoredData(zu,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:s}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Qa,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,s)=>a+s.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let s=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(s,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((s,o)=>s+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Qa,[]),this.setStoredData(In,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:s,significantTvt:o}=this.tuning,u=s*Math.min(t/o,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Tn.get(e)??t)}setStoredData(e,t){Tn.set(e,JSON.stringify(t))}removeStoredData(e){Tn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Qa,"[]"),r=t/e,a=i.length?tt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,s={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(s),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Qa,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Rp()).subscribe(t=>this.providerStartWatchingTimestamp=Yi())),this.subscription.add(this.currentStallDuration$.pipe(Cp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:s}=this.tuning;if(Mp(this.lastUniqueVideoTrackSelected)||s&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=Yi(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-c>=i+o&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Lp(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Yi()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},ja=En;import{combine as Bp,map as Vp,observeElementSize as Op,Subscription as Np,ValueSubject as wn,noop as _p}from"@vkontakte/videoplayer-shared/evergreen";var za=class{constructor(){this.subscription=new Np;this.pipSize$=new wn(void 0);this.videoSize$=new wn(void 0);this.elementSize$=new wn(void 0);this.pictureInPictureWindowRemoveEventListener=_p}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Op(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Bp({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Vp(({videoSize:r,inPip:a,pipSize:s})=>a?s:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as qu,map as Fp,once as Wu}from"@vkontakte/videoplayer-shared/evergreen";var gt=({subscription:n,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!M.browser.isSafari)return;let r=0,a=!1;n.add(e.volume.stateChangeStarted$.pipe(Fp(()=>{let s=e.volume.getTransition(),o=t.getValue();return!o||!s?!1:!s.to.muted&&o.muted}),qu(s=>!!s),Wu()).subscribe(()=>{r=performance.now(),a=!0})),n.add(i.playbackRateState$.pipe(qu(()=>a),Wu()).subscribe(()=>{let s=t.getValue(),o=e.playbackRate.getState();s&&o!==s.playbackRate&&performance.now()-r<1e3&&(s.playbackRate=o)}))};var Ki=class{constructor(e){this.subscription=new Wp;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new oi;this.stallsManager=new ja;this.elementSizeManager=new za;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return Hp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ui(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Le(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;qp(this.observableVideo)&&(this.observableVideo=we(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=s=>{e.error$.next({id:i,category:Gu.WTF,message:`${i} internal logic error`,thrown:s})},a=(s,o)=>this.subscription.add(s.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(xn(l=>!!l.length),Ku()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let s=this.params.desiredState.seekState.stateChangeEnded$.pipe(Pn(l=>l.to.state!=="none"),kn());this.stallsManager.init({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(xn(Yu),Ku()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Pn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),gt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if(Qp(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let g of p.audio){f.push(Sn(g));let b=[];for(let S of g.representations){let I=Fu(S);b.push(I),this.audioTracksMap.set(I,{stream:g,representation:S})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Fa(f));let g=[];for(let b of f.representations){let S=_u({...b,streamId:f.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:f,representation:b}))}this.videoStreamsMap.set(f,g)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let g of f.representations){let b=Uu(f,g);this.textTracksMap.set(b,{stream:f,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=qa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zp(this.video,"progress")).pipe(xn(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(Gp(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,g]=m,b=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===f.id);Yu(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="manifest_ready"?await this.player.initRepresentations(f.id,g?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,h),g&&await this.player.switchRepresentation("audio",g.id,h))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(kn()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Sn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Pn(({to:l})=>l==="ready"),kn());this.subscription.add(qa(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(qa(c,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=qa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,An(["init"])).pipe(jp(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ui:Fi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ba:Ca,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:La,{desiredState:r,output:a}=this.params,s=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:k})=>k===o),c=a.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:k})=>k===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=s?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(m,f||1/0),1),b=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:k})=>k===b?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(u&&!s){let k=e(u,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}if(c){let k=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}}let v=u;(s||!v)&&(v=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:g,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=S&&t(v,p,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(v)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Gu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};import{ErrorCategory as Xi}from"@vkontakte/videoplayer-shared/evergreen";var Wa=n=>{if(!n)return{id:"EmptyResponse",category:Xi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Xi.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Xi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Xi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Xi.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as Ec,assertNonNullable as at,ErrorCategory as Ut,filter as Fn,filterChanged as Qh,flattenObject as cs,fromEvent as Ht,getTraceSubscriptionMethod as jh,getWindow as $r,interval as zh,isNonNullable as It,isNullable as Mr,map as Un,merge as Rr,now as qh,Subject as Et,Subscription as wc,SubscriptionRemovable as Wh,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";var St=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Ga=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 Ji,assertNever as Xu,ErrorCategory as Zi,flattenObject as li,fromEvent as Ju,getWindow as Yp,merge as Kp,now as er,Subject as di,Subscription as Xp,ValueSubject as $n}from"@vkontakte/videoplayer-shared/evergreen";var Fe=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ya=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Xa=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new di;this.manifestReceived=new di;this.firstBytesRequested=new di;this.firstBytesReceived=new di;this.lastConnectionType$=new $n(void 0);this.lastConnectionReused$=new $n(void 0);this.lastRequestFirstBytes$=new $n(void 0);this.recoverableError$=new di;this.error$=new di;this.abortAllController=new AbortController;this.subscription=new Xp;this.fetchManifest=Ji(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ya(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ka);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=Ji(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){let d=e,l=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(d,Yp().location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:Xu(t)}this.requestQuic&&(d=St(d));let h=this.abortAllController.signal,m;if(s){let T=new AbortController;if(m=Kp(Ju(this.abortAllController.signal,"abort"),Ju(s,"abort")).subscribe(()=>{try{T.abort()}catch(y){Ka(y)}}),this.subscription.add(m),this.abortAllController.signal.aborted||s.aborted)try{T.abort()}catch(y){Ka(y)}h=T.signal}let f=0,g=er();p.log("startRequest",li({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(d,{priority:a,headers:l,signal:h}),S=er();if(!b)return p.error("error",{message:"No response in request"}),p.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-g),!b.ok||!b.body){m?.unsubscribe();let T=`Fetch error ${b.status}: ${b.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){m?.unsubscribe();let T=er(),y={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",li(y)),p.end(),b.arrayBuffer()}let I=b.body;if(o){let T;[I,T]=b.body.tee(),this.throughputEstimator?.trackStream(T,u)}let v=I.getReader(),x,A=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),k=!1,D=T=>{m?.unsubscribe(),k=!0,Ka(T)},E=Ji(h,async function*({done:T,value:y}){if(f===0&&(this.lastRequestFirstBytes$.next(er()-g),this.firstBytesReceived.next()),h.aborted){m?.unsubscribe();return}if(!T&&y){if(c&&x)R.set(y,f),f+=y.byteLength;else{let O=new Uint8Array(R.length+y.length);O.set(R),O.set(y,R.length),R=O,f+=y.byteLength}r?.(new DataView(R.buffer),f),yield v?.read().then(E,D)}}.bind(this));yield v?.read().then(E,D),m?.unsubscribe();let _=er(),C={failed:k,requestStartedAt:g,requestEndedAt:_,duration:_-g};return k?(p.error("endRequest",li(C)),p.end(),null):(p.log("endRequest",li(C)),p.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ji(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(s=Math.min(c,r),o=Math.max(d,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(l,m.from-s,m.to-m.from+1);else{let b=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!b)return null;f=new DataView(b)}let g=t.parseSegments(f,h,m).map(b=>({networkStatus:"none",bufferStatus:"none",status:"none",time:b.time,byte:b.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ji(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});if(!r)return null;let a=e.segments.map(s=>({...s,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Ga(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:Xu(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(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Zi.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Zi.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Zi.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Zi.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Zi.FATAL})}}},Ka=n=>{if(!Fe(n))throw n};var Rn=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Zp,isNullable as tc}from"@vkontakte/videoplayer-shared/evergreen";var Zu=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var ec=n=>{try{let e=Jp(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),s={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(s).forEach(o=>{let u=s[o];(typeof u>"u"||u==="")&&delete s[o]}),s}return null}catch{return null}};function Jp(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
171
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
|
|
172
172
|
(-(?<script>[a-z]{4}))?
|
|
173
173
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
174
174
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
175
175
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
176
176
|
(?:-(?<privateuse>(?:${e})))?
|
|
177
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(h,"i")}var od=u=>{if(!u?.startsWith("P"))return;let e=(a,n)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*n},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(u),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},Oe=(u,e)=>{let t=u;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,(n,o)=>nd(s)?n:nd(o)?s:s.padStart(parseInt(o,10),"0"))}return t},_i=(u,e)=>{let i=new DOMParser().parseFromString(u,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(L=>L.textContent?.trim()??""),n=a.at(0)??"",o=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],l=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:c?new Date(c).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:l?new Date(l).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],v=y.reduce((L,k)=>({...L,[k.id]:k.children}),{}),w=y.reduce((L,k)=>({...L,[k.id]:k.getAttribute("duration")}),{});S?g=od(S):Object.values(w).filter(L=>L).length&&!o?g=Object.values(w).reduce((L,k)=>L+(od(k)??0),0):f&&(g=parseInt(f,10));let P=0,A=s.getAttribute("profiles")?.split(",")??[];for(let L of y.map(k=>k.id))for(let k of v[L]){let N=k.getAttribute("id")??"id"+(P++).toString(10),B=k.getAttribute("mimeType")??"",I=k.getAttribute("codecs")??"",T=k.getAttribute("contentType")??B?.split("/")[0],O=k.getAttribute("profiles")?.split(",")??[],R=ad(k.getAttribute("lang")??"")??{},U=k.querySelector("Label")?.textContent?.trim()??void 0,G=k.querySelectorAll("Representation"),ee=k.querySelector("SegmentTemplate"),re=k.querySelector("Role")?.getAttribute("value")??void 0,pe=T,me={id:N,language:R.language,isDefault:re==="main",label:U,codecs:I,hdr:pe==="video"&&Io(I),mime:B,representations:[]};for(let H of G){let _=H.getAttribute("lang")??void 0,fe=U??k.getAttribute("label")??H.getAttribute("label")??void 0,we=H.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(we||n,e).toString(),Ue=H.getAttribute("mimeType")??B,kt=H.getAttribute("codecs")??I??"",We;if(T==="text"){let Ve=H.getAttribute("id")||"",xt=R.privateuse?.includes("x-auto")||Ve.includes("_auto"),Ge=H.querySelector("SegmentTemplate");if(Ge){let cr={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=parseInt(Ge.getAttribute("startNumber")??"",10)??1,bi=parseInt(Ge.getAttribute("timescale")??"",10),Pn=Ge.querySelectorAll("SegmentTimeline S")??[],gi=Ge.getAttribute("media");if(!gi)continue;let Ys=[],Ks=0,Xs="",Si=0,dr=Gs,ke=0;for(let Ye of Pn){let Gt=parseInt(Ye.getAttribute("d")??"",10),He=parseInt(Ye.getAttribute("r")??"",10)||0,Pt=parseInt(Ye.getAttribute("t")??"",10);ke=Number.isFinite(Pt)?Pt:ke;let Yt=Gt/bi*1e3,vi=ke/bi*1e3;for(let it=0;it<He+1;it++){let At=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:(ke+it*Gt).toString(10)}),yi=(vi??0)+it*Yt,hr=yi+Yt;dr++,Ys.push({time:{from:yi,to:hr},url:At})}ke+=(He+1)*Gt,Ks+=(He+1)*Yt}Si=ke/bi*1e3,Xs=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:ke.toString(10)});let lr={time:{from:Si,to:1/0},url:Xs},ct={type:"template",baseUrl:ce,segmentTemplateUrl:gi,initUrl:"",totalSegmentsDurationMs:Ks,segments:Ys,nextSegmentBeyondManifest:lr,timescale:bi};We={id:Ve,kind:"text",segmentReference:ct,profiles:[],duration:g,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:xt}}else We={id:Ve,isAuto:xt,kind:"text",url:ce}}else{let Ve=H.getAttribute("contentType")??Ue?.split("/")[0]??T,xt=k.getAttribute("profiles")?.split(",")??[],Ge=parseInt(H.getAttribute("width")??"",10),cr=parseInt(H.getAttribute("height")??"",10),Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=H.getAttribute("frameRate")??"",bi=H.getAttribute("quality")??void 0,Pn=Gs?sd(Gs):void 0,gi=H.getAttribute("id")??"id"+(P++).toString(10),Ys=Ve==="video"?`${cr}p`:Ve==="audio"?`${Ws}Kbps`:kt,Ks=`${gi}@${Ys}`,Xs=[...A,...O,...xt],Si,dr=H.querySelector("SegmentBase"),ke=H.querySelector("SegmentTemplate")??ee;if(dr){let ct=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,Gt]=ct.split("-").map(At=>parseInt(At,10)),He={from:Ye,to:Gt},Pt=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Yt,vi]=Pt?Pt.split("-").map(At=>parseInt(At,10)):[],it=Pt?{from:Yt,to:vi}:void 0;Si={type:"byteRange",url:ce,initRange:He,indexRange:it}}else if(ke){let ct={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ye=parseInt(ke.getAttribute("timescale")??"",10),Gt=ke.getAttribute("initialization")??"",He=ke.getAttribute("media"),Pt=parseInt(ke.getAttribute("startNumber")??"",10)??1,Yt=Oe(Gt,ct);if(!He)throw new ReferenceError("No media attribute in SegmentTemplate");let vi=ke.querySelectorAll("SegmentTimeline S")??[],it=[],At=0,yi="",hr=0;if(vi.length){let Js=Pt,Ke=0;for(let Ti of vi){let rt=parseInt(Ti.getAttribute("d")??"",10),Kt=parseInt(Ti.getAttribute("r")??"",10)||0,Zs=parseInt(Ti.getAttribute("t")??"",10);Ke=Number.isFinite(Zs)?Zs:Ke;let An=rt/Ye*1e3,rh=Ke/Ye*1e3;for(let ea=0;ea<Kt+1;ea++){let sh=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:(Ke+ea*rt).toString(10)}),Au=(rh??0)+ea*An,ah=Au+An;Js++,it.push({time:{from:Au,to:ah},url:sh})}Ke+=(Kt+1)*rt,At+=(Kt+1)*An}hr=Ke/Ye*1e3,yi=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:Ke.toString(10)})}else if(km(g)){let Ke=parseInt(ke.getAttribute("duration")??"",10)/Ye*1e3,Ti=Math.ceil(g/Ke),rt=0;for(let Kt=1;Kt<Ti;Kt++){let Zs=Oe(He,{...ct,segmentNumber:Kt.toString(10),segmentTime:rt.toString(10)});it.push({time:{from:rt,to:rt+Ke},url:Zs}),rt+=Ke}hr=rt,yi=Oe(He,{...ct,segmentNumber:Ti.toString(10),segmentTime:rt.toString(10)})}let ih={time:{from:hr,to:1/0},url:yi};Si={type:"template",baseUrl:ce,segmentTemplateUrl:He,initUrl:Yt,totalSegmentsDurationMs:At,segments:it,nextSegmentBeyondManifest:ih,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ve||!Ue)continue;let lr={video:"video",audio:"audio",text:"text"}[Ve];if(!lr)continue;pe||=lr,We={id:Ks,kind:lr,segmentReference:Si,profiles:Xs,duration:g,bitrate:Ws,mime:Ue,codecs:kt,width:Ge,height:cr,fps:Pn,quality:bi}}me.language||=_,me.label||=fe,me.mime||=Ue,me.codecs||=kt,me.hdr||=pe==="video"&&Io(kt),me.representations.push(We)}if(pe){let H=r[pe].find(_=>_.id===me.id);if(H&&me.representations.every(_=>_.segmentReference.type==="template"))for(let _ of H.representations){let fe=me.representations.find(Ue=>Ue.id===_.id);if(!fe)continue;let we=fe.segmentReference,ce=_.segmentReference;ce.segments.push(...we.segments),ce.nextSegmentBeyondManifest=we.nextSegmentBeyondManifest}else r[pe].push(me)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as _a}from"@vkontakte/videoplayer-shared/evergreen";var Fa=u=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(u){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:_a(u)}},ud=({webmCodec:u,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Fa(u),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.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",...Fa(u),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Fa(u),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Fa(u),...s,"HLS","HLS_ONDEMAND"];default:_a(e)}if($.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:_a(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},cd=({androidPreferredFormat:u,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],n,o=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(u){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:_a(u)}else $.video.nativeHlsSupported&&!o&&!$.browser.isChromiumBased?n=a:o?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},Eo=u=>u?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ui=u=>{if(u.size===0)return;if(u.size===1)return u.values().next().value.split(".").at(0);for(let t of u){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return u.values().next().value.split(".").at(0)},Hi=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return $m().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})},ji=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return Mm().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Vt=u=>u.split(".")[0].replace("0",""),$m=()=>["av1","vp9","hev1","avc1"],Mm=()=>["opus","mp4a"];import{abortable as Ao,assertNonNullable as ot,ErrorCategory as Xm,fromEvent as Jm,getExponentialDelay as Zm,getWindow as vd,isHigher as ef,isNonNullable as ie,isNullable as le,once as tf,Subject as rf,Subscription as sf,ValueSubject as os}from"@vkontakte/videoplayer-shared/evergreen";var Ua=u=>u.valid,z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var zi=class extends z{};import{assertNever as Rm}from"@vkontakte/videoplayer-shared/evergreen";var Vr=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:Rm(e)}}};var Or=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Nr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Fr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var _r=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ur=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var si=class extends Y{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,n=this.readUint32();r=this.readUint32();let o=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}};var Hr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends Y{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var qr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Wr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends Y{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Yr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends Y{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var es=class extends Y{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ts=class extends Y{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var is=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var ss=class extends z{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var Bm={ftyp:Or,moov:Nr,mvhd:Fr,moof:_r,mdat:Ur,sidx:si,trak:Hr,mdia:Wr,mfhd:Xr,tkhd:Gr,traf:Jr,tfhd:Zr,tfdt:es,trun:ts,minf:Yr,sv3d:jr,st3d:zr,prhd:Qr,proj:Kr,equi:qr,uuid:Vr,stbl:is,stsd:rs,avc1:ss,unknown:zi},ft=class u{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!Ua(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=Bm[e];return i?new i(t,new u):new zi(t,new u)}};var Ot=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{Ua(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Cm=new TextDecoder("ascii"),Vm=u=>Cm.decode(new DataView(u.buffer,u.byteOffset+4,4))==="ftyp",Om=u=>{let e=new si(u,new ft),t=e.earliestPresentationTime/e.timescale*1e3,i=u.byteOffset+u.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},Nm=(u,e)=>{let i=new ft().parse(u),r=new Ot(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],o=a[a.length-1],c=n.source.byteOffset,d=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(u.buffer,c,d)},Fm=u=>{let t=new ft().parse(u),i=new Ot(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},_m=u=>{let t=new ft().parse(u);return new Ot(t).find("sidx")?.timescale},Um=(u,e)=>{let i=new ft().parse(u),s=new Ot(i).findAll("traf"),a=s[s.length-1].children.find(d=>d.type==="tfhd"),n=s[s.length-1].children.find(d=>d.type==="tfdt"),o=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return o.sampleDuration.length?c=o.sampleDuration.reduce((d,l)=>d+l,0):c=a.defaultSampleDuration*o.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},Hm=u=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ft().parse(u),r=new Ot(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},dd={validateData:Vm,parseInit:Hm,getIndexRange:()=>{},parseSegments:Om,parseFeedableSegmentChunk:Nm,getChunkEndTime:Um,getServerLatencyTimestamps:Fm,getTimescaleFromIndex:_m};import{assertNonNullable as wo,isNonNullable as md,isNullable as zm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as jm}from"@vkontakte/videoplayer-shared/evergreen";var ld={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},hd=u=>{let e=u.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=as(u,t),r=i in ld,s=r?ld[i].type:"binary",a=u.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let o=new DataView(u.buffer,u.byteOffset+t+1,n-1),c=a&255>>n,h=as(o),d=c*2**((n-1)*8)+h,l=t+n,p;return l+d>u.byteLength?p=new DataView(u.buffer,u.byteOffset+l):p=new DataView(u.buffer,u.byteOffset+l,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:l,tagSize:l+d,value:p,valueSize:d}},as=(u,e=u.byteLength)=>{switch(e){case 1:return u.getUint8(0);case 2:return u.getUint16(0);case 3:return u.getUint8(0)*2**16+u.getUint16(1);case 4:return u.getUint32(0);case 5:return u.getUint8(0)*2**32+u.getUint32(1);case 6:return u.getUint16(0)*2**32+u.getUint32(2);case 7:{let t=u.getUint8(0)*281474976710656+u.getUint16(1)*4294967296+u.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(u,e)=>{switch(e){case"int":return u.getInt8(0);case"uint":return as(u);case"float":return u.byteLength===4?u.getFloat32(0):u.getFloat64(0);case"string":return new TextDecoder("ascii").decode(u);case"utf8":return new TextDecoder("utf-8").decode(u);case"date":return new Date(Date.UTC(2001,0)+u.getInt8(0)).getTime();case"master":return u;case"binary":return u;default:jm(e)}},ai=(u,e)=>{let t=0;for(;t<u.byteLength;){let i=new DataView(u.buffer,u.byteOffset+t),r=hd(i);if(!e(r))return;r.type==="master"&&ai(r.value,e),t=r.value.byteOffset-u.byteOffset+r.valueSize}},pd=u=>{if(u.getUint32(0)!==440786851)return!1;let e,t,i,r=hd(u);return ai(r.value,({tag:s,type:a,value:n})=>(s===17143?e=et(n,a):s===17026?t=et(n,a):s===17029&&(i=et(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var fd=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Qm=[231,22612,22743,167,171,163,160,175],qm=u=>{let e,t,i,r,s=!1,a=!1,n=!1,o,c,h=!1,d=0;return ai(u,({tag:l,type:p,value:m,valueSize:f})=>{if(l===21419){let b=et(m,p);c=as(b)}else l!==21420&&(c=void 0);return l===408125543?(e=m.byteOffset,t=m.byteOffset+f):l===357149030?s=!0:l===290298740?a=!0:l===2807729?i=et(m,p):l===17545?r=et(m,p):l===21420&&c===475249515?o=et(m,p):l===374648427?ai(m,({tag:b,type:g,value:S})=>b===30321?(h=et(S,g)===1,!1):!0):s&&a&&fd.includes(l)&&(n=!0),!n}),wo(e,"Failed to parse webm Segment start"),wo(t,"Failed to parse webm Segment end"),wo(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:h,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Wm=u=>{if(zm(u.cuesSeekPosition))return;let e=u.segmentStart+u.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Gm=(u,e)=>{let t=!1,i=!1,r=n=>md(n.time)&&md(n.position),s=[],a;return ai(u,({tag:n,type:o,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=et(c,o));break;case 183:break;case 241:a&&(a.position=et(c,o));break;default:t&&fd.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,o)=>{let{time:c,position:h}=n,d=s[o+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Ym=u=>{let e=0,t=!1;try{ai(u,i=>i.tag===524531317?i.tagSize<=u.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Qm.includes(i.tag)?(e+i.tagSize<=u.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=u.byteLength&&t?new DataView(u.buffer,u.byteOffset,e):null},bd={validateData:pd,parseInit:qm,getIndexRange:Wm,parseSegments:Gm,parseFeedableSegmentChunk:Ym};var Qe=u=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(u);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return bd;case"mp4":return dd}}throw new ReferenceError(`Unsupported mime type ${u}`)};import{videoSizeToQuality as Km}from"@vkontakte/videoplayer-shared/evergreen";var Nt=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Km({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},ns=({id:u,bitrate:e})=>({id:u,bitrate:e}),gd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Sd=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),ko=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),xo=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Po=u=>"url"in u,Ne=u=>u.type==="template";var Qi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,manifest:n}){this.error$=new rf;this.playingRepresentation$=new os(void 0);this.playingRepresentationInit$=new os(void 0);this.currentSegmentLength$=new os(0);this.onLastSegment$=new os(!1);this.fullyBuffered$=new os(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new AbortController;this.downloadAbortController=new AbortController;this.subscription=new sf;this.startWith=Ao(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Qe(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Ao(this.destroyAbortController.signal,async function*(e,t=!0){if(le(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);ot(r,`No such representation ${e}`),ot(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),a=this.segments.get(r.id);ot(s,"No init buffer for switching representation"),ot(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,o=d=>d.segment.networkStatus!=="downloaded"||d.segment.time.to-n>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=d=>{let l=this.representations.get(d.representationId);return ot(l,"No itemRepresentation for previous track before switch"),d.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(l,r)},h=d=>t?o(d)&&c(d):o(d);this.bufferPlaybackQueue.filter(h).forEach(d=>d.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(d=>!h(d)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(n),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Ao(this.downloadAbortController.signal,async function*(){let e=Zm(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=vd();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(Jm(i,"online").pipe(tf()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=a,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=n?.baseUrls??[],this.representations=new Map(i.map(o=>[o.id,o]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){le(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return ie(t)&&ie(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from}getRepresentationInitialTime(){return le(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(le(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=vd();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.cancelIdleCallback)for(let t of this.idleCallbacks.values())e.cancelIdleCallback(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Nt(e),s=Nt(t);i=ie(r)&&ie(s)&&ef(s.quality,r.quality)}else if(this.kind==="audio"){let r=ns(e),s=ns(t);i=ie(r?.bitrate)&&ie(s?.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,requestIdleCallback(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():ie(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:a,initDataView:n,segments:o}=await s??{};if(this.initDataPromises.delete(e.id),le(n)||le(o))return;a&&this.parsedInitData.set(e.id,a);let c=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,o),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:Xm.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(le(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(n=>this.withinInterval(e,n.segment.time)),i=this.bufferPlaybackQueue.find(n=>n.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),s=this.bufferPlaybackQueue[0],a=this.downloadAbortController.signal;ie(r)&&ie(i)&&ie(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),ie(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,a):await this.appendSegmentPartially(i,a)),ie(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,a),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){ot(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(le(t)||le(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(a=>e>=a.time.from&&e<a.time.to);ie(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(le(t)||t.length===0)return;let i=t[t?.length-1];le(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){ot(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;ie(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(n=>this.withinInterval(e,n.time))),r=r===-1?0:r;let a=[];for(;r<t.length&&s>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:n,to:o}=t[r].time;s-=o-n,r++}return a}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return ie(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return ie(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return ie(e)?e-i>t:!1}async appendSegmentFully(e,t){if(le(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(le(e.segment.data)||le(e.segment.loadedBytes)||le(e.segment.feedingBytes)||le(e.segment.fedBytes)||le(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||ie(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let a of this.segments.values())for(let n of a)ie(n.size)&&s>0&&n.time.to<=e-r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size);for(let a of this.segments.values())for(let n of[...a].reverse())ie(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(o=>o.segment===n)&&!this.downloadingBufferItems.find(o=>o.segment===n)&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as af,isNonNullable as nf,isNullable as yd,now as Td}from"@vkontakte/videoplayer-shared/evergreen";var Ha=class extends Qi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...a,priority:i}),this.lastDataObtainedTimestampMs=Td(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,a=0;for(;a<this.downloadingBufferItems.length&&this.downloadingBufferItems[a].segment.networkStatus==="none"&&(e<=r||t<=s);){let n=this.downloadingBufferItems[a].segment;n.networkStatus="downloading",n.size=1/0,n.loadedBytes=0,n.feedingBytes=0,n.fedBytes=0,i.push(this.downloadingBufferItems[a]),e+=n.byte.to+1-n.byte.from,t+=n.time.to+1-n.time.from,a++}return i}prepareFetchParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(n,o)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Td(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:af.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:a}){let n=this.representations.get(i);if(!(!this.downloadingBufferItems.length||yd(n)||yd(r)||a.aborted))for(let o of e){let{segment:c}=o,h=c.byte.from-r,d=c.byte.to-r,l=d-h+1,p=h<s,m=d<=s;c.size=l,p&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+h,l),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o),c.loadedBytes=Math.min(l,s-h),await this.onDownloadItem(o)):nf(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(l,s-h),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+h,c.loadedBytes),await this.onDownloadItem(o))))}}updateRepresentationBaseUrl(e,t){if(Me(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as of,isNullable as $o,now as Id}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends Qi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let n=await this.fetcher.fetch(s,{...a,priority:i});if(this.lastDataObtainedTimestampMs=Id(),$o(n))return;let o=e[0],c=new DataView(n);o.segment.size=c.byteLength,o.segment.loadedBytes=c.byteLength,o.segment.data=c,this.onItemFullyDownloaded(o),await this.onDownloadItem(o),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(a,n)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=Id(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,signal:r,representationId:t.id})}catch(o){this.error$.next({id:"SegmentFeeding",category:of.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:o})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Me(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let a=e[0],{segment:n}=a,o=this.representations.get(i);!this.downloadingBufferItems.length||$o(o)||$o(n.feedingBytes)||n.networkStatus!=="downloading"||s.aborted||(n.loadedBytes=r,n.loadedBytes>n.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(n.data=new DataView(t.buffer,t.byteOffset,n.loadedBytes),await this.onDownloadItem(a)))}updateRepresentationBaseUrl(e,t){if(!Me(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as uf,ErrorCategory as cf,isNullable as bt,ValueSubject as Ed}from"@vkontakte/videoplayer-shared/evergreen";var ja=class extends qi{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Ed(0);this.currentLowLatencySegmentLength$=new Ed(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=t.streams[this.kind].flatMap(r=>r.representations);for(let r of i){if(bt(r)||!Me(r.segmentReference))return;let s=r.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],o=n.at(-1)?.time.to??0,c=s?.findIndex(h=>o>=h.time.from+a&&o<=h.time.to+a);if(c===-1){let h=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,h)}else{let h=s.slice(c+1);this.segments.set(r.id,[...n,...h])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;uf(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let r=t?.streams[this.kind]?.flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(bt(r))return;let s=this.segments.get(r.id);if(s?.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){if(bt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return bt(t)||!Me(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),bt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:a}=r.getServerLatencyTimestamps(i);s&&a&&this.currentLiveSegmentServerLatency$.next(a-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(bt(t.segment.data)||bt(r)||!Me(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:a}=r;t.segment.time.to=s.getChunkEndTime(i,a)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Me(s))return;let a=this.segments.get(r.id)??[],n=a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(n?.isCurrentLowLatency&&(n.time.to=t.segment.time.to,i=n.time.to-n.time.from,n.isCurrentLowLatency=!1),!!!a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*s.timescale/1e3).toString(10),h=Oe(s.segmentTemplateUrl,{segmentTime:c});a.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:h,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let s=this.tuning.dash.useFetchPriorityHints?i:"auto",a=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,a);let{initMetadata:n,initDataView:o,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),bt(o)||bt(c))return;n&&this.parsedInitData.set(t.id,n);let h=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,h);let d=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(t.id,d),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:cf.WTF,message:"loadInit threw",thrown:s})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],a=0,n=i.length-1;do s.unshift(i[n]),a+=i[n].time.to-i[n].time.from,n--;while(a<r&&n>=0);return this.liveInitialAdditionalOffset=a-r,this.isActiveLowLatency()?[s[0]]:s}};var us=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new ja(e,t,i,r):Me(i[0].segmentReference)?new qi(e,t,i,r):new Ha(e,t,i,r)}};import{ErrorCategory as hf,fromEvent as pf,isNullable as Wi,Subject as mf,Subscription as ff}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as df,ErrorCategory as wd,Subject as kd}from"@vkontakte/videoplayer-shared/evergreen";var lf=18,xd=!1;try{xd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=lf}catch(u){console.error(u)}var Mo=class{constructor(e,t=!1){this.bufferFull$=new kd;this.error$=new kd;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:wd.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};xd&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:wd.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:df(t)}}},Pd=Mo;var ae=(u,e)=>{let t=0;for(let i=0;i<u.length;i++){let r=u.start(i)*1e3,s=u.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var cs=class{constructor(e){this.error$=new mf;this.subscription=new ff;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Pd(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(pf(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:hf.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(Wi(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!Wi(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Wi(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return Wi(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Wi(e)?0:ae(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Wi(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var Tf=["timeupdate","progress","play","seeked","stalled","waiting"],Md=["timeupdate","progress","loadeddata","playing","seeked"],Qa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new $d;this.subscriptionRemovable=new yf;this.representationSubscription=new $d;this.forceEnded$=new _t;this.destroyController=new AbortController;this.state$=new V("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new _t;this.manifestRequested=new _t;this.manifestReceived=new _t;this.firstBytesRequested=new _t;this.firstBytesReceived=new _t;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.currentBuffer$=new K({from:0,to:0});this.bufferLength$=new K(0);this.nativeBufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new _t;this.fetcherError$=new _t;this.initRepresentations=Ad(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",za({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={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};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),gt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=Ad(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){ls(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ni.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Oa({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.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ni.PARSER,message:"No playable video representations"})}initBuffer(){gt(this.element),this.state$.setState("running"),this.subscription.add(hs(...Tf.map(t=>oi(this.element,t)),oi(ds(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:ni.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(hs(...e.map(t=>oi(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(oi(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Sf(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:ni.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){gt(this.element),gt(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),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",za({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ft(this.element)&&Ft(this.source)&&Ft(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}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.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&ds().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Ft(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(ls(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){gt(this.element),gt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",za(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=vf(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,h=Ft(this.videoBufferManager)&&o<s&&r-a>i,d=Ft(this.audioBufferManager)&&c<s&&r-n>i;return(h||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(ls(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",za(i)),i}parseManifest(e){try{return _i(e??"",this.manifestUrlString)}catch(t){let i=Di(e)??{id:"ManifestParsing",category:ni.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:d,codecs:l})=>i(n,d,l));t[n]=c;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:l})=>l);n==="audio"&&(s=ji(d),h=s[0]),n==="video"&&(r=Hi(d),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?h=this.forceVideoCodec:h=r[0]),h&&(t[n]=c.filter(({codecs:l})=>Vt(l)===h))}else{let d=new Set(c.map(({codecs:l})=>l));h=Ui(d),h&&(t[n]=c.filter(({codecs:l})=>l.startsWith(h)))}if(n==="video"){let d=this.tuning.preferHDR,l=t.video.some(m=>m.hdr),p=t.video.some(m=>!m.hdr);$.display.isHDR&&d&&l?t.video=t.video.filter(m=>m.hdr):p&&(t.video=t.video.filter(m=>!m.hdr))}}let a={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(a.codecs={video:r,audio:s}),a}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){gt(this.manifest),gt(this.element);let s=c=>{this.representationSubscription.add(oi(c,"error").pipe(Ro(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ni.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ii();let a=ds().document,n=a.createElement("source");if(s(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),Mt())if(r){let c=a.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoNativeBufferManager=new cs(this.source),this.videoBufferManager=us.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],Ft(i)){this.audioNativeBufferManager=new cs(this.source);let c=this.manifest.streams.audio.reduce((h,d)=>[...h,...d.representations],[]);this.audioBufferManager=us.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=ds().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:ni.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&&ds().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){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$)),this.representationSubscription.add(hs(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),gt(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(hs(...Md.map(e=>oi(this.element,e))).pipe(Lo(e=>this.videoBufferManager?.getPlaybackBufferState()),Ro(Ft),Lo(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(hs(...Md.map(e=>oi(this.element,e))).pipe(Lo(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),bf()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Ro(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=gf(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(ls(this.element)||ls(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as qa,combine as If,ErrorCategory as Ef,filter as Bo,filterChanged as wf,fromEvent as kf,isNonNullable as xf,map as Do,merge as ps}from"@vkontakte/videoplayer-shared/evergreen";var Wa=class extends Qa{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){qa(this.manifest),qa(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(t=>t.representations).flatMap(t=>{let i=[];return t.duration&&i.push(t.duration),Me(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){qa(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){qa(this.element);let e=ps(kf(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(Bo(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(ps(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=ps(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Do(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=ps(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Do(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=If({allBuffersFull:e,someBufferEnded:t}).pipe(wf(),Do(({allBuffersFull:s,someBufferEnded:a})=>s&&a),Bo(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:Ef.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(ps(this.forceEnded$,i).pipe(Bo(s=>xf(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var Gi=class extends Rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Pf()).subscribe(s=>{let a=[...this.videoTracksMap.entries()].find(([,{representation:d}])=>d.id===s);if(!a){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[n,{stream:o}]=a,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===o.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(n),e.currentVideoStream$.next(Ma(o));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r))}getPlayer(){return new Wa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as Jf,assertNonNullable as Zf,combine as eb,debounce as tb,ErrorCategory as Ud,filter as jo,filterChanged as Is,fromEvent as ib,isNonNullable as Hd,isNullable as rb,map as Es,merge as ws,observableFrom as sn,once as jd,Subscription as sb,throttle as ab}from"@vkontakte/videoplayer-shared/evergreen";var Ee=(u,e,t=0)=>{for(let i=0;i<u.length;i++)if(u.start(i)*1e3-t<=e&&u.end(i)*1e3+t>e)return!0;return!1};import{abortable as Fo,assertNonNullable as Zi,combine as er,ErrorCategory as qe,filter as en,filterChanged as vs,flattenObject as ys,fromEvent as yt,getTraceSubscriptionMethod as _f,interval as _o,isNonNullable as Ts,isNullable as Nd,map as tr,merge as ci,now as Uo,Subject as Tt,Subscription as Fd,SubscriptionRemovable as Uf,tap as Hf,throttle as jf,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Af,ErrorCategory as Rd,Subject as Ld}from"@vkontakte/videoplayer-shared/evergreen";var $f=18,Bd=!1;try{Bd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=$f}catch(u){console.error(u)}var Co=class{constructor(e,t=!1){this.bufferFull$=new Ld;this.error$=new Ld;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Rd.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Bd&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Rd.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Af(t)}}},Dd=Co;var Yi=u=>{let e=0;for(let t=0;t<u.length;t++)e+=u.end(t)-u.start(t);return e*1e3};import{abortable as Ut,assertNonNullable as Re,ErrorCategory as St,fromEvent as Vo,getExponentialDelay as Oo,isHigher as Mf,isNonNullable as Ht,isNullable as ne,now as Ga,once as Rf,Subject as Lf,Subscription as Bf,ValueSubject as ui}from"@vkontakte/videoplayer-shared/evergreen";var ms=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new ui(0);this.currentLowLatencySegmentLength$=new ui(0);this.currentSegmentLength$=new ui(0);this.onLastSegment$=new ui(!1);this.fullyBuffered$=new ui(!1);this.playingRepresentation$=new ui(void 0);this.playingRepresentationInit$=new ui(void 0);this.error$=new Lf;this.gaps=[];this.subscription=new Bf;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Dd(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Vo(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,o=this.mediaSource.readyState;o!=="open"&&(n={id:`SegmentEjection_source_${o}`,category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(Vo(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 n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=this.getForwardBufferDuration(n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(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=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();Ht(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=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();Ht(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=Ut(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Ne(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Re(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Re(s,"No segments for starting representation");let a=this.initData.get(i);if(Re(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ne(n)||ne(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Re(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Ht(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(){!ne(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(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||Ht(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),ne(r)||ne(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);Ht(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=Nt(i),m=Nt(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ht(p)&&Ht(m)&&Mf(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=[];if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Ht(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!Ne(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ne(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),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Ne(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:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ut(n,async function*(){let h=Oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ga(),!h)return;let d=new DataView(h),l=Qe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ne(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let o=Oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Vo(window,"online").pipe(Rf()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ga(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ne(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(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ga(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ne(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?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ga();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress: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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=Qe(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(!p)continue;let f=Qe(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===l?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:St.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Po(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,n=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qe(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:c,dataView:h,segments:d}=o,l=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ne(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:St.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let r=[],s=0,a=o=>{o.sort((h,d)=>h.from-d.from);let c=[o[0]];for(let h=1;h<o.length;h++){let{from:d,to:l}=o[h],p=c[c.length-1];p.to>=d?p.to=Math.max(p.to,l):c.push(o[h])}return c},n=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let c=Po(o)?o.size??0:o.byte.to-o.byte.from;s+=c};for(let o of this.segments.values())for(let c of o){let h=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||d)&&c.status==="fed"&&n(c)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let c=this.sourceBuffer.buffered.start(o)*1e3,h=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let l of this.segments.values())for(let p of l)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)&&d++;if(d===this.segments.size){let l={time:{from:c,to:h},url:"",status:"none"};n(l)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let h of c)h.time.from>=e+o&&h.status==="fed"&&n(h)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,h)=>c||h,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!D(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||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let a=0;a<s.length;a++){let n=s.start(a)*1e3,o=s.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let a=Math.round(s.from),n=Math.round(s.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:St.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ne(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ne(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),n=Math.ceil(r.time.to),o=e.some(h=>h.from-t<=a&&h.to+t>=n),c=e.filter(h=>a>=h.from&&a<h.to-t||n>h.from+t&&n<=h.to);o||(c.length===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:St.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as fs,assertNever as Cd,fromEvent as Vd,merge as Df,now as bs,Subject as Ki,ValueSubject as No,flattenObject as Xi,ErrorCategory as gs,SubscriptionRemovable as Cf}from"@vkontakte/videoplayer-shared/evergreen";var Ka=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Ki;this.firstBytesManifest$=new Ki;this.firstBytesRequested$=new Ki;this.firstBytesReceived$=new Ki;this.lastConnectionType$=new No(void 0);this.lastConnectionReused$=new No(void 0);this.lastRequestFirstBytes$=new No(void 0);this.recoverableError$=new Ki;this.error$=new Ki;this.abortAllController=new AbortController;this.subscription=new Cf;this.fetchManifest=fs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ya);return r?(t.log("success",Xi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Xi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=fs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:h=!1}={}){let d=e,l=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(d,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:Cd(t)}this.requestQuic&&(d=Ze(d));let m=this.abortAllController.signal,f;if(a){let T=new AbortController;if(f=Df(Vd(this.abortAllController.signal,"abort"),Vd(a,"abort")).subscribe(()=>{try{T.abort()}catch(O){Ya(O)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(O){Ya(O)}m=T.signal}let b=0,g=bs();p.log("startRequest",Xi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(d,{priority:s,headers:l,signal:m},{ignoreNetworkErrors:h}),y=bs();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(y-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let T=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!n){this.unsubscribeAbortSubscription(f);let T=bs(),O={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",Xi(O)),p.end(),S.arrayBuffer()}let v=S.body;if(n){let T;[v,T]=S.body.tee(),this.throughputEstimator?.trackStream(T,o)}let w=v.getReader(),P,A=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(A)&&(P=A),!P&&i&&(P=i.to-i.from+1);let E=P?new Uint8Array(P):new Uint8Array(0),L=!1,k=T=>{this.unsubscribeAbortSubscription(f),L=!0,Ya(T)},N=fs(m,async function*({done:T,value:O}){if(b===0&&(this.lastRequestFirstBytes$.next(bs()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!T&&O){if(c&&P)E.set(O,b),b+=O.byteLength;else{let R=new Uint8Array(E.length+O.length);R.set(E),R.set(O,E.length),E=R,b+=O.byteLength}r?.(new DataView(E.buffer),b),yield w?.read().then(N,k)}}.bind(this));yield w?.read().then(N,k),this.unsubscribeAbortSubscription(f);let B=bs(),I={failed:L,requestStartedAt:g,requestEndedAt:B,duration:B-g};return L?(p.error("endRequest",Xi(I)),p.end(),null):(p.log("endRequest",Xi(I)),p.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=fs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},measureThroughput:!1,...i});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=fs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Cd(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:gs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:gs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:gs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:gs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:gs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ya=u=>{if(!Ie(u))throw u};import{isNullable as Vf,ValueSubject as Od}from"@vkontakte/videoplayer-shared/evergreen";var jt=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 Od(e.initial),this.debounced$=new Od(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`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 n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-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)&&(Vf(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 Xa=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pt(this.slow,e,this.params.emaAlphaSlow),this.fast=pt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ja=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=co(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pt(this.emaSmoothed,e,this.params.emaAlpha);let i=Yc(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Za=class extends jt{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?pt(this.smoothed,t,this.params.emaAlpha):t}};var vt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Xa({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ja({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 Za({initial:e,label:"liveEdgeDelay",...t})}};var Ji=(u,e)=>{u&&u.playbackRate!==e&&(u.playbackRate=e)};import{isNullable as Of,ValueSubject as Nf}from"@vkontakte/videoplayer-shared/evergreen";var Ss=class u{constructor(e,t){this.currentRepresentation$=new Nf(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(!Of(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,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.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=u.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=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ne(t.segmentReference))}};var zf=["timeupdate","progress","play","seeked","stalled","waiting"],Qf=["timeupdate","progress","loadeddata","playing","seeked"];var tn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Fd;this.subscriptionRemovable=new Uf;this.representationSubscription=new Fd;this.state$=new V("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.firstBytesManifest$=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.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=Fo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(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:qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Fo(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:qe.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Di(e)??{id:"ManifestParsing",category:qe.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";if(d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p),d&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:qe.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",ys(n)),n}.bind(this));this.initRepresentations=Fo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ys({initialVideo:e,initialAudio:t,sourceHls:i})),Zi(this.manifest),Zi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(yt(d,"error").pipe(en(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((d,l)=>[...d,...l.representations],[]);if(this.videoBufferManager=new ms("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Ts(t)){let d=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=new ms("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}if(Ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ss(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ci(...Qf.map(d=>yt(this.element,d))).pipe(tr(d=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),vs(),Hf(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vs()).subscribe(l=>this.liveStreamEndTimestamp=Uo())),this.subscription.add(yt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:l}=this.tuning.dash;this.livePauseWatchdogSubscription=_o(l).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+l,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(yt(this.element,"play").subscribe(l=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(er({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(tr(({isActiveLive:l,isLowLatency:p})=>l&&p),vs()).subscribe(l=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(er({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(en(({bufferLength:l,isActiveLive:p,isLowLatency:m})=>p&&m&&!!l)).subscribe(({bufferLength:l})=>this.liveBuffer.next(l))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(l=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!l)return;let p=this.liveSeekableDuration$.getValue()-l/1e3;this.liveSeekableDuration$.next(Math.max(p,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+l/1e3)})),this.representationSubscription.add(er({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(en(({isLive:l})=>l),vs((l,p)=>p.bufferLength<l.bufferLength),tr(({rtt:l,bufferLength:p,segmentServerLatency:m})=>{let f=$t(this.manifestUrlString,2);return(l/2+p+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(er({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:l,isActiveLive:p,isLowLatency:m})=>{if(!m||!p)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=l-f;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*g),Ji(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(l=>{let p=0;if(l){let m=(this.element?.currentTime??0)*1e3;p=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==p&&this.liveLoadBufferLength$.next(p)}));let d=0;this.representationSubscription.add(er({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(jf(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:l,bufferLength:p})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=$t(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(l)?l:p,w=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let A="none";if(w?A="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(E=>E.proceedLowLatencyLive()),A="active_low_latency"):f!==0&&v<g?A="live_forward_buffering":v<g+y&&(A="live_with_target_offset"),isFinite(l)&&(d=l>d?l:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let E=d-(g+S),L=this.normalizeLiveOffset(Math.trunc(f+E/m)),k=Math.abs(L-f),N=0;!l||k<=this.tuning.dashCmafLive.offsetCalculationError?N=f:L>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=te(this.manifestUrlString,N,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},l=>{this.error$.next({id:"updateLive",category:qe.VIDEO_PIPELINE,thrown:l,message:"Failed to update live with subscription"})}))}let o=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(tr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(tr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=er({allBuffersFull:o,someBufferEnded:c}).pipe(vs(),tr(({allBuffersFull:d,someBufferEnded:l})=>d&&l),en(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(l=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){l();return}this.error$.next({id:"OpenOfStream",category:qe.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),l()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ne(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Ts(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=_o(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:qe.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 Ka({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Zi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Uo()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Zi(this.element),this.state$.setState("running"),this.subscription.add(ci(...zf.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:a}=this.tuning.dash,n=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let h=this.currentStallDuration$.getValue();h+=a,this.currentStallDuration$.next(h);let d={timeInWaiting:h},l=Uo(),p=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,b=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,S=b<p&&l-m>r,y=this.audioBufferManager&&g<p&&l-f>r;if((!t||c)&&((S||y)&&h>r||h>=i))throw new Error(`Stall timeout exceeded: ${h} ms`);if(n&&h%s===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:qe.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),d.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),d.position=v}this.tracer.log("stallIntervalCallback",ys(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=_o(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:qe.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Zi(this.element),Zi(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),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Nd(this.element)||Nd(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ys({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ts(this.element)&&Ts(this.source)&&Ts(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=_f(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(r&&c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a.push(1/0):a.push(c.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ys(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as qf,map as Wf,observeElementSize as Gf,Subscription as Yf,ValueSubject as Ho,noop as Kf}from"@vkontakte/videoplayer-shared/evergreen";var rn=class{constructor(){this.subscription=new Yf;this.pipSize$=new Ho(void 0);this.videoSize$=new Ho(void 0);this.elementSize$=new Ho(void 0);this.pictureInPictureWindowRemoveEventListener=Kf}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Gf(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(qf({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Wf(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new sb;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Bi;this.elementSizeManager=new rn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Jf(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Dt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new tn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;rb(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Ud.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(jo(d=>!!d.length),jd()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Es(d=>d.to.state!=="none"),Is());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(jo(Hd),jd()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Es(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Zf(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(ko(b));let g=[];for(let S of b.representations){let y=ns(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(xo(f));let b=[];for(let g of f.representations){let S=Nt({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=gd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=ws(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ib(this.video,"progress")).pipe(jo(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(ab(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);Hd(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(eb({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ws(sn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Es(d=>d.to)))}).pipe(Es(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Is()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Is()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xo(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Is()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(ko(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Es(({to:d})=>d==="ready"),Is());this.subscription.add(ws(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ws(c,this.player.state$.stateChangeEnded$,sn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sn(["init"])).pipe(tb(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:E})=>E===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:E})=>E===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:E})=>E===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ud.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var ks=class extends di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as zo,merge as zd,filter as Qd,filterChanged as qd,isNullable as Qo,map as Wd,ValueSubject as qo,isNonNullable as nb}from"@vkontakte/videoplayer-shared/evergreen";var xs=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new qo(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qd()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Wd(o=>o.to)).subscribe(this.player.isLowLatency$)).add(zo({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wd(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(zo({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:zd(r.playbackRateState$,new qo(1))}).pipe(Qd(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||Qo(h)||(t=o-h)})).add(zo({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:zd(r.playbackRateState$,new qo(1))}).pipe(qd((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||Qo(o)||Qo(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=Sd(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Qd(o=>nb(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as Db,assertNonNullable as Cb,combine as Vb,debounce as Ob,ErrorCategory as ul,filter as nu,filterChanged as Vs,fromEvent as Nb,isNonNullable as cl,isNullable as Fb,map as Os,merge as Ns,observableFrom as pn,once as dl,Subscription as _b}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as tu,assertNonNullable as sr,combine as ar,ErrorCategory as tt,filter as dn,filterChanged as Bs,flattenObject as Ds,fromEvent as ut,getTraceSubscriptionMethod as Eb,interval as iu,isNonNullable as Cs,isNullable as nl,map as nr,merge as mi,now as ru,Subject as It,Subscription as su,SubscriptionRemovable as wb,tap as kb,throttle as ol,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as ob,ErrorCategory as Gd,Subject as Yd}from"@vkontakte/videoplayer-shared/evergreen";var ub=18,Kd=!1;try{Kd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=ub}catch(u){console.error(u)}var Wo=class{constructor(e,t=!1){this.bufferFull$=new Yd;this.error$=new Yd;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Gd.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Kd&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Gd.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:ob(t)}}},Xd=Wo;import{abortable as zt,assertNonNullable as Le,ErrorCategory as hi,fromEvent as Xo,getExponentialDelay as Jo,isHigher as pb,isNonNullable as Qt,isNullable as oe,now as on,once as mb,Subject as fb,Subscription as bb,ValueSubject as pi}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as cb,throttleFn as db}from"@vkontakte/videoplayer-shared/evergreen";var Ps=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??cb({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Jd=({id:u,bitrate:e})=>({id:u,bitrate:e}),Zd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),el=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Go=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Yo=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ko=u=>"url"in u,Fe=u=>u.type==="template";var tl=u=>{u.sort((t,i)=>t.from-i.from);let e=[u[0]];for(let t=1;t<u.length;t++){let{from:i,to:r}=u[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(u[t])}return e},li=(u,e)=>{for(let t of u)if(e(t))return t;return null},il=u=>{let e=!1,t=db(()=>{e=!0},u);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as lb,Subscription as hb}from"@vkontakte/videoplayer-shared/evergreen";var an=u=>{let e=[];for(let t=0;t<u.length;t++){let i=Math.floor(u.start(t)*1e3),r=Math.ceil(u.end(t)*1e3);e.push(i,r)}return e};var nn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new hb;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(lb(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!D(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=an(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],n=t[i+1];if(a>r||n<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var As=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new pi(0);this.currentLowLatencySegmentLength$=new pi(0);this.currentSegmentLength$=new pi(0);this.onLastSegment$=new pi(!1);this.fullyBuffered$=new pi(!1);this.playingRepresentation$=new pi(void 0);this.playingRepresentationInit$=new pi(void 0);this.error$=new fb;this.gaps=[];this.subscription=new bb;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xd(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new nn(this.mediaSource,this.sourceBuffer),this.subscription.add(Xo(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Xo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:hi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=ae(this.sourceBuffer.buffered,n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(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=zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();Qt(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=zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();Qt(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=zt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Fe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Le(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Le(s,"No segments for starting representation");let a=this.initData.get(i);if(Le(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Le(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(oe(n)||oe(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Le(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Qt(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(){!oe(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(oe(e)||oe(this.downloadingRepresentationId)||oe(this.playingRepresentationId)||oe(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||Qt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),oe(r)||oe(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);Qt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=Ps(i),m=Ps(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Qt(p)&&Qt(m)&&pb(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ae(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h?.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&ae(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ae(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Qt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Fe(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Fe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Fe(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:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await zt(n,async function*(){let h=Jo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=on(),!h)return;let d=new DataView(h),l=Qe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Fe(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await zt(a,async function*(){let o=Jo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Xo(window,"online").pipe(mb()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=on(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Fe(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(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=on(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Fe(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?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=on();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}: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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=Qe(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:c}=o,h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(p){if(c.status==="downloading"&&m){c.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),b=o.loadedBytes===l?f:Qe(n.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(c.status="partially_fed",o.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(o.fedBytes+=b.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(oe(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:hi.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",Ko(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?zt(this.destroyAbortController.signal,async function*(){let n=Jo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qe(e.mime),r)).then(n=>{if(!n)return;let{init:o,dataView:c,segments:h}=n,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let l=h;this.isLive&&Fe(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:hi.WTF,message:"loadInit threw",thrown:n})});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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||oe(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=n=>{if(s>=t)return;r.push({...n.time});let o=Ko(n)?n.size??0:n.byte.to-n.byte.from;s+=o};for(let n of this.segments.values())for(let o of n){let c=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||h)&&o.status==="fed"&&a(o)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let o=this.sourceBuffer.buffered.start(n)*1e3,c=this.sourceBuffer.buffered.end(n)*1e3,h=0;for(let d of this.segments.values())for(let l of d)["none","partially_ejected"].includes(l.status)&&Math.round(l.time.from)<=Math.round(o)&&Math.round(l.time.to)>=Math.round(c)&&h++;if(h===this.segments.size){let d={time:{from:o,to:c},url:"",status:"none"};a(d)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let c of o)c.time.from>=e+n&&c.status==="fed"&&a(c)}return r.length?(r=tl(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,c)=>o||c,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||oe(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,n=i.end(s)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){r=void 0;break}n>t.time.from&&n<t.time.to&&(r.from=n),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),a=Math.round(r.to);for(let n=0;n<i.length;n++)if(s>=Math.round(i.start(n)*1e3)&&a<=Math.round(i.end(n)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:hi.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(oe(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||oe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=an(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=!1,c=0;for(let h=0;h<e.length;h+=2){let d=e[h],l=e[h+1];o||(o=d-t<=a&&l+t>=n),(a>=d&&a<l-t||n>d+t&&n<=l)&&(c+=1)}o||(c===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:hi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as $s,assertNever as rl,fromEvent as sl,merge as gb,now as Ms,Subject as ir,ValueSubject as Zo,flattenObject as rr,ErrorCategory as Rs,SubscriptionRemovable as Sb}from"@vkontakte/videoplayer-shared/evergreen";var cn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new ir;this.firstBytesManifest$=new ir;this.firstBytesRequested$=new ir;this.firstBytesReceived$=new ir;this.lastConnectionType$=new Zo(void 0);this.lastConnectionReused$=new Zo(void 0);this.lastRequestFirstBytes$=new Zo(void 0);this.recoverableError$=new ir;this.error$=new ir;this.abortAllController=new AbortController;this.subscription=new Sb;this.fetchManifest=$s(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(un);return r?(t.log("success",rr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$s(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:rl(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=gb(sl(this.abortAllController.signal,"abort"),sl(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){un(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){un(T)}p=I.signal}let f=0,b=Ms();l.log("startRequest",rr({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested$.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=Ms();if(!g)return l.error("error",{message:"No response in request"}),l.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){this.unsubscribeAbortSubscription(m);let I=Ms(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",rr(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),w,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(w=P),!w&&i&&(w=i.to-i.from+1);let A=w?new Uint8Array(w):new Uint8Array(0),E=!1,L=I=>{this.unsubscribeAbortSubscription(m),E=!0,un(I)},k=$s(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Ms()-b),this.firstBytesReceived$.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&T){if(c&&w)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),this.unsubscribeAbortSubscription(m);let N=Ms(),B={failed:E,requestStartedAt:b,requestEndedAt:N,duration:N-b};return E?(l.error("endRequest",rr(B)),l.end(),null):(l.log("endRequest",rr(B)),l.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=$s(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=$s(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}=Ci(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:rl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Rs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Rs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Rs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Rs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Rs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},un=u=>{if(!Ie(u))throw u};import{isNullable as vb,ValueSubject as yb}from"@vkontakte/videoplayer-shared/evergreen";var Ls=class u{constructor(e,t){this.currentRepresentation$=new yb(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(!vb(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,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.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=u.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=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Fe(t.segmentReference))}};var xb=["progress","play","seeked","stalled","waiting"],Pb=["timeupdate","progress","loadeddata","playing","seeked"];var ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new su;this.subscriptionRemovable=new wb;this.representationSubscription=new su;this.state$=new V("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new It;this.manifestRequested$=new It;this.firstBytesManifest$=new It;this.manifestReceived$=new It;this.firstBytesRequested$=new It;this.firstBytesReceived$=new It;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new It;this.fetcherError$=new It;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new It;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=tu(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(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:tt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=tu(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:tt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Di(e)??{id:"ManifestParsing",category:tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Ds(n)),n}.bind(this));this.initRepresentations=tu(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ds({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new su,this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(ut(l,"error").pipe(dn(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new As("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Cs(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new As("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}Ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ls(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...Pb.map(l=>ut(this.element,l))).pipe(nr(l=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Bs(),kb(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(ut(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Bs()).subscribe(p=>this.liveStreamEndTimestamp=ru())),this.subscription.add(ut(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=iu(1e3).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ut(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ar({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(nr(({isActiveLive:p,isLowLatency:m})=>p&&m),Bs()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(ar({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(dn(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(ar({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(dn(({isLive:p})=>p),Bs((p,m)=>m.bufferLength<p.bufferLength),nr(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=$t(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ar({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(y)>g&&(v=1+Math.sign(y)*S),Ji(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add(ar({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ol(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=$t(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let E="none";if(P?E="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),E="active_low_latency"):b!==0&&w<S?E="live_forward_buffering":w<S+v&&(E="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),E==="live_forward_buffering"||E==="live_with_target_offset"){let L=l-(S+y),k=this.normolizeLiveOffset(Math.trunc(b+L/f)),N=Math.abs(k-b),B=0;!p||N<=this.tuning.dashCmafLive.offsetCalculationError?B=b:k>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(B=k),this.manifestUrlString=te(this.manifestUrlString,B,2)}(E==="live_with_target_offset"||E==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:tt.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let c=mi(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(nr(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),h=mi(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(nr(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=ar({allBuffersFull:c,someBufferEnded:h}).pipe(Bs(),nr(({allBuffersFull:l,someBufferEnded:p})=>l&&p),dn(l=>l));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(mi(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Fe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Cs(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=iu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:tt.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 cn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ru()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(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(){sr(this.element),this.state$.setState("running");let e=ut(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ol(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(mi(...xb.map(t=>ut(this.element,t)),ut(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:tt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ut(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ut(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ru(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,c=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=c<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,l=this.audioBufferManager&&h<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||l)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:tt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Ds(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=iu(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:tt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){sr(this.element),sr(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),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(nl(this.element)||nl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ds({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Cs(this.element)&&Cs(this.source)&&Cs(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Eb(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,n=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a=1/0:(a===null||c.to>a)&&(a=c.to));if(a!==null){let o=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Ds({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Ab,map as $b,observeElementSize as Mb,Subscription as Rb,ValueSubject as au,noop as Lb}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(){this.subscription=new Rb;this.pipSize$=new au(void 0);this.videoSize$=new au(void 0);this.elementSize$=new au(void 0);this.pictureInPictureWindowRemoveEventListener=Lb}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Mb(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Ab({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($b(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var fi=class{constructor(e){this.subscription=new _b;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Bi;this.elementSizeManager=new hn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Db(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Dt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Fb(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ul.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(nu(d=>!!d.length),dl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Os(d=>d.to.state!=="none"),Vs());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(nu(cl),dl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Os(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Cb(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(Go(b));let g=[];for(let S of b.representations){let y=Jd(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(Yo(f));let b=[];for(let g of f.representations){let S=Ps({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=Zd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:n}=this.params.tuning.dash,o=n&&il(n)||null;this.subscription.add(Ns(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Nb(this.video,"progress")).pipe(nu(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l||d==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=li(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);cl(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(Vb({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Ns(pn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Os(d=>d.to)))}).pipe(Os(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Vs()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Vs()).subscribe(d=>{let l=li(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Yo(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Vs()).subscribe(d=>{let l=li(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Go(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Os(({to:d})=>d==="ready"),Vs());this.subscription.add(Ns(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,pn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ns(c,this.player.state$.stateChangeEnded$,pn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Ns(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pn(["init"])).pipe(Ob(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=li(this.videoTracksMap.keys(),E=>E.id===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=li(this.videoStreamsMap.keys(),E=>E.id===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=g?.id&&li(this.audioStreamsMap.keys(),E=>E.id===g.id)||this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;P&&A?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=A):P&&!A&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ul.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var Fs=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ou,merge as ll,filter as hl,filterChanged as pl,isNullable as uu,map as ml,ValueSubject as cu,isNonNullable as Ub}from"@vkontakte/videoplayer-shared/evergreen";var _s=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new cu(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(pl()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(ml(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ou({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ml(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o+c:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(hl(o=>Ub(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(ou({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ll(r.playbackRateState$,new cu(1))}).pipe(hl(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||uu(h)||(t=o-h)})).add(ou({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ll(r.playbackRateState$,new cu(1))}).pipe(pl((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||uu(o)||uu(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=el(o);this.params.output.availableTextTracks$.next([c])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var fl="X-Playback-Duration",du=async u=>{let e=await fetch(u),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(fl)?parseInt(e.headers.get(fl),10):void 0};import{assertNever as Jb,combine as Zb,debounce as eg,ErrorCategory as bn,filter as tg,filterChanged as ig,isNonNullable as Sl,isNullable as gn,map as vl,merge as rg,observableFrom as sg,Subscription as ag,ValueSubject as hu,VideoQuality as ng}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Hb,getExponentialDelay as jb}from"@vkontakte/videoplayer-shared/evergreen";var zb=u=>{let e=null;if(u.QUALITY&&(e=nt(u.QUALITY)),!e&&u.RESOLUTION){let[t,i]=u.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Hb({width:t,height:i})}return e??null},Qb=(u,e)=>{let t=u.split(`
|
|
178
|
-
`),i=[],r=[];for(let
|
|
179
|
-
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let o=r[++a],c=new URL(o,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:c}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),l=new Date(i.programDateTime).valueOf();i.segmentStartTime=l-d}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=o;let c=new Date(o);c.setMilliseconds(0),s=c.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Wb(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Xb.WTF,thrown:t,message:e})}};var Us=class{constructor(e){this.subscription=new ag;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new hu([]);this.liveOffset=new ei;this.manifestStartTime$=new hu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Jb(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ng.INVARIANT,url:this.params.source.url};let t=(i,r)=>mn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new De(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:bn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:bn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new hu(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:bn.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(ig(),vl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&Sl(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let l=this.manifests$.getValue().find(p=>p.id===d);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(se(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(Zb({startTime:this.manifestStartTime$.pipe(tg(Sl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:o})=>this.params.output.liveTime$.next(n+o*1e3),i)),this.subscription.add(this.manifests$.pipe(vl(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=rg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sg(["init"])).pipe(eg(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(gn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:o}=t?.to??i??{};for(let[c,h]of[[n,"mq"],[o,"lq"]]){let d=String(parseFloat(c||""));h&&c&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=te(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),du(a).then(n=>{if(!gn(n))this.maxSeekBackTime$.next(n);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(gn(o)||!isFinite(o))&&fetch(a).then(c=>c.text()).then(c=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){let d=new URL(h,a).toString();du(d).then(l=>{gn(l)||this.maxSeekBackTime$.next(l)})}}).catch(()=>{})}})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=te(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as og,debounce as ug,ErrorCategory as pu,fromEvent as mu,isNonNullable as cg,isNullable as dg,map as yl,merge as Tl,observableFrom as Il,Subscription as lg,ValueSubject as El,VideoQuality as hg}from"@vkontakte/videoplayer-shared/evergreen";var Hs=class{constructor(e){this.subscription=new lg;this.videoState=new V("stopped");this.manifests$=new El([]);this.unmuteAfterBrowserResetsHappened=new El(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return og(t)}};this.textTracksManager=new De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:hg.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),mn(te(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:pu.WTF,message:"HlsProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(yl(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&cg(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(se(m.url)))}let d=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n.state==="requested"&&this.seek(n.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(yl(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Tl(mu(n,"addtrack"),mu(n,"removetrack"),mu(n,"change"),Il(["init"])).subscribe(()=>{for(let o=0;o<n.length;o++)n[o].mode="hidden"},i))}let a=Tl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Il(["init"])).pipe(ug(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(dg(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[n,o]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));o&&n&&r.searchParams.set(o,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as pg,assertNonNullable as wl,debounce as mg,ErrorCategory as kl,isHigherOrEqual as fg,isLowerOrEqual as bg,isNonNullable as gg,merge as Sg,observableFrom as vg,Subscription as yg,map as Tg}from"@vkontakte/videoplayer-shared/evergreen";var js=class{constructor(e){this.subscription=new yg;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:o}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return pg(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"MpegProvider",category:kl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Tg(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&gg(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let o=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(o!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(o),h.playbackRate=o)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Sg(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vg(["init"])).pipe(mg(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ze(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(se(t))}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=ze(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||xi(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?bg(r,e.max):!0,o=e.min?fg(r,e.min):!0;n&&o||i(e)}};import{assertNever as Pl,debounce as kg,merge as Al,observableFrom as xg,Subscription as Pg,map as $l,ValueSubject as Ag,ErrorCategory as bu,VideoQuality as $g}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Ig}from"@vkontakte/videoplayer-shared/evergreen";var xl=["stun:videostun.mycdn.me:80"],Eg=1e3,wg=3,fu=()=>null,Sn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=fu;this.externalStopCallback=fu;this.externalErrorCallback=fu;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:xl}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Ig.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Eg)}normalizeOptions(e={}){let t={stunServerList:xl,maxRetryNumber:wg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var zs=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new Ag(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Pl(e)}};this.subscription=new Pg,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new Sn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:bu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Al(this.videoState.stateChangeStarted$.pipe($l(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe($l(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(a,n)=>this.subscription.add(a.subscribe(n,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Pl(a.to)}},i)).add(Al(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xg(["init"])).pipe(kg(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:$g.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:bu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var or=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Qs,assertNonNullable as Et,ErrorCategory as vn,filter as Cl,isNonNullable as Vl,isNullable as Vg,map as Og,merge as Ng,once as Fg,Subject as Z,Subscription as Ol,ValueSubject as F,flattenObject as gu,devNull as _g,getWindow as Ug}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Mg,map as Ml,Subscription as Rg,Subject as Lg}from"@vkontakte/videoplayer-shared/evergreen";var Rl=u=>new Mg(e=>{let t=new Rg,i=u.desiredPlaybackState$.stateChangeStarted$.pipe(Ml(({from:c,to:h})=>`${c}-${h}`)),r=u.desiredPlaybackState$.stateChangeEnded$,s=u.providerChanged$.pipe(Ml(({type:c})=>c!==void 0)),a=new Lg,n=0,o="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),o=c,n=window.setTimeout(()=>a.next(c),u.maxTransitionInterval),C({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{C({m:"hangup.cl",id:n}),window.clearTimeout(n),o="unknown",n=0})),t.add(s.subscribe(c=>{n&&(C({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(o),u.maxTransitionInterval),C({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Bg,Subscription as Dg,combine as Cg,filter as Bl,once as Dl}from"@vkontakte/videoplayer-shared/evergreen";function Ll(){return new(window.AudioContext||window.webkitAudioContext)}var ur=class u{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Dg;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Bl(s=>!!s.type),Dl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Cg({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Bl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Dl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ll();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:u.errorId,category:Bg.VIDEO_PIPELINE,message:e?.message??`${u.errorId} exception`,thrown:e})}};var Hg={chunkDuration:5e3,maxParallelRequests:5},qs=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new Z;this.noAvailableProvidersError$=new Z;this.volumeMultiplierError$=new Z;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableVideoCodecs$:new F([]),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),availableAudioCodecs$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),currentNativeBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new Z,fetcherError$:new Z,fetcherRecoverableError$:new Z,warning$:new Z,willSeekEvent$:new Z,soundProhibitedEvent$:new Z,seekedEvent$:new Z,loopedEvent$:new Z,endedEvent$:new Z,manifestRequested$:new Z,firstBytesManifest$:new Z,manifestReceived$:new Z,firstBytesRequested$:new Z,firstBytesReceived$:new Z,firstBytesEvent$:new Z,loadedMetadataEvent$:new Z,firstFrameEvent$:new Z,canplay$:new Z,isLive$:new F(void 0),isLiveEnded$:new F(null),canPlayLiveTailBuffer$:new F(!1),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new Z,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new Ol;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=On([...cd(this.params.tuning),...ud(this.params.tuning)]).filter(c=>Vl(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gu(s)),this.screenFormatsIterator=new or(s);let a=[...Eo(!0),...Eo(!1)];this.chromecastFormatsIterator=new or(a.filter(c=>Vl(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&n!==1&&ur.isSupported()&&(this.volumeMultiplierManager=new ur(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}init(){C.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new or(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Vg(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:vn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Qs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),this.params.tuning.useNewDashProvider?new Fs({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ks({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),this.params.tuning.useNewDashProvider?new _s({...n,source:o}):new xs({...n,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return Et(o),new Hs({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new Us({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new js({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new jc({...n,source:o,config:{...Hg,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new zs({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,n={meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof lt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return Et(c),new fr({...n,chromecastConnector:c})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Et(o),new vr({...n,connection:o})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Qs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Qs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Qs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Ol,t=!1,i=0;e.add(Ng(this.providerOutput.error$.pipe(Cl(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Rl({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Og(s=>({id:`ProviderHangup:${s}`,category:vn.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let s=this.params.desiredState.playbackState.transitionEnded$.pipe(Cl(({to:a})=>a==="playing"),Fg()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=C.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&Ug().console.log(`===== DASH_LIVE DEBUG START ====
|
|
180
|
-
`,
|
|
181
|
-
`+
|
|
177
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var ic=n=>{if(!n?.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ue=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>tc(a)?o:tc(u)?a:a.padStart(parseInt(u,10),"0"))}return t},es=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),o=s.at(0)??"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),l=a.getElementsByTagName("vk:Attrs")[0],p=l?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=l?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let b,S=a.getAttribute("mediaPresentationDuration"),I=[...a.getElementsByTagName("Period")],v=I.reduce((D,E)=>({...D,[E.id]:E.children}),{}),x=I.reduce((D,E)=>({...D,[E.id]:E.getAttribute("duration")}),{});S?b=ic(S):Object.values(x).filter(D=>D).length&&!u?b=Object.values(x).reduce((D,E)=>D+(ic(E)??0),0):f&&(b=parseInt(f,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let D of I.map(E=>E.id))for(let E of v[D]){let _=E.getAttribute("id")??"id"+(A++).toString(10),C=E.getAttribute("mimeType")??"",T=E.getAttribute("codecs")??"",y=E.getAttribute("contentType")??C?.split("/")[0],O=E.getAttribute("profiles")?.split(",")??[],$=ec(E.getAttribute("lang")??"")??{},F=E.querySelector("Label")?.textContent?.trim()??void 0,W=E.querySelectorAll("Representation"),Z=E.querySelector("SegmentTemplate"),te=E.querySelector("Role")?.getAttribute("value")??void 0,ue=y,ce={id:_,language:$.language,isDefault:te==="main",label:F,codecs:T,hdr:ue==="video"&&Rn(T),mime:C,representations:[]};for(let U of W){let N=U.getAttribute("lang")??void 0,le=F??E.getAttribute("label")??U.getAttribute("label")??void 0,he=U.querySelector("BaseURL")?.textContent?.trim()??"",ae=new URL(he||o,e).toString(),Me=U.getAttribute("mimeType")??C,lt=U.getAttribute("codecs")??T??"",Ve;if(y==="text"){let ke=U.getAttribute("id")||"",dt=$.privateuse?.includes("x-auto")||ke.includes("_auto"),Oe=U.querySelector("SegmentTemplate");if(Oe){let xi={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Jr=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,Zr=parseInt(Oe.getAttribute("startNumber")??"",10)??1,Wt=parseInt(Oe.getAttribute("timescale")??"",10),Vs=Oe.querySelectorAll("SegmentTimeline S")??[],Gt=Oe.getAttribute("media");if(!Gt)continue;let ea=[],ta=0,ia="",Yt=0,ki=Zr,me=0;for(let Ne of Vs){let Mt=parseInt(Ne.getAttribute("d")??"",10),Re=parseInt(Ne.getAttribute("r")??"",10)||0,pt=parseInt(Ne.getAttribute("t")??"",10);me=Number.isFinite(pt)?pt:me;let Rt=Mt/Wt*1e3,Kt=me/Wt*1e3;for(let Qe=0;Qe<Re+1;Qe++){let ht=Ue(Gt,{...xi,segmentNumber:ki.toString(10),segmentTime:(me+Qe*Mt).toString(10)}),Xt=(Kt??0)+Qe*Rt,Ai=Xt+Rt;ki++,ea.push({time:{from:Xt,to:Ai},url:ht})}me+=(Re+1)*Mt,ta+=(Re+1)*Rt}Yt=me/Wt*1e3,ia=Ue(Gt,{...xi,segmentNumber:ki.toString(10),segmentTime:me.toString(10)});let Pi={time:{from:Yt,to:1/0},url:ia},Xe={type:"template",baseUrl:ae,segmentTemplateUrl:Gt,initUrl:"",totalSegmentsDurationMs:ta,segments:ea,nextSegmentBeyondManifest:Pi,timescale:Wt};Ve={id:ke,kind:"text",segmentReference:Xe,profiles:[],duration:b,bitrate:Jr,mime:"",codecs:"",width:0,height:0,isAuto:dt}}else Ve={id:ke,isAuto:dt,kind:"text",url:ae}}else{let ke=U.getAttribute("contentType")??Me?.split("/")[0]??y,dt=E.getAttribute("profiles")?.split(",")??[],Oe=parseInt(U.getAttribute("width")??"",10),xi=parseInt(U.getAttribute("height")??"",10),Jr=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,Zr=U.getAttribute("frameRate")??"",Wt=U.getAttribute("quality")??void 0,Vs=Zr?Zu(Zr):void 0,Gt=U.getAttribute("id")??"id"+(A++).toString(10),ea=ke==="video"?`${xi}p`:ke==="audio"?`${Jr}Kbps`:lt,ta=`${Gt}@${ea}`,ia=[...R,...O,...dt],Yt,ki=U.querySelector("SegmentBase"),me=U.querySelector("SegmentTemplate")??Z;if(ki){let Xe=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Mt]=Xe.split("-").map(ht=>parseInt(ht,10)),Re={from:Ne,to:Mt},pt=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rt,Kt]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],Qe=pt?{from:Rt,to:Kt}:void 0;Yt={type:"byteRange",url:ae,initRange:Re,indexRange:Qe}}else if(me){let Xe={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Ne=parseInt(me.getAttribute("timescale")??"",10),Mt=me.getAttribute("initialization")??"",Re=me.getAttribute("media"),pt=parseInt(me.getAttribute("startNumber")??"",10)??1,Rt=Ue(Mt,Xe);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let Kt=me.querySelectorAll("SegmentTimeline S")??[],Qe=[],ht=0,Xt="",Ai=0;if(Kt.length){let ra=pt,_e=0;for(let Jt of Kt){let je=parseInt(Jt.getAttribute("d")??"",10),Dt=parseInt(Jt.getAttribute("r")??"",10)||0,aa=parseInt(Jt.getAttribute("t")??"",10);_e=Number.isFinite(aa)?aa:_e;let Os=je/Ne*1e3,Rl=_e/Ne*1e3;for(let sa=0;sa<Dt+1;sa++){let Dl=Ue(Re,{...Xe,segmentNumber:ra.toString(10),segmentTime:(_e+sa*je).toString(10)}),Eo=(Rl??0)+sa*Os,Ll=Eo+Os;ra++,Qe.push({time:{from:Eo,to:Ll},url:Dl})}_e+=(Dt+1)*je,ht+=(Dt+1)*Os}Ai=_e/Ne*1e3,Xt=Ue(Re,{...Xe,segmentNumber:ra.toString(10),segmentTime:_e.toString(10)})}else if(Zp(b)){let _e=parseInt(me.getAttribute("duration")??"",10)/Ne*1e3,Jt=Math.ceil(b/_e),je=0;for(let Dt=1;Dt<Jt;Dt++){let aa=Ue(Re,{...Xe,segmentNumber:Dt.toString(10),segmentTime:je.toString(10)});Qe.push({time:{from:je,to:je+_e},url:aa}),je+=_e}Ai=je,Xt=Ue(Re,{...Xe,segmentNumber:Jt.toString(10),segmentTime:je.toString(10)})}let Ml={time:{from:Ai,to:1/0},url:Xt};Yt={type:"template",baseUrl:ae,segmentTemplateUrl:Re,initUrl:Rt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:Ml,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Me)continue;let Pi={video:"video",audio:"audio",text:"text"}[ke];if(!Pi)continue;ue||=Pi,Ve={id:ta,kind:Pi,segmentReference:Yt,profiles:ia,duration:b,bitrate:Jr,mime:Me,codecs:lt,width:Oe,height:xi,fps:Vs,quality:Wt}}ce.language||=N,ce.label||=le,ce.mime||=Me,ce.codecs||=lt,ce.hdr||=ue==="video"&&Rn(lt),ce.representations.push(Ve)}if(ue){let U=r[ue].find(N=>N.id===ce.id);if(U&&ce.representations.every(N=>N.segmentReference.type==="template"))for(let N of U.representations){let le=ce.representations.find(Me=>Me.id===N.id);if(!le)continue;let he=le.segmentReference,ae=N.segmentReference;ae.segments.push(...he.segments),ae.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ue].push(ce)}}return{duration:b,streams:r,baseUrls:s,live:g}};import{assertNever as is}from"@vkontakte/videoplayer-shared/evergreen";var ts=n=>{let{webmDecodingInfo:e}=M.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:is(n)}},rc=({webmCodec:n,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...ts(n),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(M.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ts(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ts(n),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ts(n),...a,"HLS","HLS_ONDEMAND"];default:is(e)}if(M.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:is(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},ac=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=M.device.isMac&&M.browser.isSafari;if(M.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:is(n)}else M.video.nativeHlsSupported&&!u&&!M.browser.isChromiumBased?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Dn=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],rs=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)},as=n=>{let e=n.map(i=>pi(i)),{codecs:t}=M.video;return rh().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})},ss=n=>{let e=n.map(i=>pi(i)),{codecs:t}=M.video;return ah().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},pi=n=>n.split(".")[0].replace("0",""),rh=()=>["av1","vp9","hev1","avc1"],ah=()=>["opus","mp4a"];import{abortable as On,assertNonNullable as Ke,ErrorCategory as xh,fromEvent as kh,getExponentialDelay as Ph,getWindow as mc,isHigher as Ah,isNonNullable as ee,isNullable as ne,once as $h,Subject as Mh,Subscription as Rh,ValueSubject as kr}from"@vkontakte/videoplayer-shared/evergreen";var ns=n=>n.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var hi=class extends Q{};import{assertNever as sh}from"@vkontakte/videoplayer-shared/evergreen";var tr=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:sh(e)}}};var ir=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var rr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var ar=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var sr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nr=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Nt=class extends Y{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var or=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ur=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cr=class extends Y{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var lr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var dr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var pr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends Y{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var mr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var br=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var gr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sr=class extends Y{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var vr=class extends Y{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var yr=class extends Y{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Tr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ir=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Er=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var oh={ftyp:ir,moov:rr,mvhd:ar,moof:sr,mdat:nr,sidx:Nt,trak:or,mdia:pr,mfhd:br,tkhd:hr,traf:gr,tfhd:Sr,tfdt:vr,trun:yr,minf:mr,sv3d:ur,st3d:cr,prhd:lr,proj:fr,equi:dr,uuid:tr,stbl:Tr,stsd:Ir,avc1:Er,unknown:hi},it=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s;try{s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!s||!ns(s))break;t.push(s),i+=s.size}return t}createBox(e,t){let i=oh[e];return i?new i(t,new n):new hi(t,new n)}};var vt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ns(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var ch=new TextDecoder("ascii"),lh=n=>ch.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",dh=n=>{let e=new Nt(n,new it),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},ph=(n,e)=>{let i=new it().parse(n),r=new vt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,c,l)},hh=n=>{let t=new it().parse(n),i=new vt(t),r={},s=i.findAll("uuid").at(-1);return s?{serverDataReceivedTimestamp:s.userData.received,serverDataPreparedTime:s.userData.received}:r},mh=n=>{let t=new it().parse(n);return new vt(t).find("sidx")?.timescale},fh=(n,e)=>{let i=new it().parse(n),a=new vt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},bh=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new it().parse(n),r=new vt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},sc={validateData:lh,parseInit:bh,getIndexRange:()=>{},parseSegments:dh,parseFeedableSegmentChunk:ph,getChunkEndTime:fh,getServerLatencyTimestamps:hh,getTimescaleFromIndex:mh};import{assertNonNullable as Ln,isNonNullable as cc,isNullable as Sh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as gh}from"@vkontakte/videoplayer-shared/evergreen";var nc={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},oc=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=wr(n,t),r=i in nc,a=r?nc[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),c=s&255>>o,d=wr(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},wr=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return wr(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:gh(e)}},_t=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=oc(i);if(!e(r))return;r.type==="master"&&_t(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},uc=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=oc(n);return _t(r.value,({tag:a,type:s,value:o})=>(a===17143?e=He(o,s):a===17026?t=He(o,s):a===17029&&(i=He(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var lc=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],vh=[231,22612,22743,167,171,163,160,175],yh=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,c,d=!1,l=0;return _t(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let g=He(m,h);c=wr(g)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=He(m,h):p===17545?r=He(m,h):p===21420&&c===475249515?u=He(m,h):p===374648427?_t(m,({tag:g,type:b,value:S})=>g===30321?(d=He(S,b)===1,!1):!0):a&&s&&lc.includes(p)&&(o=!0),!o}),Ln(e,"Failed to parse webm Segment start"),Ln(t,"Failed to parse webm Segment end"),Ln(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Th=n=>{if(Sh(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ih=(n,e)=>{let t=!1,i=!1,r=o=>cc(o.time)&&cc(o.position),a=[],s;return _t(n,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=He(c,u));break;case 183:break;case 241:s&&(s.position=He(c,u));break;default:t&&lc.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:c,position:d}=o,l=a[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Eh=n=>{let e=0,t=!1;try{_t(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):vh.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},dc={validateData:uc,parseInit:yh,getIndexRange:Th,parseSegments:Ih,parseFeedableSegmentChunk:Eh};var Ft=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return dc;case"mp4":return sc}}throw new ReferenceError(`Unsupported mime type ${n}`)};import{videoSizeToQuality as wh}from"@vkontakte/videoplayer-shared/evergreen";var yt=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?ft(a):void 0)??wh({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},xr=({id:n,bitrate:e})=>({id:n,bitrate:e}),pc=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),hc=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Cn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Bn=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Vn=n=>"url"in n,Ae=n=>n.type==="template";var mi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,manifest:o}){this.error$=new Mh;this.playingRepresentation$=new kr(void 0);this.playingRepresentationInit$=new kr(void 0);this.currentSegmentLength$=new kr(0);this.onLastSegment$=new kr(!1);this.fullyBuffered$=new kr(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new AbortController;this.downloadAbortController=new AbortController;this.subscription=new Rh;this.startWith=On(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Ft(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Ke(i,"No init buffer for starting representation"),Ke(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=On(this.destroyAbortController.signal,async function*(e,t=!0){if(ne(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Ke(r,`No such representation ${e}`),Ke(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),s=this.segments.get(r.id);Ke(a,"No init buffer for switching representation"),Ke(s,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=l=>l.segment.networkStatus!=="downloaded"||l.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=l=>{let p=this.representations.get(l.representationId);return Ke(p,"No itemRepresentation for previous track before switch"),l.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},d=l=>t?u(l)&&c(l):u(l);this.bufferPlaybackQueue.filter(d).forEach(l=>l.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(l=>!d(l)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=On(this.downloadAbortController.signal,async function*(){let e=Ph(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=mc();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(kh(i,"online").pipe($h()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=s,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ne(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return ee(t)&&ee(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ne(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ne(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=mc();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.cancelIdleCallback)for(let t of this.idleCallbacks.values())e.cancelIdleCallback(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=yt(e),a=yt(t);i=ee(r)&&ee(a)&&Ah(a.quality,r.quality)}else if(this.kind==="audio"){let r=xr(e),a=xr(t);i=ee(r?.bitrate)&&ee(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,requestIdleCallback(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():ee(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:s,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ne(o)||ne(u))return;s&&this.parsedInitData.set(e.id,s);let c=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:xh.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ne(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],s=this.downloadAbortController.signal;ee(r)&&ee(i)&&ee(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),ee(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,s):await this.appendSegmentPartially(i,s)),ee(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,s),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Ke(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ne(t)||ne(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(s=>e>=s.time.from&&e<s.time.to);ee(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ne(t)||t.length===0)return;let i=t[t?.length-1];ne(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Ke(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;ee(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let s=[];for(;r<t.length&&a>0;){s.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return s}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return ee(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return ee(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return ee(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ne(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ne(e.segment.data)||ne(e.segment.loadedBytes)||ne(e.segment.feedingBytes)||ne(e.segment.fedBytes)||ne(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||ee(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let s of this.segments.values())for(let o of s)ee(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let s of this.segments.values())for(let o of[...s].reverse())ee(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as Dh,isNonNullable as Lh,isNullable as fc,now as bc}from"@vkontakte/videoplayer-shared/evergreen";var os=class extends mi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...s}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...s,priority:i}),this.lastDataObtainedTimestampMs=bc(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Fe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,s=0;for(;s<this.downloadingBufferItems.length&&this.downloadingBufferItems[s].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[s].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[s]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,s++}return i}prepareFetchParams(e,t){if(ve(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=bc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Dh.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:s}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||fc(o)||fc(r)||s.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<a,m=l<=a;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,a-d),await this.onDownloadItem(u)):Lh(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,a-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(ve(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as Ch,isNullable as Nn,now as gc}from"@vkontakte/videoplayer-shared/evergreen";var fi=class extends mi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...s}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...s,priority:i});if(this.lastDataObtainedTimestampMs=gc(),Nn(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Fe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(s,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=gc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:s,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Ch.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!ve(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let s=e[0],{segment:o}=s,u=this.representations.get(i);!this.downloadingBufferItems.length||Nn(u)||Nn(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(s)))}updateRepresentationBaseUrl(e,t){if(!ve(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as Bh,ErrorCategory as Vh,isNullable as rt,ValueSubject as Sc}from"@vkontakte/videoplayer-shared/evergreen";var us=class extends fi{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Sc(0);this.currentLowLatencySegmentLength$=new Sc(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=t.streams[this.kind].flatMap(r=>r.representations);for(let r of i){if(rt(r)||!ve(r.segmentReference))return;let a=r.segmentReference.segments.map(d=>({...d,networkStatus:"none",bufferStatus:"none",size:void 0})),s=100,o=this.segments.get(r.id)??[],u=o.at(-1)?.time.to??0,c=a?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(c===-1){let d=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,d)}else{let d=a.slice(c+1);this.segments.set(r.id,[...o,...d])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;Bh(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let r=t?.streams[this.kind]?.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(rt(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(rt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return rt(t)||!ve(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),rt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:s}=r.getServerLatencyTimestamps(i);a&&s&&this.currentLiveSegmentServerLatency$.next(s-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(rt(t.segment.data)||rt(r)||!ve(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:s}=r;t.segment.time.to=a.getChunkEndTime(i,s)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ve(a))return;let s=this.segments.get(r.id)??[],o=s.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!s.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),d=Ue(a.segmentTemplateUrl,{segmentTime:c});s.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:d,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",s=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,s);let{initMetadata:o,initDataView:u,segments:c}=await s??{};if(this.initDataPromises.delete(t.id),rt(u)||rt(c))return;o&&this.parsedInitData.set(t.id,o);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,l),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:Vh.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,o=i.length-1;do a.unshift(i[o]),s+=i[o].time.to-i[o].time.from,o--;while(s<r&&o>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}};var Pr=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new us(e,t,i,r):ve(i[0].segmentReference)?new fi(e,t,i,r):new os(e,t,i,r)}};import{ErrorCategory as _h,fromEvent as Fh,isNullable as bi,Subject as Uh,Subscription as Hh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Oh,ErrorCategory as vc,Subject as yc}from"@vkontakte/videoplayer-shared/evergreen";var Nh=18,Tc=!1;try{Tc=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=Nh}catch(n){console.error(n)}var _n=class{constructor(e,t=!1){this.bufferFull$=new yc;this.error$=new yc;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:vc.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Tc&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:vc.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Oh(t)}}},Ic=_n;var Tt=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Ar=class{constructor(e){this.error$=new Uh;this.subscription=new Hh;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Ic(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(Fh(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_h.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(bi(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!bi(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(bi(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return bi(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||bi(e)?0:Tt(this.sourceBuffer.buffered,e)}async abortBuffer(e){return bi(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var Gh=["timeupdate","progress","play","seeked","stalled","waiting"],xc=["timeupdate","progress","loadeddata","playing","seeked"],ls=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new wc;this.subscriptionRemovable=new Wh;this.representationSubscription=new wc;this.forceEnded$=new Et;this.destroyController=new AbortController;this.state$=new V("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new Et;this.manifestRequested=new Et;this.manifestReceived=new Et;this.firstBytesRequested=new Et;this.firstBytesReceived=new Et;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.currentBuffer$=new K({from:0,to:0});this.bufferLength$=new K(0);this.nativeBufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new Et;this.fetcherError$=new Et;this.initRepresentations=Ec(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",cs({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={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};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),at(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=Ec(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Mr(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ut.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Xa({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.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})}initBuffer(){at(this.element),this.state$.setState("running"),this.subscription.add(Rr(...Gh.map(t=>Ht(this.element,t)),Ht($r(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Rr(...e.map(t=>Ht(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Ht(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=zh(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){at(this.element),at(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),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",cs({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){It(this.element)&&It(this.source)&&It(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}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.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&$r().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),It(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Mr(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){at(this.element),at(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",cs(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=qh(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,d=It(this.videoBufferManager)&&u<a&&r-s>i,l=It(this.audioBufferManager)&&c<a&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Mr(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",cs(i)),i}parseManifest(e){try{return es(e??"",this.manifestUrlString)}catch(t){let i=Wa(e)??{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>!!(this.element?.canPlayType?.(u)&&Pe()?.isTypeSupported?.(`${u}; codecs="${c}"`)||o==="text"),r,a;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(a=ss(l),d=a[0]),o==="video"&&(r=as(l),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>pi(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=rs(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);M.display.isHDR&&l&&p?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr))}}let s={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(s.codecs={video:r,audio:a}),s}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){at(this.manifest),at(this.element);let a=c=>{this.representationSubscription.add(Ht(c,"error").pipe(Fn(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=ba();let s=$r().document,o=s.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),Zt())if(r){let c=s.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Ar(this.source),this.videoBufferManager=Pr.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],It(i)){this.audioNativeBufferManager=new Ar(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=Pr.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=$r().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Ut.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&&$r().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){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$)),this.representationSubscription.add(Rr(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),at(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Rr(...xc.map(e=>Ht(this.element,e))).pipe(Un(e=>this.videoBufferManager?.getPlaybackBufferState()),Fn(It),Un(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Rr(...xc.map(e=>Ht(this.element,e))).pipe(Un(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),Qh()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Fn(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=jh(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Mr(this.element)||Mr(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as ds,combine as Yh,ErrorCategory as Kh,filter as Hn,filterChanged as Xh,fromEvent as Jh,isNonNullable as Zh,map as Qn,merge as Dr}from"@vkontakte/videoplayer-shared/evergreen";var ps=class extends ls{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){ds(this.manifest),ds(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(t=>t.representations).flatMap(t=>{let i=[];return t.duration&&i.push(t.duration),ve(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){ds(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){ds(this.element);let e=Dr(Jh(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(Hn(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Dr(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Dr(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(Qn(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Dr(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(Qn(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=Yh({allBuffersFull:e,someBufferEnded:t}).pipe(Xh(),Qn(({allBuffersFull:a,someBufferEnded:s})=>a&&s),Hn(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:Kh.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Dr(this.forceEnded$,i).pipe(Hn(a=>Zh(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(s=>!s.updating))).subscribe(r))}};var gi=class extends Ki{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(em()).subscribe(a=>{let s=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===a);if(!s){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=s,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Fa(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new ps({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as km,assertNonNullable as Pm,combine as Am,debounce as $m,ErrorCategory as Bc,filter as eo,filterChanged as Ur,fromEvent as Mm,isNonNullable as Vc,isNullable as Rm,map as Hr,merge as Qr,observableFrom as Is,once as Oc,Subscription as Dm,throttle as Lm}from"@vkontakte/videoplayer-shared/evergreen";var wt=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Kn,assertNonNullable as yi,combine as Ti,ErrorCategory as Be,filter as vs,filterChanged as Nr,flattenObject as _r,fromEvent as nt,getTraceSubscriptionMethod as mm,interval as Xn,isNonNullable as Fr,isNullable as Lc,map as Ii,merge as zt,now as Jn,Subject as ot,Subscription as Cc,SubscriptionRemovable as fm,tap as bm,throttle as gm,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as tm,ErrorCategory as kc,Subject as Pc}from"@vkontakte/videoplayer-shared/evergreen";var im=18,Ac=!1;try{Ac=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=im}catch(n){console.error(n)}var jn=class{constructor(e,t=!1){this.bufferFull$=new Pc;this.error$=new Pc;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:kc.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Ac&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:kc.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:tm(t)}}},$c=jn;var zn=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as xt,assertNonNullable as ye,ErrorCategory as st,fromEvent as qn,getExponentialDelay as Wn,isHigher as rm,isNonNullable as kt,isNullable as ie,now as hs,once as am,Subject as sm,Subscription as nm,ValueSubject as Qt}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new Qt(0);this.currentLowLatencySegmentLength$=new Qt(0);this.currentSegmentLength$=new Qt(0);this.onLastSegment$=new Qt(!1);this.fullyBuffered$=new Qt(!1);this.playingRepresentation$=new Qt(void 0);this.playingRepresentationInit$=new Qt(void 0);this.error$=new sm;this.gaps=[];this.subscription=new nm;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=xt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ye(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $c(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(qn(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(qn(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(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,zn(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,s*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);ye(i,"No init buffer for starting representation"),ye(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ie(a)||ie(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ye(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let s=this.getCurrentPosition();kt(s)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ie(a)||ie(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ye(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();kt(s)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=xt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let c=t.find(p=>p.id===u);c&&this.representations.set(u,c);let d=this.representations.get(u);if(!d||!Ae(d.segmentReference)){this.isSeekingLive=!1;return}let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ye(r,`Representation not found by id ${i}`);let a=this.segments.get(i);ye(a,"No segments for starting representation");let s=this.initData.get(i);if(ye(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,xt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ye(a,`No such representation ${i}`);let s=this.segments.get(i),o=this.initData.get(i);if(ie(o)||ie(s)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),s=this.segments.get(i),ye(s,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();kt(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ie(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||kt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(ye(t,`No such representation ${this.downloadingRepresentationId}`),ye(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(a))return;let s=r.find(p=>e>=p.time.from&&e<p.time.to);kt(s)&&isFinite(s.time.from)&&isFinite(s.time.to)&&this.currentSegmentLength$.next(s?.time.to-s.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),h=yt(i),m=yt(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&kt(h)&&kt(m)&&rm(h.quality,m.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||g?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=s.time.to-e+u&&(o=s?s.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([I,v])=>{let x=v.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:I,status:x?.status}}).find(I=>I.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&zn(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(d.includes(s))p="high";else{let h=d.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=r.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;kt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!Ae(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),a=100,s=this.segments.get(i.id)??[],o=s.at(-1)?.time.to??0,u=r?.findIndex(c=>o>=c.time.from+a&&o<=c.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(u+1);this.segments.set(i.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ye(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ae(r))return;let a=this.segments.get(i.id)??[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to,t=s.time.to-s.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Ue(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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),a=e.findIndex(({status:p,time:{from:h,to:m}},f)=>{let g=h<=i&&m>=i,b=h>i||g||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+S||r<S&&m-h>=S||m<=i+S;return(p==="none"||p==="partially_ejected"&&b&&I&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(wt(this.sourceBuffer.buffered,h)&&wt(this.sourceBuffer.buffered,m)))&&b&&I});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<s.length&&(o<=d||u<=l);p++){let h=s[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){Ae(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:a,url:s,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await xt(o,async function*(){let d=Wn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=hs(),!d)return;let l=new DataView(d),p=Ft(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,f)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Fe(d)||(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())Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await xt(s,async function*(){let u=Wn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),qn(window,"online").pipe(am()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=hs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Fe(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=hs(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=hs();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ft(s.mime).parseFeedableSegmentChunk(c,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await s();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,m=l<=r;if(!h)continue;let f=Ft(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===p?g:f.parseFeedableSegmentChunk(g);b?.byteLength&&(c.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await s())}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&M.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(wt(this.sourceBuffer.buffered,e.segment.time.from,100)&&wt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:st.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Vn(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,a]of this.initData.entries()){let s=a instanceof Promise;t||=s,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?xt(this.destroyAbortController.signal,async function*(){let u=Wn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ft(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&Ae(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{a||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,o),o}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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;let r=[],a=0,s=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{if(a>=t)return r;r.push({...u.time}),r=s(r);let c=Vn(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:Tt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let s=0;s<a.length;s++){let o=a.start(s)*1e3,u=a.end(s)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}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||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let s=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||ie(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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=s&&d.to+t>=o),c=e.filter(d=>s>=d.from&&s<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.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"})}};import{abortable as Cr,assertNever as Mc,fromEvent as Rc,merge as om,now as Br,Subject as Si,ValueSubject as Gn,flattenObject as vi,ErrorCategory as Vr,SubscriptionRemovable as um}from"@vkontakte/videoplayer-shared/evergreen";var fs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new Si;this.firstBytesManifest$=new Si;this.firstBytesRequested$=new Si;this.firstBytesReceived$=new Si;this.lastConnectionType$=new Gn(void 0);this.lastConnectionReused$=new Gn(void 0);this.lastRequestFirstBytes$=new Gn(void 0);this.recoverableError$=new Si;this.error$=new Si;this.abortAllController=new AbortController;this.subscription=new um;this.fetchManifest=Cr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ya(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ms);return r?(t.log("success",vi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",vi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Cr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let y=new URL(l,location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:Mc(t)}this.requestQuic&&(l=St(l));let m=this.abortAllController.signal,f;if(s){let y=new AbortController;if(f=om(Rc(this.abortAllController.signal,"abort"),Rc(s,"abort")).subscribe(()=>{try{y.abort()}catch(O){ms(O)}}),this.subscription.add(f),this.abortAllController.signal.aborted||s.aborted)try{y.abort()}catch(O){ms(O)}m=y.signal}let g=0,b=Br();h.log("startRequest",vi({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b})),this.firstBytesRequested$.next();let S=yield this.doFetch(l,{priority:a,headers:p,signal:m},{ignoreNetworkErrors:d}),I=Br();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(I-b),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let y=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:y}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let y=Br(),O={requestStartedAt:b,requestEndedAt:y,duration:y-b};return h.log("endRequest",vi(O)),h.end(),S.arrayBuffer()}let v=S.body;if(o){let y;[v,y]=S.body.tee(),this.throughputEstimator?.trackStream(y,u)}let x=v.getReader(),A,R=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let k=A?new Uint8Array(A):new Uint8Array(0),D=!1,E=y=>{this.unsubscribeAbortSubscription(f),D=!0,ms(y)},_=Cr(m,async function*({done:y,value:O}){if(g===0&&(this.lastRequestFirstBytes$.next(Br()-b),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!y&&O){if(c&&A)k.set(O,g),g+=O.byteLength;else{let $=new Uint8Array(k.length+O.length);$.set(k),$.set(O,k.length),k=$,g+=O.byteLength}r?.(new DataView(k.buffer),g),yield x?.read().then(_,E)}}.bind(this));yield x?.read().then(_,E),this.unsubscribeAbortSubscription(f);let C=Br(),T={failed:D,requestStartedAt:b,requestEndedAt:C,duration:C-b};return D?(h.error("endRequest",vi(T)),h.end(),null):(h.log("endRequest",vi(T)),h.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=Cr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(s=Math.min(c,r),o=Math.max(d,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(l,m.from-s,m.to-m.from+1);else{let b=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!b)return null;f=new DataView(b)}let g=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Cr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(s=>({...s,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=a}onHeadersReceived(e){let{type:t,reused:i}=Ga(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Mc(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),s=parseInt(a);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Vr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Vr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Vr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Vr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Vr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ms=n=>{if(!Fe(n))throw n};import{isNullable as cm,ValueSubject as Dc}from"@vkontakte/videoplayer-shared/evergreen";var Pt=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 Dc(e.initial),this.debounced$=new Dc(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(cm(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 bs=class extends Pt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=tt(this.slow,e,this.params.emaAlphaSlow),this.fast=tt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gs=class extends Pt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=vn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=tt(this.emaSmoothed,e,this.params.emaAlpha);let i=ju(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ss=class extends Pt{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?tt(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gs({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 Ss({initial:e,label:"liveEdgeDelay",...t})}};var Yn=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as lm,ValueSubject as dm}from"@vkontakte/videoplayer-shared/evergreen";var Or=class n{constructor(e,t){this.currentRepresentation$=new dm(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(!lm(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,s=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<s||e>o)continue;let u=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.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&&Ae(t.segmentReference))}};var Sm=["timeupdate","progress","play","seeked","stalled","waiting"],vm=["timeupdate","progress","loadeddata","playing","seeked"];var ys=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cc;this.subscriptionRemovable=new fm;this.representationSubscription=new Cc;this.state$=new V("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 ot;this.manifestRequested$=new ot;this.firstBytesManifest$=new ot;this.manifestReceived$=new ot;this.firstBytesRequested$=new ot;this.firstBytesReceived$=new ot;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 ot;this.fetcherError$=new ot;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ot;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=Kn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=de(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:Be.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Kn(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Be.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=es(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let c=Wa(e)??{id:"ManifestParsing",category:Be.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let i=(u,c,d)=>!!(this.element?.canPlayType?.(c)&&Pe()?.isTypeSupported?.(`${c}; codecs="${d}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:c,streamIsUnpublished:d,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((c-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(l||(h=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),l&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:Be.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},a,s;for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h));r[u]=d;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let p=d.map(({codecs:h})=>h);u==="audio"&&(s=ss(p),l=s[0]),u==="video"&&(a=as(p),this.forceVideoCodec&&a.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=a[0]),l&&(r[u]=d.filter(({codecs:h})=>pi(h)===l))}else{let p=new Set(d.map(({codecs:h})=>h));l=rs(p),l&&(r[u]=d.filter(({codecs:h})=>h.startsWith(l)))}if(u==="video"){let p=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);M.display.isHDR&&p&&h?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:s}),this.tracer.log("updateManifestEnd",_r(o)),o}.bind(this));this.initRepresentations=Kn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",_r({initialVideo:e,initialAudio:t,sourceHls:i})),yi(this.manifest),yi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(nt(l,"error").pipe(vs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Be.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ba();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Zt())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let s={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},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Lr("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],Fr(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Lr("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(Or.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Or(this.manifest.streams.text,s)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(zt(...vm.map(l=>nt(this.element,l))).pipe(Ii(l=>this.element?Tt(this.element.buffered,this.element.currentTime*1e3):0),Nr(),bm(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(zt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Nr()).subscribe(p=>this.liveStreamEndTimestamp=Jn())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=Xn(p).subscribe(h=>{let m=ca(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,m+p,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(nt(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ti({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ii(({isActiveLive:p,isLowLatency:h})=>p&&h),Nr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Yn(this.element,1)})),this.representationSubscription.add(Ti({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(vs(({bufferLength:p,isActiveLive:h,isLowLatency:m})=>h&&m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let h=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Ti({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(vs(({isLive:p})=>p),Nr((p,h)=>h.bufferLength<p.bufferLength),Ii(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=ca(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ti({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,b=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=p-f;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(S)>g&&(I=1+Math.sign(S)*b),Yn(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(Ti({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gm(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=ca(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,b=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(p)?p:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),R="active_low_latency"):f!==0&&v<b?R="live_forward_buffering":v<b+I&&(R="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),R==="live_forward_buffering"||R==="live_with_target_offset"){let k=l-(b+S),D=this.normalizeLiveOffset(Math.trunc(f+k/m)),E=Math.abs(D-f),_=0;!p||E<=this.tuning.dashCmafLive.offsetCalculationError?_=f:D>0&&E>this.tuning.dashCmafLive.offsetCalculationError&&(_=D),this.manifestUrlString=de(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Be.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let u=zt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Ii(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=zt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Ii(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=Ti({allBuffersFull:u,someBufferEnded:c}).pipe(Nr(),Ii(({allBuffersFull:l,someBufferEnded:p})=>l&&p),vs(l=>l));if(this.representationSubscription.add(zt(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Be.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(zt(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Be.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Fr(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=Xn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Be.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 fs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){yi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Jn()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=de(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){yi(this.element),this.state$.setState("running"),this.subscription.add(zt(...Sm.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Be.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&wt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:s}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let d=this.currentStallDuration$.getValue();d+=s,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=Jn(),h=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,g=this.videoBufferManager?.getForwardBufferDuration()??0,b=this.audioBufferManager?.getForwardBufferDuration()??0,S=g<h&&p-m>r,I=this.audioBufferManager&&b<h&&p-f>r;if((!t||c)&&((S||I)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%a===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:Be.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),l.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),l.position=v}this.tracer.log("stallIntervalCallback",_r(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Xn(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Be.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){yi(this.element),yi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),wt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Lc(this.element)||Lc(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",_r({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Fr(this.element)&&Fr(this.source)&&Fr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=mm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,s=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?s.push(1/0):s.push(c.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",_r(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as ym,map as Tm,observeElementSize as Im,Subscription as Em,ValueSubject as Zn,noop as wm}from"@vkontakte/videoplayer-shared/evergreen";var Ts=class{constructor(){this.subscription=new Em;this.pipSize$=new Zn(void 0);this.videoSize$=new Zn(void 0);this.elementSize$=new Zn(void 0);this.pictureInPictureWindowRemoveEventListener=wm}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Im(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(ym({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Tm(({videoSize:r,inPip:a,pipSize:s})=>a?s:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var qt=class{constructor(e){this.subscription=new Dm;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new oi;this.stallsManager=new ja;this.elementSizeManager=new Ts;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return km(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ui(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Le(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ys({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Rm(this.observableVideo)&&(this.observableVideo=we(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=s=>{e.error$.next({id:i,category:Bc.WTF,message:`${i} internal logic error`,thrown:s})},a=(s,o)=>this.subscription.add(s.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(eo(l=>!!l.length),Oc()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let s=this.params.desiredState.seekState.stateChangeEnded$.pipe(Hr(l=>l.to.state!=="none"),Ur());this.stallsManager.init({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(eo(Vc),Oc()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Hr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),gt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if(Pm(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let g of p.audio){f.push(Cn(g));let b=[];for(let S of g.representations){let I=xr(S);b.push(I),this.audioTracksMap.set(I,{stream:g,representation:S})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Bn(f));let g=[];for(let b of f.representations){let S=yt({...b,streamId:f.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:f,representation:b}))}this.videoStreamsMap.set(f,g)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let g of f.representations){let b=pc(f,g);this.textTracksMap.set(b,{stream:f,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Qr(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Mm(this.video,"progress")).pipe(eo(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(Lm(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,f]=h,g=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);Vc(g)&&(this.stallsManager.lastVideoTrackSelected=g);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(Am({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Qr(Is([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Hr(l=>l.to)))}).pipe(Hr(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),Ur()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ur()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Bn(m));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ur()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Cn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Hr(({to:l})=>l==="ready"),Ur());this.subscription.add(Qr(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Is(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Qr(c,this.player.state$.stateChangeEnded$,Is(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Qr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Is(["init"])).pipe($m(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ui:Fi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ba:Ca,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:La,{desiredState:r,output:a}=this.params,s=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:k})=>k===o),c=a.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:k})=>k===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Tt(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=s?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(m,f||1/0),1),b=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:k})=>k===b?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(u&&!s){let k=e(u,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}if(c){let k=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}}let v=u;(s||!v)&&(v=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:g,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=S&&t(v,p,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(v)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var jr=class extends qt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as to,merge as Nc,filter as _c,filterChanged as Fc,isNullable as io,map as Uc,ValueSubject as ro,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/evergreen";var zr=class extends qt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),s(r.timeUpdate$,i.liveBufferTime$),s(this.player.liveSeekableDuration$,i.duration$),s(this.player.liveLatency$,i.liveLatency$);let o=new ro(1);s(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Fc()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(Uc(u=>u.to)).subscribe(this.player.isLowLatency$)).add(to({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Uc(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(to({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Nc(r.playbackRateState$,new ro(1))}).pipe(_c(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||io(d)||(t=u-d)})).add(to({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Nc(r.playbackRateState$,new ro(1))}).pipe(Fc((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||io(u)||io(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=hc(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(_c(u=>Cm(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Hc="X-Playback-Duration",ao=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Hc)?parseInt(e.headers.get(Hc),10):void 0};import{assertNever as zm,combine as qm,debounce as Wm,ErrorCategory as xs,filter as Gm,filterChanged as Ym,isNonNullable as zc,isNullable as ks,map as qc,merge as Km,observableFrom as Xm,Subscription as Jm,ValueSubject as no,VideoQuality as Zm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Bm,getExponentialDelay as Vm}from"@vkontakte/videoplayer-shared/evergreen";var Om=n=>{let e=null;if(n.QUALITY&&(e=ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Bm({width:t,height:i})}return e??null},Nm=(n,e)=>{let t=n.split(`
|
|
178
|
+
`),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let c=Object.fromEntries(o[1].split(",").map(g=>g.split("="))),d=c.QUALITY??`stream-${c.BANDWIDTH}`,l=Om(c),p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,m;if(c.RESOLUTION){let[g,b]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));g&&b&&(m={width:g,height:b})}let f=new URL(t[++a],e).toString();l&&i.push({id:d,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(u){let c=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=c.URI?.replace(/playlist$/,"subtitles.vtt"),l=c.LANGUAGE,p=c.NAME;d&&l&&r.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},_m=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),so=0,Qc=async(n,e=n,t,i)=>{let a=await(await fetch(n,i)).text();so+=1;try{let{qualityManifests:s,textTracks:o}=Nm(a,e);return{qualityManifests:s,textTracks:o}}catch{if(so<=t.manifestRetryMaxCount)return await _m(Vm(so-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qc(n,e,t)}return{qualityManifests:[],textTracks:[]}},Es=Qc;import{isNonNullable as Fm,Subscription as Um,throttle as Hm,ValueSubject as jc,Subject as Qm,ErrorCategory as jm}from"@vkontakte/videoplayer-shared/evergreen";var ws=class{constructor(e,t,i,r,a){this.subscription=new Um;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new jc(null);this.getCurrentTime$=new jc(null);this.error$=new Qm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(Hm(1e3)).subscribe(s=>{this.processLiveTime(s)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),s=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(s,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
179
|
+
`),a=0;for(let s=0;s<r.length;++s){let o=r[s];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++s],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:c}),a=a+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let c=new Date(u);c.setMilliseconds(0),a=c.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Fm(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let s of t)if(s.time.from<=e&&s.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:s.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:jm.WTF,thrown:t,message:e})}};var qr=class{constructor(e){this.subscription=new Jm;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new no([]);this.liveOffset=new Vt;this.manifestStartTime$=new no(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return zm(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Zm.INVARIANT,url:this.params.source.url};let t=(i,r)=>Es(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ws(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Le(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:xs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:xs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new no(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:xs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=we(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ce(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(Ym(),qc(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&zc(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(pe(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(qm({startTime:this.manifestStartTime$.pipe(Gm(zc)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(qc(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Km(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Xm(["init"])).pipe(Wm(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(ks(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=de(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(s),this.video.setAttribute("src",s),this.video.load(),ao(s).then(o=>{if(!ks(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ks(u)||!isFinite(u))&&fetch(s).then(c=>c.text()).then(c=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(d){let l=new URL(d,s).toString();ao(l).then(p=>{ks(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xs.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=de(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as ef,debounce as tf,ErrorCategory as oo,fromEvent as uo,isNonNullable as rf,isNullable as af,map as Wc,merge as Gc,observableFrom as Yc,Subscription as sf,ValueSubject as Kc,VideoQuality as nf}from"@vkontakte/videoplayer-shared/evergreen";var Wr=class{constructor(e){this.subscription=new sf;this.videoState=new V("stopped");this.manifests$=new Kc([]);this.unmuteAfterBrowserResetsHappened=new Kc(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return ef(t)}};this.textTracksManager=new Le(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nf.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Es(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:oo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:oo.WTF,message:"HlsProvider internal logic error",thrown:o})},r=we(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Wc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),gt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&rf(c.to)){let h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(pe(m.url)))}let l=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(l!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(l),h.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Wc(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!M.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Gc(uo(o,"addtrack"),uo(o,"removetrack"),uo(o,"change"),Yc(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=Gc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yc(["init"])).pipe(tf(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(af(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let c=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as of,assertNonNullable as Xc,debounce as uf,ErrorCategory as Jc,isHigherOrEqual as cf,isLowerOrEqual as lf,isNonNullable as df,merge as pf,observableFrom as hf,Subscription as mf,map as ff}from"@vkontakte/videoplayer-shared/evergreen";var Gr=class{constructor(e){this.subscription=new mf;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return of(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Jc.WTF,message:"MpegProvider internal logic error",thrown:o})},r=we(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(ff(o=>o.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),gt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&df(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(u!==c){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let s=pf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,hf(["init"])).pipe(uf(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Xc(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Xc(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=St(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(pe(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let d=Ye(s,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),s=Object.values(this.trackUrls).map(c=>c.track);if(!r||!a||ri(e,s[0].quality,s.at(-1)?.quality)){i();return}let o=e.max?lf(r,e.max):!0,u=e.min?cf(r,e.min):!0;o&&u||i(e)}};import{assertNever as el,debounce as vf,merge as tl,observableFrom as yf,Subscription as Tf,map as il,ValueSubject as If,ErrorCategory as lo,VideoQuality as Ef}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as bf}from"@vkontakte/videoplayer-shared/evergreen";var Zc=["stun:videostun.mycdn.me:80"],gf=1e3,Sf=3,co=()=>null,Ps=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=co;this.externalStopCallback=co;this.externalErrorCallback=co;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Zc}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:bf.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),gf)}normalizeOptions(e={}){let t={stunServerList:Zc,maxRetryNumber:Sf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Yr=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new If(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return el(e)}};this.subscription=new Tf,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new Ps(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:lo.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};this.subscription.add(tl(this.videoState.stateChangeStarted$.pipe(il(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(il(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})}));let r=we(this.video);this.subscription.add(()=>r.destroy());let a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return el(s.to)}},i)).add(tl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,yf(["init"])).pipe(vf(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Ef.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:lo.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lo.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ei=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Kr,assertNonNullable as ut,ErrorCategory as As,filter as ul,isNonNullable as cl,isNullable as Mf,map as Rf,merge as Df,once as Lf,Subject as J,Subscription as ll,ValueSubject as B,flattenObject as po,devNull as Cf,getWindow as Bf}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as wf,map as rl,Subscription as xf,Subject as kf}from"@vkontakte/videoplayer-shared/evergreen";var al=n=>new wf(e=>{let t=new xf,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(rl(({from:c,to:d})=>`${c}-${d}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(rl(({type:c})=>c!==void 0)),s=new kf,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>s.next(c),n.maxTransitionInterval),L({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{L({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(c=>{o&&(L({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval),L({m:"hangup.rs.1",id:o})))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Pf,Subscription as Af,combine as $f,filter as nl,once as ol}from"@vkontakte/videoplayer-shared/evergreen";function sl(){return new(window.AudioContext||window.webkitAudioContext)}var wi=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Af;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(nl(a=>!!a.type),ol()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){M.browser.isSafari&&e!=="MPEG"||this.subscriptions.add($f({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nl(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),ol()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=sl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:Pf.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var Vf={chunkDuration:5e3,maxParallelRequests:5},Xr=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new J;this.noAvailableProvidersError$=new J;this.volumeMultiplierError$=new J;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableVideoCodecs$:new B([]),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),availableAudioCodecs$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),currentNativeBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new J,fetcherError$:new J,fetcherRecoverableError$:new J,warning$:new J,willSeekEvent$:new J,soundProhibitedEvent$:new J,seekedEvent$:new J,loopedEvent$:new J,endedEvent$:new J,manifestRequested$:new J,firstBytesManifest$:new J,manifestReceived$:new J,firstBytesRequested$:new J,firstBytesReceived$:new J,firstBytesEvent$:new J,loadedMetadataEvent$:new J,firstFrameEvent$:new J,canplay$:new J,isLive$:new B(void 0),isLiveEnded$:new B(null),canPlayLiveTailBuffer$:new B(!1),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new J,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new ll;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=qs([...ac(this.params.tuning),...rc(this.params.tuning)]).filter(c=>cl(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",po(a)),this.screenFormatsIterator=new Ei(a);let s=[...Dn(!0),...Dn(!1)];this.chromecastFormatsIterator=new Ei(s.filter(c=>cl(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&wi.isSupported()&&(this.volumeMultiplierManager=new wi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){L.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Ei(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Mf(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:As.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Kr(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,s=this.providerOutput,o={container:i,source:null,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ut(u),this.params.tuning.useDashProviderVirtual&&!M.device.isMobile?new gi({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&M.device.isMobile?new gi({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new jr({...o,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ut(u),new zr({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return ut(u),new Wr({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ut(u),new qr({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ut(u),new Gr({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ut(u),new Nu({...o,source:u,config:{...Vf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ut(u),new Yr({container:i,source:u,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kr(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Ze){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return ut(c),new Ri({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return ut(u),new Bi({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Kr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Kr(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Kr(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new ll,t=!1,i=0;e.add(Df(this.providerOutput.error$.pipe(ul(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),al({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Rf(a=>({id:`ProviderHangup:${a}`,category:As.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(ul(({to:s})=>s==="playing"),Lf()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=L.drain(),{logDashLiveDebug:s,sendDashLiveDebug:o}=this.params.tuning;if(s&&Bf().console.log(`===== DASH_LIVE DEBUG START ====
|
|
180
|
+
`,a.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`
|
|
181
|
+
`+d:""}`).join(`
|
|
182
182
|
`),`
|
|
183
|
-
===== DASH_LIVE DEBUG END ====`),n){let o=s.reduce((c,{time:h,data:d,stack:l})=>{let p=Object.entries(d).map(([m,f])=>`${m}:${f}`).join(",");return c+=`${h}: ${p}${l?`: ${l}`:""};`,c},"");_g.push("core",{key:"vp_dash_live_debug",strings:[o]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(C({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{C({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let a=this.current$.getValue().destination,n={error:s,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=s.category===vn.NETWORK,c=s.category===vn.FATAL,h=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!c,l=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,p=h&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:h,tryFailover:p,canReinitProvider:d},d?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",gu(n)):this.tracer.error("providerError",gu(n))})),e}};import{fromEvent as yn,once as jg,combine as zg,Subscription as Nl,ValueSubject as Su,map as Fl,filter as Qg,isNonNullable as Tn,now as _e,safeStorage as vu,getWindow as qg}from"@vkontakte/videoplayer-shared/evergreen";var Wg=5e3,_l="one_video_throughput",Ul="one_video_rtt",Tu=()=>{let{navigator:u}=qg();if(u)return u.connection},Hl=()=>{let u=Tu()?.downlink;if(Tn(u)&&u!==10)return u*1e3},jl=()=>{let u=Tu()?.rtt;if(Tn(u)&&u!==3e3)return u},zl=(u,e,t)=>{let i=t*8,r=i/u;return i/(r+e)},yu=class u{constructor(e){this.subscription=new Nl;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=u.load(_l)||(e.useBrowserEstimation?Hl():void 0)||Wg,i=u.load(Ul)??(e.useBrowserEstimation?jl():void 0)??0;if(this.throughput$=new Su(t),this.rtt$=new Su(i),this.rttAdjustedThroughput$=new Su(zl(t,i,e.rttPenaltyRequestSize)),this.throughput=vt.getSmoothedValue(t,-1,e),this.rtt=vt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=Hl();n&&this.throughput.next(n);let o=jl();Tn(o)&&this.rtt.next(o)},s=Tu();s&&"onchange"in s&&this.subscription.add(yn(s,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{vu.set(_l,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{vu.set(Ul,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Fl(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(zg({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Fl(({throughput:r,rtt:s})=>zl(r,s,e.rttPenaltyRequestSize)),Qg(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=_e(),r=new Nl;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(yn(e,"progress").pipe(jg()).subscribe(s=>{t=s.loaded,i=_e()}));break;case 1:case 0:r.add(yn(e,"loadstart").subscribe(()=>{t=0,i=_e()}));break}r.add(yn(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=_e(),o=a-t,c=n-i;this.addRawSpeed(o,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=_e(),a=0,n=_e(),o=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let l=_e();if(l-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||l-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=_e()}else a+=d.byteLength;n=_e()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&_e()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,_e()-n,this.concurrentDownloads.size),a=0,n=_e());await i?.read().then(c,o)}};this.concurrentDownloads.add(e),i?.read().then(c,o)}addRawSpeed(e,t,i=1,r=!1){if(u.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=vu.get(e);if(Tn(t))return parseInt(t,10)??void 0}},Ql=yu;import{fillWithDefault as Gg,VideoQuality as In}from"@vkontakte/videoplayer-shared/evergreen";var Yg={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:In.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:In.Q_720P,trafficSavingLimit:In.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:In.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},ql=u=>Gg(u,Yg);import{assertNonNullable as wu,combine as wt,ErrorCategory as En,filter as ue,filterChanged as q,fromEvent as ku,isNonNullable as Xl,isNullable as nS,Logger as oS,map as Q,mapTo as Jl,merge as qt,now as wn,once as he,Subject as j,Subscription as Zl,tap as xu,ValueSubject as M,isHigher as uS,isInvariantQuality as eh,flattenObject as Wt,throttle as Pu,getTraceSubscriptionMethod as th,TracerFactory as cS,InternalsExposure as dS,getPlayerId as lS,devNull as kn}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Kg,map as Xg,filter as Wl,isNonNullable as Jg}from"@vkontakte/videoplayer-shared/evergreen";var Iu=({seekState:u,position$:e})=>Kg(u.stateChangeEnded$.pipe(Xg(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Wl(Jg)),e.pipe(Wl(()=>u.getState().state==="none")));import{assertNonNullable as Zg}from"@vkontakte/videoplayer-shared/evergreen";var Gl=u=>{let e=typeof u.container=="string"?document.getElementById(u.container):u.container;return Zg(e,`Wrong container or containerId {${u.container}}`),e};import{filter as eS,once as tS}from"@vkontakte/videoplayer-shared/evergreen";var Yl=(u,e,t,i)=>{u!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(eS(r=>r.length>0),tS()).subscribe(r=>{r.find(i)&&e.startTransitionTo(u)}):(u===void 0||t?.getValue().find(i))&&e.startTransitionTo(u)};import{devNull as iS,getWindow as Eu}from"@vkontakte/videoplayer-shared/evergreen";var Kl=()=>{let u="mediaCapabilities"in Eu().navigator?rS:sS,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(aS).map(async([r,s])=>({codec:r,supported:await u(s)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return iS.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},rS=async u=>{if(!u)return Promise.resolve({supported:!1});let e={["channels"in u?"audio":"video"]:u};return await Eu().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},sS=u=>{if(!u)return Promise.resolve({supported:!1});let e=Eu().document,t="channels"in u?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(u?.contentType??"")==="probably"})},aS={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var xn=class{constructor(e={},t=cS.createRootTracer(!1),i){this.subscription=new Zl;this.logger=new oS;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willReady$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,fetcherRecoverableError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,manifestRequested$:new j,firstBytesManifest$:new j,manifestReceived$:new j,firstBytesRequested$:new j,firstBytesReceived$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j,fetcherError$:new j,severeStallOccured$:new j};this.experimental={element$:new M(void 0),enableDebugTelemetry$:new M(!1),dumpTelemetry:Sc,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=ql(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(s=>s.setSuppressErrors(!0)),Object.values(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new lt(r):new ra(r),this.throughputEstimator=new Ql(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new dS("core",lS(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,kn.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let o=Reflect.get(s,a,n);return typeof o!="function"?o:(...c)=>{try{return o.apply(s,c)}catch(h){let d=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),l=`Player.${String(a)}`,p=`Exception calling ${l} (${d.join(", ")})`;throw this.events.fatalError$.next({id:l,category:En.WTF,message:p,thrown:h}),h}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Wt(a)),this.domContainer=Gl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new qs({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(kn.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Kl())):kn.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(ue(s=>!!s),he()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ku(document,"visibilitychange").pipe(he()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),kn.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(ue(t=>!!t),he()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{wu(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(i=>i.length>0),he()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Yl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(nS(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(yc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),he()).subscribe(()=>{this.initedAt=wn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:En.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(he()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(wt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(o=>n?n.id===o.streamId:!0).map(({quality:o})=>o).sort((o,c)=>eh(o)?1:eh(c)?-1:uS(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let o of a)o.fps&&(n[o.quality]=o.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(ue(a=>Xl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(Q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(Q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(xu(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(wt({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(a=>a.to),q(),Q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(wt({atLiveEdge:wt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:n,isLowLatency:o})=>{let c=this.getActiveLiveDelay(o);return a&&Math.abs(n)<c/1e3}),q(),xu(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(wt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:n,duration:o})=>a&&(Math.abs(o)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),q(),xu(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(a=>a.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(a=>a.volume),q()).subscribe(this.info.volume$)).add(Iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(qt(e.providerOutput.endedEvent$.pipe(Jl(!0)),e.providerOutput.seekedEvent$.pipe(Jl(!1))).pipe(q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Q(a=>({id:a?`No${a}`:"NoProviders",category:En.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(he()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(he()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(he()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(he()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(he()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(he(),Q(a=>a??wn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(he(),Q(()=>wn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(he(),Q(()=>wn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:a})=>a==="playing"),he()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let a=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return a&&!n}),q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":o?c?a?d="pip":n?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zl;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(i=>i.length>0),he()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=ze(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;wu(this.providerContainer),wu(e),gc(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>bc(t)),this.providerContainer.current$.subscribe(({type:t})=>Er("provider",t)),e.duration$.subscribe(t=>Er("duration",t)),e.availableVideoTracks$.pipe(ue(t=>!!t.length),he()).subscribe(t=>Er("tracks",t)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(t=>this.subscription.add(t)),Er("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=th(this.tracer.log.bind(this.tracer)),t=th(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(wt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(wt({currentBuffer:this.info.currentBuffer$.pipe(ue(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Pu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(wt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Pu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),ue(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(wt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Pu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),ue(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:En.DOM,message:String(r)})})};this.subscription.add(qt(ku(document,"visibilitychange"),ku(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Wt({quality:t,availableTracks:Wt(e),track:Wt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ar()}};import{Subscription as eU,Observable as tU,Subject as iU,ValueSubject as rU,VideoQuality as sU}from"@vkontakte/videoplayer-shared/evergreen";var aU=`@vkontakte/videoplayer-core@${$u}`;export{pr as ChromecastState,$n as HttpConnectionType,tU as Observable,be as PlaybackState,xn as Player,ta as PredefinedQualityLimits,aU as SDK_VERSION,iU as Subject,eU as Subscription,Mn as Surface,$u as VERSION,rU as ValueSubject,dt as VideoFormat,sU as VideoQuality,Mh as areValidLiveRecordSources,$ as clientChecker,Jt as isMobile};
|
|
183
|
+
===== DASH_LIVE DEBUG END ====`),o){let u=a.reduce((c,{time:d,data:l,stack:p})=>{let h=Object.entries(l).map(([m,f])=>`${m}:${f}`).join(",");return c+=`${d}: ${h}${p?`: ${p}`:""};`,c},"");Cf.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(a=>{a.id.startsWith("ProviderHangup")&&(L({m:"final.0",e:a.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{L({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,o={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=a.category===As.NETWORK,c=a.category===As.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!c&&(u&&t||!l);o={...o,isNetworkError:u,isFatalError:c,haveFailoverHost:d,tryFailover:h,canReinitProvider:l},l?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}a.traceAsLog?this.tracer.log("providerInfo",po(o)):this.tracer.error("providerError",po(o))})),e}};import{fromEvent as $s,once as Of,combine as Nf,Subscription as dl,ValueSubject as ho,map as pl,filter as _f,isNonNullable as Ms,now as $e,safeStorage as mo,getWindow as Ff}from"@vkontakte/videoplayer-shared/evergreen";var Uf=5e3,hl="one_video_throughput",ml="one_video_rtt",bo=()=>{let{navigator:n}=Ff();if(n)return n.connection},fl=()=>{let n=bo()?.downlink;if(Ms(n)&&n!==10)return n*1e3},bl=()=>{let n=bo()?.rtt;if(Ms(n)&&n!==3e3)return n},gl=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},fo=class n{constructor(e){this.subscription=new dl;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(hl)||(e.useBrowserEstimation?fl():void 0)||Uf,i=n.load(ml)??(e.useBrowserEstimation?bl():void 0)??0;if(this.throughput$=new ho(t),this.rtt$=new ho(i),this.rttAdjustedThroughput$=new ho(gl(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let o=fl();o&&this.throughput.next(o);let u=bl();Ms(u)&&this.rtt.next(u)},a=bo();a&&"onchange"in a&&this.subscription.add($s(a,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{mo.set(hl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{mo.set(ml,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(pl(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Nf({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pl(({throughput:r,rtt:a})=>gl(r,a,e.rttPenaltyRequestSize)),_f(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=$e(),r=new dl;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add($s(e,"progress").pipe(Of()).subscribe(a=>{t=a.loaded,i=$e()}));break;case 1:case 0:r.add($s(e,"loadstart").subscribe(()=>{t=0,i=$e()}));break}r.add($s(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=$e(),u=s-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=$e(),s=0,o=$e(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(r,$e()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=$e();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=l.byteLength,a=$e()}else s+=l.byteLength;o=$e()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&$e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,$e()-o,this.concurrentDownloads.size),s=0,o=$e());await i?.read().then(c,u)}};this.concurrentDownloads.add(e),i?.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=mo.get(e);if(Ms(t))return parseInt(t,10)??void 0}},Sl=fo;import{fillWithDefault as Hf,VideoQuality as Rs}from"@vkontakte/videoplayer-shared/evergreen";var vl={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Rs.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Rs.Q_720P,trafficSavingLimit:Rs.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Rs.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},yl=n=>({...Hf(n,vl),configName:[...n.configName??[],...vl.configName]});import{assertNonNullable as vo,combine as ct,ErrorCategory as Ds,filter as re,filterChanged as z,fromEvent as yo,isNonNullable as xl,isNullable as Zf,Logger as eb,map as j,mapTo as kl,merge as At,now as Ls,once as oe,Subject as H,Subscription as Pl,tap as To,ValueSubject as P,isHigher as tb,isInvariantQuality as Al,flattenObject as $t,throttle as Io,getTraceSubscriptionMethod as $l,TracerFactory as ib,InternalsExposure as rb,getPlayerId as ab,devNull as Cs}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Qf,map as jf,filter as Tl,isNonNullable as zf}from"@vkontakte/videoplayer-shared/evergreen";var go=({seekState:n,position$:e})=>Qf(n.stateChangeEnded$.pipe(jf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Tl(zf)),e.pipe(Tl(()=>n.getState().state==="none")));import{assertNonNullable as qf}from"@vkontakte/videoplayer-shared/evergreen";var Il=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return qf(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Wf,once as Gf}from"@vkontakte/videoplayer-shared/evergreen";var El=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Wf(r=>r.length>0),Gf()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};import{devNull as Yf,getWindow as So}from"@vkontakte/videoplayer-shared/evergreen";var wl=()=>{let n="mediaCapabilities"in So().navigator?Kf:Xf,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Jf).map(async([r,a])=>({codec:r,supported:await n(a)}))),i=[M.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Yf.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},Kf=async n=>{if(!n)return Promise.resolve({supported:!1});let e={["channels"in n?"audio":"video"]:n};return await So().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Xf=n=>{if(!n)return Promise.resolve({supported:!1});let e=So().document,t="channels"in n?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(n?.contentType??"")==="probably"})},Jf={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Bs=class{constructor(e={configName:[]},t=ib.createRootTracer(!1),i){this.subscription=new Pl;this.logger=new eb;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new P(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new P(void 0),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),currentNativeBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canPlayLiveTailBuffer$:new P(!1),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,firstBytesManifest$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:hu,getCurrentTime$:new P(null)};this.initLogs(),this.tuning=yl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(a=>a.setSuppressErrors(!0)),Object.values(this.events).forEach(a=>a.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Ze(r):new ua(r),this.throughputEstimator=new Sl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new rb("core",ab(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Cs.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(a,s,o)=>{let u=Reflect.get(a,s,o);return typeof u!="function"?u:(...c)=>{try{return u.apply(a,c)}catch(d){let l=c.map(m=>JSON.stringify(m,(f,g)=>{let b=typeof g;return["number","string","boolean"].includes(b)?g:g===null?null:`<${b}>`})),p=`Player.${String(s)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Ds.WTF,message:h,thrown:d}),d}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...s}=e;this.tracer.log("initVideo",$t(s)),this.domContainer=Il(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Xr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(Cs.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=wl())):Cs.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?M.isInited$.pipe(re(a=>!!a),oe()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yo(document,"visibilitychange").pipe(oe()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),Cs.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(re(t=>!!t),oe()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),s=t??(this.tuning.isAudioDisabled||a);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ze)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:s})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ze)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:s,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{vo(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),oe()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{El(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Zf(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(fu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),oe()).subscribe(()=>{this.initedAt=Ls(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$t(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Ds.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(oe()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$t(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(s=>s.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,c)=>Al(u)?1:Al(c)?-1:tb(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(s=>xl(s))).subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(j(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(j(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(To(s=>s&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ct({hasLiveOffsetByPaused:At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(s=>s.to),z(),j(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ct({atLiveEdge:ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:go({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:s,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return s&&Math.abs(o)<c/1e3}),z(),To(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),To(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(s=>s.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(s=>s.volume),z()).subscribe(this.info.volume$)).add(go({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(At(e.providerOutput.endedEvent$.pipe(kl(!0)),e.providerOutput.seekedEvent$.pipe(kl(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(s=>({id:s?`No${s}`:"NoProviders",category:Ds.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(oe()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(oe()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(oe()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(oe()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(oe()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(oe(),j(s=>s??Ls()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(oe(),j(()=>Ls()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(oe(),j(()=>Ls()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:s})=>s==="playing"),oe()).subscribe(()=>i.next(!1)));let r=0,a=At(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),z());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":u?c?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Pl;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),oe()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ye(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(At(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;vo(this.providerContainer),vo(e),pu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>du(t)),this.providerContainer.current$.subscribe(({type:t})=>_i("provider",t)),e.duration$.subscribe(t=>_i("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),oe()).subscribe(t=>_i("tracks",t)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(t=>this.subscription.add(t)),_i("codecs",M.video.supportedCodecs)}initTracerSubscription(){let e=$l(this.tracer.log.bind(this.tracer)),t=$l(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ct({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Io(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Io(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Io(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ds.DOM,message:String(r)})})};this.subscription.add(At(yo(document,"visibilitychange"),yo(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!qi()}};import{Subscription as kV,Observable as PV,Subject as AV,ValueSubject as $V,VideoQuality as MV}from"@vkontakte/videoplayer-shared/evergreen";var RV=`@vkontakte/videoplayer-core@${wo}`;export{$i as ChromecastState,Ns as HttpConnectionType,PV as Observable,fe as PlaybackState,Bs as Player,na as PredefinedQualityLimits,RV as SDK_VERSION,AV as Subject,kV as Subscription,_s as Surface,wo as VERSION,$V as ValueSubject,Je as VideoFormat,MV as VideoQuality,ad as areValidLiveRecordSources,M as clientChecker,Ct as isMobile};
|