@vkontakte/videoplayer-core 2.0.150-dev.f4d0e2c9.0 → 2.0.151-dev.ea826f67.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 +35 -35
- package/es2015.esm.js +32 -32
- package/es2018.cjs +31 -31
- package/es2018.esm.js +36 -36
- package/es2024.cjs +32 -32
- package/es2024.esm.js +35 -35
- package/esnext.cjs +32 -32
- package/esnext.esm.js +35 -35
- package/evergreen.esm.js +42 -42
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +3 -1
- package/types/player/types.d.ts +21 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +20 -1
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProviderVirtual/lib/fetcher.d.ts +20 -1
- package/types/providers/DashProviderVirtual/lib/player/basePlayer.d.ts +3 -1
- package/types/providers/types.d.ts +3 -1
- package/types/providers/utils/videoStreamRepresentaionsFilter.d.ts +4 -0
- package/types/utils/tuningConfig.d.ts +1 -0
package/evergreen.esm.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.151-dev.ea826f67.0
|
|
3
|
+
* Thu, 29 Jan 2026 11:04:30 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
|
|
5
5
|
*/
|
|
6
|
-
var wo="2.0.150-dev.f4d0e2c9.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 Ll,isNonNullable as oa,ValueSubject as Fs,Subject as Bl,Subscription as Cl,merge as Vl,observableFrom as Ol,fromEvent as ko,map as Po,tap as Ao,filterChanged as Nl,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 Cl;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(Vl(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)),Ol([i.getCastState()])).pipe(Nl(),Po(_l),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();Ll(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})}}},_l=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 ad,filter as ei,filterChanged as Ho,isNonNullable as Ks,isNullable as Qo,map as sd,Subscription as nd,ValueSubject as Xs}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Fl,assertNonNullable as Lt,ErrorCategory as Ul,getHighestQuality as Hl,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=Hl(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:Ul.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return Fl(t)}let u=Ql(i.videoId??a,s);u.contentUrl=a,u.streamType=o,u.metadata=jl();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 Ql(n,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(n,e):{contentId:n,contentType:e,metadata:{title:"",subtitle:""},streamType:la()}}function jl(){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 td,ValueSubject as id}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as zl}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}=zl().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 Bt=()=>/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=Bt()}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 Bo,isBrowserWindow as ql}from"@vkontakte/videoplayer-shared/evergreen";var fa=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Bo()}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=Bo();if(!ql(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),Co=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ba=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Wl=js().document?.createElement("video"),Gl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Yl='video/mp4; codecs="hev1.1.6.L93.B0"',Oo='video/webm; codecs="vp09.00.10.08"',No='video/webm; codecs="av01.0.00M.08"',Kl='audio/mp4; codecs="mp4a.40.2"',Xl='audio/webm; codecs="opus"',_o,Jl=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}};Jl().catch(n=>{console.log(Wl),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:Co(),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?.(Gl),r=!!Pe()?.isTypeSupported?.(Yl),a=!!Pe()?.isTypeSupported?.(Kl);this._codecs={h264:i,h265:r,vp9:!!Pe()?.isTypeSupported?.(Oo),av1:!!Pe()?.isTypeSupported?.(No),aac:a,opus:!!Pe()?.isTypeSupported?.(Xl),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 Zl,isBrowserWindow as ed}from"@vkontakte/videoplayer-shared/evergreen";var Fo="audio/mpeg",Sa=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=Zl();if(!ed(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 id(!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(){td()&&(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)}},rd=n=>{let t=Object.keys(n).filter(i=>!Mi(i));return qs(t).length>0};var Ri=class{constructor(e){this.subscription=new nd;this.sessionId$=new Xs(null);this.mediaSessionId$=new Xs(null);this.contentId$=new Xs(null);this.isMobile=Bt();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:ad.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(),sd(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 od,ErrorCategory as Js,filter as ud,Subject as cd,Subscription as Zs,tap as ld,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 cd;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();od(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(ld(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),ud(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 dd,map as pd,Subscription as hd,combine as md,filterChanged as Wo,assertNonNullable as fd}from"@vkontakte/videoplayer-shared/evergreen";var Ze=class n{constructor(e){this.subscription=new hd;this.connection$=new qo(void 0);this.castState$=new qo("NOT_AVAILABLE");this.errorEvent$=new dd;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(){fd(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=md({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Wo())});this.subscription.add(e.pipe(pd(({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 bd,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||bd(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 Bi,debounce as Yo,ErrorCategory as gd,fromEvent as Ct,map as Ko,merge as Xo,observableFrom as Sd,Subject as vd,Subscription as en,timeout as yd}from"@vkontakte/videoplayer-shared/evergreen";var Td=5,Id=5,Ed=500,Jo=7e3,Ci=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:Bi(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:Bi(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:Bi(e)}break}default:Bi(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 vd;e.add(r.pipe(Yo(Ed)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ct(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)>Td)&&r.next(o),a=o})),e.add(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer: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<Id&&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:Bi(s)}}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Sd(["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(yd(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:gd.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 xd}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as wd}from"@vkontakte/videoplayer-shared/evergreen";var Zo=n=>{try{n.pause(),n.playbackRate=0,wd(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as kd,Subscription as Pd}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=xd(),rn=ya.WeakMap?new ya.WeakMap:new tn,an=ya.WeakMap?new ya.WeakMap:new Map,Ad=(n,e=20)=>{let t=0;return kd(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 Pd;return a.add(Ad(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 Rd,fromEvent as ii,merge as tu,observableFrom as iu,filterChanged as ru,map as Ni,Subject as au,Subscription as Dd,ValueSubject as Ld,ErrorCategory as Bd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as sn,isNullable as $d,Subscription as Md}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=$d(r),c=new Md;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 Cd=n=>["__",n.language,n.label].join("|"),Vd=(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 Ld(void 0);this.error$=new au;this.subscription=new Dd;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:Cd(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))(Rd(e)||!Vd(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 Nd,filter as un,mapTo as cn,combine as _d,once as Fd,shareReplay as ge,throttle as Ud,ErrorCategory as Hd,ValueSubject as lu,Subscription as Qd}from"@vkontakte/videoplayer-shared/evergreen";var Od=3,ou=(n,e,t=Od)=>{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 Qd,i=()=>t.unsubscribe(),r=Ia(be(n,"progress"),be(n,"timeupdate")).pipe(Ge(()=>ou(n.buffered,n.currentTime)),ge(1)),a=M.browser.isSafari?_d({play:e("play").pipe(Fd()),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:Hd.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 Nd,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(Ud(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 jd,isHigherOrEqual as ov,isLower as mu,isLowerOrEqual as uv,isNonNullable as Ea,isNullable as zd,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 zd(n)||Ea(n.min)&&Ea(n.max)&&mu(n.max,n.min)||Ea(n.min)&&e&&jd(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 ${
|
|
8
|
-
`}),
|
|
6
|
+
var Mo="2.0.151-dev.ea826f67.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 Li=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Li||{}),Qa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Qa||{});var qa=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(qa||{}),ds=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ds||{});import{assertNever as Co,assertNonNullable as Od,isNonNullable as ls,ValueSubject as za,Subject as Nd,Subscription as _d,merge as Fd,observableFrom as Ud,fromEvent as $o,map as Ro,tap as Do,filterChanged as Hd,isNullable as Wa,ErrorCategory as Lo}from"@vkontakte/videoplayer-shared/evergreen";var Ao=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ps=class{constructor(e){this.connection$=new za(void 0);this.castState$=new za("NOT_AVAILABLE");this.errorEvent$=new Nd;this.realCastState$=new za("NOT_AVAILABLE");this.subscription=new _d;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=ls(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Ao("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Lo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ls(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Wa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Wa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add($o(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Co(r.sessionState)}})).add(Fd($o(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Do(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Ro(r=>r.castState)),Ud([i.getCastState()])).pipe(Hd(),Ro(jd),Do(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=ls(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();Od(n);let u=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(Wa(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?ls(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Lo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},jd=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Co(o)}};import{assertNonNullable as Za,combine as en,debounce as tn,ErrorCategory as ul,filter as ii,filterChanged as zo,isNonNullable as rn,isNullable as Wo,map as cl,Subscription as dl,ValueSubject as sn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Qd,assertNonNullable as Lt,ErrorCategory as qd,getHighestQuality as zd,isNonNullable as Vo}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Bo}from"@vkontakte/videoplayer-shared/evergreen";var le=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Bo(t)}return o},hs=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:Bo(e)}};var fs=o=>{let{source:e,format:t,meta:i,output:r}=o,s,a,n;switch(t){case"MPEG":{let d=e[t];Lt(d);let p=zd(Object.keys(d));Lt(p);let h=d[p];Lt(h),s=h,a="video/mp4",n=ms();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=e[t];Lt(d),s=d.url,a="application/x-mpegurl",n=ms();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=e[t];Lt(d),s=d.url,a="application/dash+xml",n=ms();break}case"DASH_LIVE_CMAF":{let d=e[t];Lt(d),s=d.url,a="application/dash+xml",n=Oo();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=e[t];Lt(d),s=le(d.url),a="application/x-mpegurl",n=Oo();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",p=new Error(d);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:qd.VIDEO_PIPELINE,message:d,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return Qd(t)}let u=Wd(i.videoId??s,a);u.contentUrl=s,u.streamType=n,u.metadata=Gd();let{title:c,subtitle:l}=i;return Vo(c)&&(u.metadata.title=c),Vo(l)&&(u.metadata.subtitle=l),u};function ms(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Oo(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function Wd(o,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(o,e):{contentId:o,contentType:e,metadata:{title:"",subtitle:""},streamType:ms()}}function Gd(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var w=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};var bs=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 qo}from"@vkontakte/videoplayer-shared/evergreen";import{isBrowserWindow as al,ValueSubject as nl}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as Yd}from"@vkontakte/videoplayer-shared/evergreen";var gs=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,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||a||u||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}=Yd().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 Ga,isBrowserWindow as Ya}from"@vkontakte/videoplayer-shared/evergreen";var Ct=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ss=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=Ga();if(!Ya(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=Ga();if(!Ya(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,u="Unknown",c="Unknown";if(a){let l=r[0];typeof l=="number"?l<s.length&&s[l]!==void 0&&(u=s[l]):u=l}if(n){let l=r[1];typeof l=="number"?l<s.length&&s[l]!==void 0&&(c=s[l]):l!==void 0&&(c=l)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&a&&typeof r[0]=="string"&&(c=s[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 s=e.match(i);if(s){let a=r[0],n=r[1],u=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,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=Ga();if(!Ya(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 No,isBrowserWindow as Kd}from"@vkontakte/videoplayer-shared/evergreen";var vs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in No()}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=No();if(!Kd(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 Ka,isBrowserWindow as Fo}from"@vkontakte/videoplayer-shared/evergreen";var Pe=()=>window.ManagedMediaSource||window.MediaSource,ti=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),_o=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ys=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Xd=Ka().document?.createElement("video"),Jd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Zd='video/mp4; codecs="hev1.1.6.L93.B0"',Uo='video/webm; codecs="vp09.00.10.08"',Ho='video/webm; codecs="av01.0.00M.08"',el='audio/mp4; codecs="mp4a.40.2"',tl='audio/webm; codecs="opus"',jo,il=async()=>{let o=Ka();if(!Fo(o))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([o.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Ho}}),o.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Uo}})]);jo={DASH_WEBM_AV1:t,DASH_WEBM:i}};il().catch(o=>{console.log(Xd),console.error(o)});var Ts=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 jo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=Ka();if(!Fo(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:ti(),mse:_o(),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?.(Jd),r=!!Pe()?.isTypeSupported?.(Zd),s=!!Pe()?.isTypeSupported?.(el);this._codecs={h264:i,h265:r,vp9:!!Pe()?.isTypeSupported?.(Uo),av1:!!Pe()?.isTypeSupported?.(Ho),aac:s,opus:!!Pe()?.isTypeSupported?.(tl),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 rl,isBrowserWindow as sl}from"@vkontakte/videoplayer-shared/evergreen";var Qo="audio/mpeg",Is=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=rl();if(!sl(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Qo)},this._codecs={mp3:!!Pe()?.isTypeSupported?.(Qo)}}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 Xa=class{constructor(){this.isInited$=new nl(!1);this._displayChecker=new vs,this._deviceChecker=new Ss(this._displayChecker),this._browserChecker=new gs,this._videoChecker=new Ts(this._deviceChecker,this._browserChecker),this._audioChecker=new Is,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(){al()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},$=new Xa;var Ja=o=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return o.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 qo(n)}})},Ci=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return qo(o)}},ol=o=>{let t=Object.keys(o).filter(i=>!Ci(i));return Ja(t).length>0};var Bi=class{constructor(e){this.subscription=new dl;this.sessionId$=new sn(null);this.mediaSessionId$=new sn(null);this.contentId$=new sn(null);this.isMobile=Ct();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Wo(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;rn(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(rn(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 bs(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ci(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:ul.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ii(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(ii(rn),zo(),tn(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(zo(),cl(Boolean));this.subscription.add(en({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ii(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=en({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(ii(({mediaLoaded:r})=>r),tn(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(ii(({mediaLoaded:r,playbackState:{from:s,to:a}})=>!r&&s==="stopped"&&a==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(en({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(tn(30)),mediaLoaded:t}).pipe(ii(({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=fs(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();Za(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Za(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Za(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(Wo(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 ll,ErrorCategory as an,filter as pl,Subject as hl,Subscription as nn,tap as ml,ValueSubject as ri,fromEvent as Vi}from"@vkontakte/videoplayer-shared/evergreen";var Go=o=>({castDevice:{friendlyName:o},remotePlayer:{},remotePlayerController:{},session:{}}),Yo=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Oi=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new ri(null);this.sessionId$=new ri(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new nn;this.subscriptionEvents=new nn;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new ri(!1);this.presentationConnection$=new ri(null);this.message$=new ri(null);this.friendlyName$=new ri(null);this.errorEvent$=new hl;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(Vi(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();ll(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:an.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Vi(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(ml(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),pl(e=>!!e)).subscribe(e=>{let t=Vi(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=Vi(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Vi(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:an.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:an.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]||Yo()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new nn}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 Ko,Subject as fl,map as bl,Subscription as gl,combine as Sl,filterChanged as Xo,assertNonNullable as vl}from"@vkontakte/videoplayer-shared/evergreen";var Ze=class o{constructor(e){this.subscription=new gl;this.connection$=new Ko(void 0);this.castState$=new Ko("NOT_AVAILABLE");this.errorEvent$=new fl;let t=o.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 Oi({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){vl(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Sl({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Xo())});this.subscription.add(e.pipe(bl(({connection:t,friendlyName:i})=>!!(t&&i)),Xo()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Go(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 yl,Subject as Es,merge as Jo}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new Es;this.transitionEnded$=new Es;this.transitionUpdated$=new Es;this.forceChanged$=new Es;this.stateChangeStarted$=Jo(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Jo(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||yl(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 Ni,debounce as Zo,ErrorCategory as Tl,fromEvent as Bt,map as eu,merge as tu,observableFrom as Il,Subject as El,Subscription as on,timeout as wl}from"@vkontakte/videoplayer-shared/evergreen";var xl=5,kl=5,Pl=500,iu=7e3,_i=class{constructor(e){this.subscription=new on;this.loadMediaTimeoutSubscription=new on;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ni(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:Ni(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:Ni(e)}break}default:Ni(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ci(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 on;this.subscription.add(e),this.subscription.add(tu(this.videoState.stateChangeStarted$.pipe(eu(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(eu(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 El;e.add(r.pipe(Zo(Pl)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Bt(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)>xl)&&r.next(n),s=n})),e.add(Bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.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:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<kl&&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:Ni(a)}}),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=tu(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Il(["init"])).pipe(Zo(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=fs(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,s)=>{this.loadMediaTimeoutSubscription.add(wl(iu).subscribe(()=>s(`timeout(${iu})`)))});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:Tl.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as su,getWindow as Al}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Ml}from"@vkontakte/videoplayer-shared/evergreen";var ru=o=>{try{o.pause(),o.playbackRate=0,Ml(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as $l,Subscription as Rl}from"@vkontakte/videoplayer-shared/evergreen";var un=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)}},ws=Al(),cn=ws.WeakMap?new ws.WeakMap:new un,dn=ws.WeakMap?new ws.WeakMap:new Map,Dl=(o,e=20)=>{let t=0;return $l(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Te=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?su(i):(i=document.createElement("video"),o.appendChild(i)),cn.set(i,r);let s=new Rl;return s.add(Dl(i,e)),dn.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=o=>{dn.get(o)?.unsubscribe(),dn.delete(o);let t=cn.get(o);cn.delete(o),t?su(o):ru(o)};import{assertNonNullable as Ui,isNonNullable as We,isNullable as Bl,fromEvent as si,merge as au,observableFrom as nu,filterChanged as ou,map as Hi,Subject as uu,Subscription as Vl,ValueSubject as Ol,ErrorCategory as Nl}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ln,isNullable as Ll,Subscription as Cl}from"@vkontakte/videoplayer-shared/evergreen";var xs=(o,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=o.getState(),n=e(),u=Ll(r),c=new Cl;return r&&c.add(r.subscribe(l=>{let d=o.getState();i(l,d)&&o.setState(l)},s)),i(n,a)||(t(a),u&&o.setState(a)),c.add(o.stateChangeStarted$.subscribe(l=>{t(l.to),u&&o.setState(l.to)},s)),c},ze=(o,e,t)=>xs(e,()=>o.loop,i=>{ln(i)&&(o.loop=i)},{onError:t}),Ee=(o,e,t,i)=>xs(e,()=>({muted:o.muted,volume:o.volume}),r=>{ln(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(o,e,t,i)=>xs(e,()=>o.playbackRate,r=>{ln(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Fi=xs;var _l=o=>["__",o.language,o.label].join("|"),Fl=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},pn=class o{constructor(e){this.available$=new uu;this.current$=new Ol(void 0);this.error$=new uu;this.subscription=new Vl;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Nl.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(Fi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Fi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Fi(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(Fi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ui(this.video);let{textTracks:e}=this.video;this.subscription.add(si(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(au(si(e,"addtrack"),si(e,"removetrack"),nu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ou((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(au(si(e,"change"),nu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Hi(i=>i&&this.htmlTextTrackToITextTrack(i).id),ou()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(si(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(si(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){Ui(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:_l(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){Ui(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Bl(e)||!Fl(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){Ui(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){Ui(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=pn;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 cu=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},hn=o=>{let e=cu(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},du=o=>{let e=cu(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as be,map as Ge,merge as ks,filterChanged as pu,isNonNullable as hu,Subject as Hl,filter as mn,mapTo as fn,combine as jl,once as Ql,shareReplay as ge,throttle as ql,ErrorCategory as zl,ValueSubject as mu,Subscription as Wl}from"@vkontakte/videoplayer-shared/evergreen";var Ul=3,lu=(o,e,t=Ul)=>{let i=0,r=0;for(let s=0;s<o.length;s++){let a=o.start(s),n=o.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=s+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var we=o=>{let e=E=>be(o,E).pipe(fn(void 0),ge(1)),t=new Wl,i=()=>t.unsubscribe(),r=ks(be(o,"progress"),be(o,"timeupdate")).pipe(Ge(()=>lu(o.buffered,o.currentTime)),ge(1)),s=$.browser.isSafari?jl({play:e("play").pipe(Ql()),playing:e("playing")}).pipe(fn(void 0),ge(1)):e("playing"),a=be(o,"volumechange").pipe(Ge(()=>({muted:o.muted,volume:o.volume})),ge(1)),n=be(o,"ratechange").pipe(Ge(()=>o.playbackRate),ge(1)),u=be(o,"error").pipe(mn(()=>!!(o.error||o.played.length)),Ge(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:zl.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),ge(1)),c=be(o,"timeupdate").pipe(Ge(()=>o.currentTime),ge(1)),l=["waiting","seeking","seeked","timeupdate"],d=new Hl,p=.3,h;t.add(ks(...l.map(E=>be(o,E))).subscribe(E=>{let _=o.currentTime;o.loop&&hu(h)&&hu(_)&&h>=o.duration-p&&_<=p&&d.next(h),h=_}));let m=e("pause").pipe(mn(()=>!o.error&&h!==o.duration),ge(1)),f=be(o,"enterpictureinpicture").pipe(ge(1)),b=be(o,"leavepictureinpicture").pipe(ge(1)),g=new mu(du(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new mu(hn(o)),I=be(o,"fullscreenchange").pipe(ge(1));t.add(I.pipe(Ge(()=>hn(o))).subscribe(S));let v=.1,x=1e3,A=be(o,"timeupdate").pipe(Ge(E=>o.duration-o.currentTime<v),pu(),ge(1)),R=ks(A.pipe(mn(E=>!o.loop&&E)),be(o,"ended")).pipe(ql(x),fn(void 0),ge(1)),D=ks(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>be(o,E)),A.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>$.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),pu(),ge(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:R,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:be(o,"durationchange").pipe(Ge(()=>o.duration),ge(1)),isBuffering$:D,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=o=>{switch(o){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as z,isNullable as $s,now as xu,isHigher as Rs,isHigherOrEqual as Ot,isInvariantQuality as Ds,isLowerOrEqual as ni,videoSizeToQuality as ku,assertNotEmptyArray as Ls,assertNonNullable as Pu}from"@vkontakte/videoplayer-shared/evergreen";var bn=!1,et={},fu=o=>{bn=o},bu=()=>{et={}},gu=o=>{o(et)},ji=(o,e)=>{bn&&(et.meta=et.meta??{},et.meta[o]=e)},Se=class{constructor(e){this.name=e}next(e){if(!bn)return;et.series=et.series??{};let t=et.series[this.name]??[];t.push([Date.now(),e]),et.series[this.name]=t}};import{isHigher as Gl,isHigherOrEqual as uv,isLower as Su,isLowerOrEqual as cv,isNonNullable as Ps,isNullable as Yl,videoHeightToQuality as Ms}from"@vkontakte/videoplayer-shared/evergreen";function vu(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ai(o,e,t){return Yl(o)||Ps(o.min)&&Ps(o.max)&&Su(o.max,o.min)||Ps(o.min)&&e&&Gl(o.min,e)||Ps(o.max)&&t&&Su(o.max,t)}function yu({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return ai({max:o?.max?Ms(o.max):void 0,min:o?.min?Ms(o.min):void 0},e?Ms(e):void 0,t?Ms(t):void 0)}var Mu=new Se("best_bitrate"),Cs=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var oi=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xu()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bs='Assertion "ABR Tracks is empty array" failed',As=new WeakMap,Tu=new WeakMap,Iu=new WeakMap,Qi=(o,e,t,i)=>{let r=[...e].sort(oi(1)),s=[...t].sort(oi(1)),a=s.filter(u=>z(u.bitrate)&&z(o.bitrate)?o.bitrate/u.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},qi=(o,e,t,i)=>{let r=As.get(e);r||(r=[...e].sort(oi(1)),As.set(e,r));let s=As.get(t);s||(s=[...t].sort(oi(1)),As.set(t,s));let a=Iu.get(o);a||(a=s.filter(u=>z(u.bitrate)&&z(o.bitrate)?o.bitrate/u.bitrate>i:!0),Iu.set(o,a));let n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Eu=o=>"quality"in o,Vs=(o,e,t,i)=>{let r=z(i?.last?.bitrate)&&z(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&xu()-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=Eu(a)?"video":"audio",u=Eu(a)?a.quality:a.bitrate;return e({message:`
|
|
7
|
+
[last ${n} selected] ${u}
|
|
8
|
+
`}),a}return i?.recordSwitch(t),t},Kl=(o,e)=>Math.log(e)/Math.log(o),Au=({tuning:o,container:e,limits:t,panelSize:i})=>{let r=o.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(o.usePixelRatio&&$.display.pixelRatio){let s=$.display.pixelRatio;if(o.pixelRatioMultiplier)r*=o.pixelRatioMultiplier*(s-1)+1;else{let a=o.pixelRatioLogBase,[n=0,u=0,c=0]=o.pixelRatioLogCoefficients,l=Kl(a,n*s+u)+c;Number.isFinite(l)&&(r*=l)}}return z(t?.min)&&Ot(t.min,o.highQualityLimit)&&(r*=2),{containerSizeLimit:o.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},wu=new WeakMap,Ye=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{Ls(o,Bs);let{containerSizeFactor:b,containerSizeLimit:g}=Au({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&z(n)?n:1,I=wu.get(o);I||(I=o.filter(T=>!Ds(T.quality)).sort((T,y)=>Rs(T.quality,y.quality)?-1:1),wu.set(o,I));let v=I.at(-1)?.quality,x=I.at(0)?.quality,A=ai(r,x,v),R=S*Cs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},D=null;for(let T of I){let y=!0;if(g)if(T.size)y=T.size.width<=g.width&&T.size.height<=g.height;else{let U=g&&ku(g);y=U?ni(T.quality,U):!0}if(!y){k[T.quality]="FitsContainer";continue}let V=h||t,M=z(V)&&isFinite(V)&&z(T.bitrate)?V-s>=T.bitrate*R:!0,F=r?.min===T.quality;if(!M&&!F){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&z(i.minBufferToSwitchUp)&&u&&!Ds(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Rs(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!d&&Ot(T.quality,d)&&!F){k[T.quality]="DroppedFramesLimit";continue}if(!!p&&Ot(T.quality,p)&&!F){k[T.quality]="StallsLimit";continue}let ue=A||($s(r?.max)||ni(T.quality,r.max))&&($s(r?.min)||Ot(T.quality,r.min)),ce=z(l)&&!l?ni(T.quality,i.backgroundVideoQualityLimit):!0;if(!ue||!ce){k[T.quality]="FitsQualityLimits";continue}D||(D=T)}D&&D.bitrate&&Mu.next(D.bitrate);let E=D??I.at(-1)??o[0],_=c?.last,C=Vs(i,m,E,c);return z(c)&&C.quality!==_?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${
|
|
11
|
+
${o.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]
|
|
@@ -16,17 +16,17 @@ var wo="2.0.150-dev.f4d0e2c9.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
19
|
-
containerSizeFactor: ${
|
|
20
|
-
containerSizeLimit: ${
|
|
19
|
+
containerSizeFactor: ${b},
|
|
20
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
21
21
|
estimatedThroughput: ${t},
|
|
22
22
|
stallsPredictedThroughput: ${h},
|
|
23
|
-
reserve: ${
|
|
24
|
-
playbackRate: ${
|
|
23
|
+
reserve: ${s},
|
|
24
|
+
playbackRate: ${n},
|
|
25
25
|
playbackRateFactor: ${S},
|
|
26
|
-
forwardBufferHealth: ${
|
|
26
|
+
forwardBufferHealth: ${a},
|
|
27
27
|
bitrateFactor: ${R},
|
|
28
28
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
29
|
-
droppedVideoMaxQualityLimit: ${
|
|
29
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
30
30
|
stallsVideoMaxQualityLimit: ${p},
|
|
31
31
|
limitsAreInvalid: ${A},
|
|
32
32
|
maxQualityLimit: ${r?.max},
|
|
@@ -37,41 +37,41 @@ var wo="2.0.150-dev.f4d0e2c9.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
39
|
[best video track] ${D?.quality}
|
|
40
|
-
[selected video track] ${
|
|
41
|
-
`}),
|
|
40
|
+
[selected video track] ${C?.quality}
|
|
41
|
+
`}),C},Os=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{Ls(o,Bs);let{containerSizeFactor:b,containerSizeLimit:g}=Au({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&z(n)?n:1,I=o.filter(y=>!Ds(y.quality)).sort((y,V)=>Rs(y.quality,V.quality)?-1:1),v=I.at(-1)?.quality,x=I.at(0)?.quality,A=ai(r,x,v),R=S*Cs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},E=I.filter(y=>{let V=!0;if(g)if(y.size)V=y.size.width<=g.width&&y.size.height<=g.height;else{let N=g&&ku(g);V=N?ni(y.quality,N):!0}if(!V)return k[y.quality]="FitsContainer",!1;let M=h||t,F=z(M)&&isFinite(M)&&z(y.bitrate)?M-s>=y.bitrate*R:!0,W=r?.min===y.quality;if(!F&&!W)return k[y.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&z(i.minBufferToSwitchUp)&&u&&!Ds(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Rs(y.quality,u.quality))return k[y.quality]="Buffer",!1;if(!!d&&Ot(y.quality,d)&&!W)return k[y.quality]="DroppedFramesLimit",!1;if(!!p&&Ot(y.quality,p)&&!W)return k[y.quality]="StallsLimit",!1;let ce=A||($s(r?.max)||ni(y.quality,r.max))&&($s(r?.min)||Ot(y.quality,r.min)),U=z(l)&&!l?ni(y.quality,i.backgroundVideoQualityLimit):!0;return!ce||!U?(k[y.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&Mu.next(E.bitrate);let _=E??I.at(-1)??o[0],C=c?.last,T=Vs(i,m,_,c);return z(c)&&T.quality!==C?.quality&&m({message:`
|
|
42
42
|
[VIDEO TRACKS ABR]
|
|
43
43
|
[available video tracks]
|
|
44
|
-
${
|
|
44
|
+
${o.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(([y,
|
|
48
|
+
${Object.entries(i??{}).map(([y,V])=>`${y}: ${V}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
[limit params]
|
|
52
|
-
containerSizeFactor: ${
|
|
53
|
-
containerSizeLimit: ${
|
|
52
|
+
containerSizeFactor: ${b},
|
|
53
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
54
54
|
estimatedThroughput: ${t},
|
|
55
55
|
stallsPredictedThroughput: ${h},
|
|
56
|
-
reserve: ${
|
|
57
|
-
playbackRate: ${
|
|
56
|
+
reserve: ${s},
|
|
57
|
+
playbackRate: ${n},
|
|
58
58
|
playbackRateFactor: ${S},
|
|
59
|
-
forwardBufferHealth: ${
|
|
59
|
+
forwardBufferHealth: ${a},
|
|
60
60
|
bitrateFactor: ${R},
|
|
61
61
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
62
|
-
droppedVideoMaxQualityLimit: ${
|
|
62
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
63
63
|
stallsVideoMaxQualityLimit: ${p},
|
|
64
64
|
limitsAreInvalid: ${A},
|
|
65
65
|
maxQualityLimit: ${r?.max},
|
|
66
66
|
minQualityLimit: ${r?.min},
|
|
67
67
|
|
|
68
68
|
[limited video tracks]
|
|
69
|
-
${Object.entries(k).map(([y,
|
|
69
|
+
${Object.entries(k).map(([y,V])=>`${y}: ${V}`).join(`
|
|
70
70
|
`)||"All tracks are available"}
|
|
71
71
|
|
|
72
72
|
[best video track] ${E?.quality}
|
|
73
73
|
[selected video track] ${T?.quality}
|
|
74
|
-
`}),T},
|
|
74
|
+
`}),T},Ns=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:c})=>{Ls(t,Bs);let l=r.considerPlaybackRate&&z(s)?s:1,d=[...t].sort(oi(-1)),p=o.bitrate;Pu(p);let h=l*Cs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Qi(o,e,t,r.minVideoAudioRatio),b=c||i;z(b)&&isFinite(b)&&(m=d.find(I=>z(I.bitrate)&&z(f?.bitrate)?b-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Vs(r,u,m,n);return z(n)&&S?.bitrate!==g?.bitrate&&u({message:`
|
|
75
75
|
[AUDIO TRACKS ABR]
|
|
76
76
|
[available audio tracks]
|
|
77
77
|
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
@@ -85,14 +85,14 @@ var wo="2.0.150-dev.f4d0e2c9.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
85
85
|
estimatedThroughput: ${i},
|
|
86
86
|
stallsPredictedThroughput: ${c},
|
|
87
87
|
reserve: ${p},
|
|
88
|
-
playbackRate: ${
|
|
89
|
-
playbackRateFactor: ${
|
|
90
|
-
forwardBufferHealth: ${
|
|
88
|
+
playbackRate: ${s},
|
|
89
|
+
playbackRateFactor: ${l},
|
|
90
|
+
forwardBufferHealth: ${a},
|
|
91
91
|
bitrateFactor: ${h},
|
|
92
92
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
93
93
|
|
|
94
94
|
[selected audio track] ${S?.id}
|
|
95
|
-
`}),S},
|
|
95
|
+
`}),S},_s=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:c})=>{Ls(t,Bs);let l=r.considerPlaybackRate&&z(s)?s:1,d=Tu.get(t);d||(d=[...t].sort(oi(-1)),Tu.set(t,d));let p=o.bitrate;Pu(p);let h=l*Cs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=qi(o,e,t,r.minVideoAudioRatio),b=c||i;z(b)&&isFinite(b)&&(m=d.find(I=>z(I.bitrate)&&z(f?.bitrate)?b-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Vs(r,u,m,n);return z(n)&&S?.bitrate!==g?.bitrate&&u({message:`
|
|
96
96
|
[AUDIO TRACKS ABR]
|
|
97
97
|
[available audio tracks]
|
|
98
98
|
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
@@ -106,14 +106,14 @@ var wo="2.0.150-dev.f4d0e2c9.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
106
106
|
estimatedThroughput: ${i},
|
|
107
107
|
stallsPredictedThroughput: ${c},
|
|
108
108
|
reserve: ${p},
|
|
109
|
-
playbackRate: ${
|
|
110
|
-
playbackRateFactor: ${
|
|
111
|
-
forwardBufferHealth: ${
|
|
109
|
+
playbackRate: ${s},
|
|
110
|
+
playbackRateFactor: ${l},
|
|
111
|
+
forwardBufferHealth: ${a},
|
|
112
112
|
bitrateFactor: ${h},
|
|
113
113
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
114
114
|
|
|
115
115
|
[selected audio track] ${S?.id}
|
|
116
|
-
`}),S};var pe=n=>new URL(n).hostname;import{assertNever as Du,assertNonNullable as Lu,combine as gp,debounce as Sp,ErrorCategory as Bu,filter as Cu,filterChanged as vp,isNonNullable as bn,map as _a,merge as Vu,observableFrom as yp,once as Tp,Subscription as Ip,ValueSubject as gn,videoQualityToHeight as Ou,videoSizeToQuality as Ep}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 Zd,assertNonNullable as ji}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Pu,assertNonNullable as Va,now as Wd}from"@vkontakte/videoplayer-shared/evergreen";function se(){return Wd()}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 B=dn(d),T;if(B<f){T=f-B,setTimeout(g,T);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,A()},b=B=>(a=B,_),S=B=>(l=B,_),I=()=>(h="json",_),v=()=>{if(!u){if(--c>=0){g(),i&&i();return}u=!0,l&&l(),t&&t()}},x=B=>(p=B,_),A=()=>{d=se(),s=new r,s.open("get",n);let B=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>B&&(a.updateChunk(O(),$.loaded-B),B=$.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-B;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:B=>(c=B,_),withRetryInterval:(B,T)=>(Pu(B)&&(f=B),Pu(T)&&(m=T),_),withTimeout:B=>(o=B,_),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 ep}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"&&Gd(n,e);function Gd(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Yd,safeStorage as Kd}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]}}},Xd=(n,e="warn")=>{let t=Yd(),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=Xd("vp_dash_live_debug",Kd.get("vp_dev_null_console_method")??!1);var Na=1e4,mn=3;var tp=6e4,ip=10,rp=1,ap=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 ep,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-rp;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)},B=$=>{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>ip)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,$(B(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,_,B=0,T,y,O,$=()=>{T&&(clearTimeout(T),T=void 0);let N=Math.max(ap,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=B+N,he=se(),ae=Math.min(1e4,le-he);B=he;let Me=()=>{c||l()&&R.seek(()=>{l()&&(B=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(B=se(),!N){$();return}_=N,!Zd(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))},tp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as sp,filter as Mu,fromEvent as np,interval as op,isHigher as up,isInvariantQuality as cp,isLower as lp,merge as dp,Subject as Ru,Subscription as pp}from"@vkontakte/videoplayer-shared/evergreen";var fn=class{constructor(){this.onDroopedVideoFramesLimit$=new Ru;this.subscription=new pp;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&&!cp(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&&up(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(np(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=op(this.droppedFramesChecker.checkTime).pipe(Mu(()=>this.playing),Mu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(sp(this.droppedFramesChecker.checkTime)),i=dp(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])=>lp(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 hp,Observable as mp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as fp}from"@vkontakte/videoplayer-shared/evergreen";var qi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var bp=(n,e)=>new mp(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=fp(document,"visibilitychange").pipe(hp(s=>!document.hidden||qi())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe()}}),Be=bp;var wp=["paused","playing","ready"],xp=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new Ip;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:Bu.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)??Ep(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(xp.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&wp.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:Bu.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)),Cu(r=>!!r.length),Tp()).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(vp(),_a(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(gp({zeroTime:this.zeroTime$.pipe(Cu(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(Be(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$,yp(["init"])).pipe(Sp(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 Zh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Up,assertNonNullable as Hp,debounce as Qp,ErrorCategory as Gu,filter as xn,filterChanged as kn,fromEvent as jp,isNonNullable as Yu,isNullable as zp,map as Pn,merge as qa,observableFrom as An,once as Ku,Subscription as qp,throttle as Wp}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as kp}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)??kp({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;
|
|
116
|
+
`}),S};var pe=o=>new URL(o).hostname;import{assertNever as Vu,assertNonNullable as Ou,combine as yp,debounce as Tp,ErrorCategory as Nu,filter as _u,filterChanged as Ip,isNonNullable as In,map as js,merge as Fu,observableFrom as Ep,once as wp,Subscription as xp,ValueSubject as En,videoQualityToHeight as Uu,videoSizeToQuality as kp}from"@vkontakte/videoplayer-shared/evergreen";var $u=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},xe=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!$u(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return $u(r)&&(o.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Us,isNullable as ip,assertNonNullable as Gi}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Ru,assertNonNullable as Fs,now as Xl}from"@vkontakte/videoplayer-shared/evergreen";function ae(){return Xl()}function gn(o){return ae()-o}function Sn(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let c=a.indexOf("?")>-1?"&":"?";return u&&(a+=c+"lowLat=1",c="&"),n&&(a+=c+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Du(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function ui(o,e,t,i){let r=window.XMLHttpRequest,s,a,n,u=!1,c=0,l,d,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;Fs(l);let C=gn(l),T;if(C<f){T=f-C,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,A()},g=C=>(s=C,_),S=C=>(d=C,_),I=()=>(h="json",_),v=()=>{if(!u){if(--c>=0){b(),i&&i();return}u=!0,d&&d(),t&&t()}},x=C=>(p=C,_),A=()=>{l=ae(),a=new r,a.open("get",o);let C=0,T,y=0,V=()=>(Fs(l),Math.max(l,Math.max(T||0,y||0)));if(s&&a.addEventListener("progress",M=>{let F=ae();s.updateChunk&&M.loaded>C&&(s.updateChunk(V(),M.loaded-C),C=M.loaded,T=F)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(u)return;Fs(a);let M=a.status;if(M>=200&&M<300){let{response:F,responseType:W}=a,Z=F?.byteLength;if(typeof Z=="number"&&s){let te=Z-C;te&&s.updateChunk&&s.updateChunk(V(),te)}W==="json"&&(!F||!Object.values(F).length)?v():(d&&d(),e(F))}else v()}),a.addEventListener("error",()=>{v()}),p){let M=()=>{Fs(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(y=ae(),a.removeEventListener("readystatechange",M))};a.addEventListener("readystatechange",M)}return a.responseType=h,a.send(),_},_={withBitrateReporting:g,withParallel:x,withJSONResponse:I,withRetryCount:C=>(c=C,_),withRetryInterval:(C,T)=>(Ru(C)&&(f=C),Ru(T)&&(m=T),_),withTimeout:C=>(n=C,_),withFinally:S,send:A,abort:()=>{a&&(a.abort(),a=void 0),u=!0,d&&d()}};return _}var zi=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 u=s.bytes*a/n;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Wi=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ae(),r=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)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ui(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=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let 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 rp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Lu}from"@vkontakte/videoplayer-shared/evergreen";var Y=(o,e)=>Lu(o)&&Lu(e)&&o.readyState==="open"&&Jl(o,e);function Jl(o,e){for(let t=0;t<o.activeSourceBuffers.length;++t)if(o.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Zl}from"@vkontakte/videoplayer-shared/evergreen";var vn=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]}}},ep=(o,e="warn")=>{let t=Zl(),i=[];function r(s,a=!1){let n=t.performance?.timing?.navigationStart??0,u=new vn(o,Math.round((Date.now()-n)/1e3),s,a?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},L=ep("vp_dash_live_debug",!1);var Hs=1e4,yn=3;var sp=6e4,ap=10,np=1,op=500,Yi=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 rp,this.chunkRateEstimator=new zi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Sn(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=Sn(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,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:u,min:c}=this.autoQualityLimits||{};!yu({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&s.video.height>u||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||Us(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&&(L({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",n=>{L({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{L({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{Du(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Wi(yn,Hs,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,u=null,c=null,l=!1,d=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,x,A)=>{u&&u.abort(),u=ui(this.urlResolver.resolve(v,!1),x,A,()=>this._retryCallback()).withTimeout(Hs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yn).withFinally(()=>{u=null}).send()},h=(v,x,A)=>{Gi(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),x,A,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let x=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${x}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let A=ae()-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-np;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},g=v=>{let x,A=()=>x&&x.start?x.start.length:0,R=M=>x.start[M]/1e3,k=M=>x.dur[M]/1e3,D=M=>x.fragIndex+M,E=(M,F)=>({chunkIdx:D(M),startTS:R(M),dur:k(M),discontinuity:F}),_=()=>{let M=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);M=Math.min(te,x.dur.length-1-W),M=Math.max(M,0)}return E(M,!0)},C=M=>{let F=A();if(!(F<=0)){if(Us(M)){for(let W=0;W<F;W++)if(R(W)>M)return E(W)}return _()}},T=M=>{let F=A(),W=M?M.chunkIdx+1:0,Z=W-x.fragIndex;if(!(F<=0)){if(!M||Z<0||Z-F>ap)return t(`Resync: offset=${Z} bChunks=${F} chunk=`+JSON.stringify(M)),_();if(!(Z>=F))return E(W-x.fragIndex,!1)}},y=(M,F,W)=>{c&&c.abort(),c=ui(this.urlResolver.resolve(M,!0,this.lowLatency),F,W,()=>this._retryCallback()).withTimeout(Hs).withRetryCount(yn).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(M,F)=>{y(v,W=>{if(!d())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&&(Gi(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,M(C(F))},()=>this._handleNetworkError())},nextChunk:T}},S=()=>{s=!1,n&&n.abort(),u&&u.abort(),c&&c.abort(),Gi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:x,logger:A}=this.params,R=g(e.jidxUrl),k,D,E,_,C=0,T,y,V,M=()=>{T&&(clearTimeout(T),T=void 0);let N=Math.max(op,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),de=C+N,he=ae(),se=Math.min(1e4,de-he);C=he;let $e=()=>{c||d()&&R.seek(()=>{d()&&(C=ae(),F(),M())})};se>0?T=window.setTimeout(()=>{this.paused?M():$e()},se):$e()},F=()=>{let N;for(;N=R.nextChunk(_);)_=N,ce(N);let de=R.nextChunk(E);if(de){if(E&&de.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?M():(S(),L({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}ue(de)}else M()},W=(N,de)=>{if(!d()||!this.sourceBuffer){L({m:"ab.0",c:[!d(),!this.sourceBuffer]});return}let he,se,$e,dt=Ve=>{L({m:"ldp.postpone",t:Ve}),window.setTimeout(()=>{d()&&W(N,de)},Ve)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),L({m:"ldp.ab.1"}),dt(100);else{let Ve=ae(),ke=x.currentTime;!this.paused&&x.buffered.length>1&&y===ke&&Ve-V>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),y!==ke&&(y=ke,V=Ve);let lt=this._getBufferSizeSec();if(lt>30)L({m:"ldp.ab.3"}),A(`Buffered ${lt} seconds; delaying appendBuffer`),dt(2e3);else try{if(this.params.config.useInvalidBufferFix&&Y(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(L({m:"ldp.ab.5"}),this.bufferStates.push({ts:Ve,buf:lt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(L({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),de&&de()}catch(Oe){if(L({m:"ldp.ab.err",e:Oe.name}),Oe.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),$e=this.sourceBuffer.buffered.length,$e!==0&&(he=this.sourceBuffer.buffered.start(0),se=ke,se-he>4&&this.sourceBuffer.remove(he,se-3)),dt(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=>{d()&&h(te(N),(de,he)=>{if(d()){if(he/=1e3,D=de,E=N,a=N.startTS,he){let se=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*se:se}Z()}},()=>this._handleNetworkError())},ce=N=>{d()&&(Gi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(N),!1)))},U=N=>{d()&&(e.cachedHeader=N,W(N,()=>{k=!0,Z()}))};s=!0,R.seek(N=>{if(d()){if(C=ae(),!N){M();return}_=N,!ip(v)||N.startTS>v?ue(N):(E=N,F())}},v),e.cachedHeader?U(e.cachedHeader):p(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Us(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,Gi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/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(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ae();if(this.chunkRateEstimator.addInterval(p,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:b}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},a=-1/0,n,u=!0,c=()=>{let d=s.get();if(d&&n&&this.autoQuality){if(u&&d>n&&gn(a)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ae();d<n&&(a=p),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=ui(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Hs).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,s=a=>{let n=[];return a?.length?(a.forEach((u,c)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=c,n.push(u))}),n.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.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))},sp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as up,filter as Cu,fromEvent as cp,interval as dp,isHigher as lp,isInvariantQuality as pp,isLower as hp,merge as mp,Subject as Bu,Subscription as fp}from"@vkontakte/videoplayer-shared/evergreen";var Tn=class{constructor(){this.onDroopedVideoFramesLimit$=new Bu;this.subscription=new fp;this.playing=!1;this.tracks=[];this.forceChecker$=new Bu;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&&!pp(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&&lp(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(cp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=dp(this.droppedFramesChecker.checkTime).pipe(Cu(()=>this.playing),Cu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(up(this.droppedFramesChecker.checkTime)),i=mp(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])=>hp(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}},ci=Tn;import{map as bp,Observable as gp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Sp}from"@vkontakte/videoplayer-shared/evergreen";var Ki=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var vp=(o,e)=>new gp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(u=>t.next(u.isIntersecting||Ki()))},{...i,...e});r.observe(o);let s=Sp(document,"visibilitychange").pipe(bp(a=>!document.hidden||Ki())).subscribe(a=>t.next(a));return()=>{r.unobserve(o),s.unsubscribe()}}),Ce=vp;var Pp=["paused","playing","ready"],Mp=["paused","playing","ready"],Xi=class{constructor(e){this.subscription=new xp;this.videoState=new O("stopped");this.representations$=new En([]);this.droppedFramesManager=new ci;this.maxSeekBackTime$=new En(1/0);this.zeroTime$=new En(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:Nu.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=ft(r.name)??kp(r.video),n=r.bitrate/1e3,u={...r.video};if(!a)continue;let c={id:s,quality:a,bitrate:n,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),In(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(Mp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Pp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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(le(this.params.source.url,u))}return;default:return Vu(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:Nu.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Fu(this.videoState.stateChangeStarted$.pipe(js(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(js(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{L({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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(js(r=>r.map(({track:s})=>s)),_u(r=>!!r.length),wp()).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(Ip(),js(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(yp({zeroTime:this.zeroTime$.pipe(_u(In)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(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&&Uu(r),min:s&&Uu(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),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 Vu(r.to)}},t)).add(Fu(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ep(["init"])).pipe(Tp(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 Yi({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&&In(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}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==n){let c=e.find(({track:l})=>l.id===s)?.representation;Ou(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Ou(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),L({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(le(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Hu=Xi;import{filterChanged as em}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Qp,assertNonNullable as qp,debounce as zp,ErrorCategory as Ju,filter as Rn,filterChanged as Dn,fromEvent as Wp,isNonNullable as Zu,isNullable as Gp,map as Ln,merge as Ks,observableFrom as Cn,once as ec,Subscription as Yp,throttle as Kp}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Ap}from"@vkontakte/videoplayer-shared/evergreen";var ju=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?ft(s):void 0)??Ap({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Qu=({id:o,bitrate:e})=>({id:o,bitrate:e}),qu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e});var wn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Qs=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var ve=o=>o.type==="template";var qs=class{constructor(e,t){this.fov=e,this.orientation=t}};var zs=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 zu=`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 Wu=`#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 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 $p,now as Yi,once as Mp,Subscription as Rp,ValueSubject as yn,isNonNullable as Dp,safeStorage as Tn,filterChanged as Lp}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 Rp;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(Mp()).subscribe(t=>this.providerStartWatchingTimestamp=Yi())),this.subscription.add(this.currentStallDuration$.pipe(Lp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:s}=this.tuning;if($p(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,Dp(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 Cp,observeElementSize as Vp,Subscription as Op,ValueSubject as wn,noop as Np}from"@vkontakte/videoplayer-shared/evergreen";var za=class{constructor(){this.subscription=new Op;this.pipSize$=new wn(void 0);this.videoSize$=new wn(void 0);this.elementSize$=new wn(void 0);this.pictureInPictureWindowRemoveEventListener=Np}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Vp(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(Cp(({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 _p,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(_p(()=>{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 qp;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 Up(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;zp(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(Be(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(Hp(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$,jp(this.video,"progress")).pipe(xn(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(Wp(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(Qp(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?Ca:Ba,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 Hh,flattenObject as cs,fromEvent as Ht,getTraceSubscriptionMethod as Qh,getWindow as $r,interval as jh,isNonNullable as It,isNullable as Mr,map as Un,merge as Rr,now as zh,Subject as Et,Subscription as wc,SubscriptionRemovable as qh,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 Gp,merge as Yp,now as er,Subject as di,Subscription as Kp,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 Kp;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,Gp().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=Yp(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(),B={failed:k,requestStartedAt:g,requestEndedAt:_,duration:_-g};return k?(p.error("endRequest",li(B)),p.end(),null):(p.log("endRequest",li(B)),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 Jp,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=Xp(),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 Xp(){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}(?:-${
|
|
170
|
+
`;var di=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 qs(this.params.fov,this.params.orientation),this.cameraRotationManager=new zs(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(zu,this.gl.VERTEX_SHADER),i=this.createShader(Wu,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,u=t-r,c=e+i,l=t+r,d=e-i,p=t+r;return[s,a,n,u,c,l,d,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 Dp,now as Zi,once as Lp,Subscription as Cp,ValueSubject as kn,isNonNullable as Bp,safeStorage as Pn,filterChanged as Vp}from"@vkontakte/videoplayer-shared/evergreen";var tt=(o,e,t)=>t*e+(1-t)*o,xn=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Gu=(o,e,t,i)=>{let r=0,s=t,a=xn(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[s]>a?r++:r--,s=(o.length+s-1)%o.length;return Math.abs(r)===n};var Ws="stalls_manager_metrics",Mn="stalls_manager_abr_params",Yu="stalls_manager_default_tuning_abr_params",An=class{constructor(){this.isSeeked$=new kn(!1);this.isBuffering$=new kn(!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 Cp;this.severeStallOccurred$=new kn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(Mn):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Zi(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Zi()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Yu)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(Mn),this.setStoredData(Yu,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ws,"[]");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,u)=>n+u.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(Ws,[]),this.setStoredData(Mn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n}=this.tuning,u=a*Math.min(t/n,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>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(Pn.get(e)??t)}setStoredData(e,t){Pn.set(e,JSON.stringify(t))}removeStoredData(e){Pn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ws,"[]"),r=t/e,s=i.length?tt(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(Ws,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(Lp()).subscribe(t=>this.providerStartWatchingTimestamp=Zi())),this.subscription.add(this.currentStallDuration$.pipe(Vp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(Dp(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),l=Zi(),d=r&&this.currentStallsCount>=r,p=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&l-c>=i+n&&t>=i;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Bp(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Zi()-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}))}},Gs=An;import{combine as Op,map as Np,observeElementSize as _p,Subscription as Fp,ValueSubject as $n,noop as Up}from"@vkontakte/videoplayer-shared/evergreen";var Ys=class{constructor(){this.subscription=new Fp;this.pipSize$=new $n(void 0);this.videoSize$=new $n(void 0);this.elementSize$=new $n(void 0);this.pictureInPictureWindowRemoveEventListener=Up}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(_p(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(Op({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Np(({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 Ku,map as Hp,once as Xu}from"@vkontakte/videoplayer-shared/evergreen";var gt=({subscription:o,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,s=!1;o.add(e.volume.stateChangeStarted$.pipe(Hp(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),Ku(a=>!!a),Xu()).subscribe(()=>{r=performance.now(),s=!0})),o.add(i.playbackRateState$.pipe(Ku(()=>s),Xu()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var er=class{constructor(e){this.subscription=new Yp;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new Gs;this.elementSizeManager=new Ys;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 Qp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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;Gp(this.observableVideo)&&(this.observableVideo=we(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Ju.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,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(Rn(d=>!!d.length),ec()).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(Ln(d=>d.to.state!=="none"),Dn());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.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(Rn(Zu),ec()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ln(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(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}),s(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:d})=>{if(d==="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 b of p.audio){f.push(wn(b));let g=[];for(let S of b.representations){let I=Qu(S);g.push(I),this.audioTracksMap.set(I,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Qs(f));let b=[];for(let g of f.representations){let S=ju({...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 p.text)for(let b of f.representations){let g=qu(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Ks(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$,Wp(this.video,"progress")).pipe(Rn(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(n=n.pipe(Kp(u))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(d!=="manifest_ready"&&d!=="running"||p)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(I=>this.videoTracksMap.get(I)?.representation.id===f.id);Zu(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,h),b&&await this.player.switchRepresentation("audio",b.id,h))},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(Dn()).subscribe(d=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);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(wn(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(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(Ln(({to:d})=>d==="ready"),Dn());this.subscription.add(Ks(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Cn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Ks(c,this.player.state$.stateChangeEnded$,Cn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ks(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Cn(["init"])).pipe(zp(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?qi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?_s:Ns,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Os,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:k})=>k===n),c=s.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let d=[...this.videoStreamsMap.keys()].find(({id:k})=>k===l.id),p=d&&this.videoStreamsMap.get(d);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=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:k})=>k===g?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(u&&!a){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;(a||!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: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 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:b,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:Ju.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};import{ErrorCategory as tr}from"@vkontakte/videoplayer-shared/evergreen";var Xs=o=>{if(!o)return{id:"EmptyResponse",category:tr.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:tr.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:tr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:tr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:tr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as Pc,assertNonNullable as st,ErrorCategory as Ht,filter as qn,filterChanged as jh,flattenObject as fa,fromEvent as jt,getTraceSubscriptionMethod as Qh,getWindow as Lr,interval as qh,isNonNullable as It,isNullable as Cr,map as zn,merge as Br,now as zh,Subject as Et,Subscription as Mc,SubscriptionRemovable as Wh,ValueSubject as G}from"@vkontakte/videoplayer-shared/evergreen";var St=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var Js=o=>{let e=o.get("X-Delivery-Type"),t=o.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ir,assertNever as tc,ErrorCategory as pi,flattenObject as hi,fromEvent as ic,getWindow as rr,merge as Xp,now as Nt,Subject as mi,Subscription as Jp,ValueSubject as sr}from"@vkontakte/videoplayer-shared/evergreen";var Fe=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var Zs=o=>{let e=new URL(o);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ta=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new mi;this.manifestReceived=new mi;this.firstBytesRequested=new mi;this.firstBytesReceived=new mi;this.lastConnectionType$=new sr(void 0);this.lastConnectionReused$=new sr(void 0);this.lastRequestFirstBytes$=new sr(void 0);this.lastConnectionMetrics$=new sr(void 0);this.lastDownloadMetrics$=new sr(void 0);this.recoverableError$=new mi;this.error$=new mi;this.abortAllController=new AbortController;this.subscription=new Jp;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=ir(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Zs(i)),this.trackRequestStart(i,performance.now());let r=Nt();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ea);if(s){let a=Nt();t.log("success",hi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let n=s.headers.get("content-length"),u=0;n&&(u=parseInt(n,10));let c=await s.text();if((!n||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let l=a-r,p=u/(l/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",hi({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=ir(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:u=!1,bufferOptimisation:c=!1}={}){let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(l,rr().location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),l=T.toString();break}default:tc(t)}this.requestQuic&&(l=St(l));let h=this.abortAllController.signal,m;if(a){let T=new AbortController;if(m=Xp(ic(this.abortAllController.signal,"abort"),ic(a,"abort")).subscribe(()=>{try{T.abort()}catch(y){ea(y)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(y){ea(y)}h=T.signal}let f=0,b=Nt();p.log("startRequest",hi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested.next();let g=yield this.doFetch(l,{priority:s,headers:d,signal:h}),S=Nt();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){m?.unsubscribe();let T=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){m?.unsubscribe();let T=Nt(),y={requestStartedAt:b,requestEndedAt:T,duration:T-b};return p.log("endRequest",hi(y)),p.end(),g.arrayBuffer()}let I=g.body;if(n){let T;[I,T]=g.body.tee(),this.throughputEstimator?.trackStream(T,u)}let v=I.getReader(),x,A=parseInt(g.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,ea(T)},E=ir(h,async function*({done:T,value:y}){if(f===0&&(this.lastRequestFirstBytes$.next(Nt()-b),this.firstBytesReceived.next()),h.aborted){m?.unsubscribe();return}if(!T&&y){if(c&&x)R.set(y,f),f+=y.byteLength;else{let V=new Uint8Array(R.length+y.length);V.set(R),V.set(y,R.length),R=V,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 _=Nt(),C={failed:k,requestStartedAt:b,requestEndedAt:_,duration:_-b};if(k)return p.error("endRequest",hi(C)),p.end(),null;if(f>0){let T=_-b,V=f/(T/1e3)*8/1024,M={bytes:f,speed:V,url:e};this.lastDownloadMetrics$.next(M)}return p.log("endRequest",hi(C)),p.end(),R.buffer}.bind(this));this.fetchByteRangeRepresentation=ir(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,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(a=Math.min(c,r),n=Math.max(l,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 p=new DataView(d,r-a,s-a+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(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,h,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=ir(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,rr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Js(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(rr()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in rr().navigator))return"unknown";let e=rr().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,a=new URL(i.url),n=a.origin+a.pathname;if(s===n&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch{this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:pi.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}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:tc(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),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:pi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:pi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:pi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:pi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:pi.FATAL,httpCode:i.status,UVBackendErrorCode:r})}}},ea=o=>{if(!Fe(o))throw o};var Vn=o=>{let e=o.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as eh,isNullable as ac}from"@vkontakte/videoplayer-shared/evergreen";var rc=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var sc=o=>{try{let e=Zp(),t=o.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(u=>{r[u[0]]=u.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 u=a[n];(typeof u>"u"||u==="")&&delete a[n]}),a}return null}catch{return null}};function Zp(){let o="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",l=`^(?:(?<langtag>${`
|
|
171
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${o})?|[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(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),B=E.getAttribute("mimeType")??"",T=E.getAttribute("codecs")??"",y=E.getAttribute("contentType")??B?.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:B,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")??B,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,Ml=_e/Ne*1e3;for(let sa=0;sa<Dt+1;sa++){let Rl=Ue(Re,{...Xe,segmentNumber:ra.toString(10),segmentTime:(_e+sa*je).toString(10)}),Eo=(Ml??0)+sa*Os,Dl=Eo+Os;ra++,Qe.push({time:{from:Eo,to:Dl},url:Rl})}_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(Jp(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 $l={time:{from:Ai,to:1/0},url:Xt};Yt={type:"template",baseUrl:ae,segmentTemplateUrl:Re,initUrl:Rt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:$l,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 ih().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 rh().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",""),ih=()=>["av1","vp9","hev1","avc1"],rh=()=>["opus","mp4a"];import{abortable as On,assertNonNullable as Ke,ErrorCategory as wh,fromEvent as xh,getExponentialDelay as kh,getWindow as mc,isHigher as Ph,isNonNullable as ee,isNullable as ne,once as Ah,Subject as $h,Subscription as Mh,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 ah}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:ah(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 nh={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=nh[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 uh=new TextDecoder("ascii"),ch=n=>uh.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",lh=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})},dh=(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)},ph=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},hh=n=>{let t=new it().parse(n);return new vt(t).find("sidx")?.timescale},mh=(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},fh=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:ch,parseInit:fh,getIndexRange:()=>{},parseSegments:lh,parseFeedableSegmentChunk:dh,getChunkEndTime:mh,getServerLatencyTimestamps:ph,getTimescaleFromIndex:hh};import{assertNonNullable as Ln,isNonNullable as cc,isNullable as gh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as bh}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:bh(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],Sh=[231,22612,22743,167,171,163,160,175],vh=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}}}},yh=n=>{if(gh(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Th=(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}}})},Ih=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):Sh.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:vh,getIndexRange:yh,parseSegments:Th,parseFeedableSegmentChunk:Ih};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 Eh}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)??Eh({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}),Bn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Cn=({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 $h;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 Mh;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=kh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=mc();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(xh(i,"online").pipe(Ah()).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)&&Ph(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:wh.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 Rh,isNonNullable as Dh,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:Rh.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)):Dh(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 Lh,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:Lh.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 Ch,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:Ch.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 Nh,fromEvent as _h,isNullable as bi,Subject as Fh,Subscription as Uh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Vh,ErrorCategory as vc,Subject as yc}from"@vkontakte/videoplayer-shared/evergreen";var Oh=18,Tc=!1;try{Tc=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=Oh}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:Vh(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 Fh;this.subscription=new Uh;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(_h(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Nh.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 Wh=["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 qh;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(...Wh.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=jh(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=zh(),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)),Hh()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Fn(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=Qh(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 Gh,ErrorCategory as Yh,filter as Hn,filterChanged as Kh,fromEvent as Xh,isNonNullable as Jh,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(Xh(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=Gh({allBuffersFull:e,someBufferEnded:t}).pipe(Kh(),Qn(({allBuffersFull:a,someBufferEnded:s})=>a&&s),Hn(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:Yh.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Dr(this.forceEnded$,i).pipe(Hn(a=>Jh(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(Zh()).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 xm,assertNonNullable as km,combine as Pm,debounce as Am,ErrorCategory as Cc,filter as eo,filterChanged as Ur,fromEvent as $m,isNonNullable as Vc,isNullable as Mm,map as Hr,merge as Qr,observableFrom as Is,once as Oc,Subscription as Rm,throttle as Dm}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 Ce,filter as vs,filterChanged as Nr,flattenObject as _r,fromEvent as nt,getTraceSubscriptionMethod as hm,interval as Xn,isNonNullable as Fr,isNullable as Lc,map as Ii,merge as zt,now as Jn,Subject as ot,Subscription as Bc,SubscriptionRemovable as mm,tap as fm,throttle as bm,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as em,ErrorCategory as kc,Subject as Pc}from"@vkontakte/videoplayer-shared/evergreen";var tm=18,Ac=!1;try{Ac=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=tm}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:em(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 im,isNonNullable as kt,isNullable as ie,now as hs,once as rm,Subject as am,Subscription as sm,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 am;this.gaps=[];this.subscription=new sm;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)&&im(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(rm()).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 Br,assertNever as Mc,fromEvent as Rc,merge as nm,now as Cr,Subject as Si,ValueSubject as Gn,flattenObject as vi,ErrorCategory as Vr,SubscriptionRemovable as om}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 om;this.fetchManifest=Br(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=Br(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=nm(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=Cr();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=Cr();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=Cr(),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)},_=Br(m,async function*({done:y,value:O}){if(g===0&&(this.lastRequestFirstBytes$.next(Cr()-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 B=Cr(),T={failed:D,requestStartedAt:b,requestEndedAt:B,duration:B-b};return D?(h.error("endRequest",vi(T)),h.end(),null):(h.log("endRequest",vi(T)),h.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=Br(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=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,{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 um,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)&&(um(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 cm,ValueSubject as lm}from"@vkontakte/videoplayer-shared/evergreen";var Or=class n{constructor(e,t){this.currentRepresentation$=new lm(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(!cm(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 gm=["timeupdate","progress","play","seeked","stalled","waiting"],Sm=["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 Bc;this.subscriptionRemovable=new mm;this.representationSubscription=new Bc;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:Ce.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:Ce.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:Ce.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:Ce.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:Ce.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(...Sm.map(l=>nt(this.element,l))).pipe(Ii(l=>this.element?Tt(this.element.buffered,this.element.currentTime*1e3):0),Nr(),fm(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(bm(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:Ce.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:Ce.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:Ce.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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:Ce.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new 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(...gm.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ce.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:Ce.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:Ce.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){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=hm(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 vm,map as ym,observeElementSize as Tm,Subscription as Im,ValueSubject as Zn,noop as Em}from"@vkontakte/videoplayer-shared/evergreen";var Ts=class{constructor(){this.subscription=new Im;this.pipSize$=new Zn(void 0);this.videoSize$=new Zn(void 0);this.elementSize$=new Zn(void 0);this.pictureInPictureWindowRemoveEventListener=Em}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Tm(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(vm({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ym(({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 Rm;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 xm(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;Mm(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:Cc.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(Be(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(km(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let g of p.audio){f.push(Bn(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(Cn(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$,$m(this.video,"progress")).pipe(eo(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(Dm(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(Pm({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(Cn(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(Bn(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(Am(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?Ca:Ba,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:Cc.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 Lm}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=>Lm(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 jm,combine as zm,debounce as qm,ErrorCategory as xs,filter as Wm,filterChanged as Gm,isNonNullable as zc,isNullable as ks,map as qc,merge as Ym,observableFrom as Km,Subscription as Xm,ValueSubject as no,VideoQuality as Jm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Bm,getExponentialDelay as Cm}from"@vkontakte/videoplayer-shared/evergreen";var Vm=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},Om=(n,e)=>{let t=n.split(`
|
|
178
|
-
`),i=[],r=[];for(let
|
|
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(_m(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:Qm.WTF,thrown:t,message:e})}};var qr=class{constructor(e){this.subscription=new Xm;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 jm(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Jm.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(Be(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(Gm(),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(zm({startTime:this.manifestStartTime$.pipe(Wm(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=Ym(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Km(["init"])).pipe(qm(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 Zm,debounce as ef,ErrorCategory as oo,fromEvent as uo,isNonNullable as tf,isNullable as rf,map as Wc,merge as Gc,observableFrom as Yc,Subscription as af,ValueSubject as Kc,VideoQuality as sf}from"@vkontakte/videoplayer-shared/evergreen";var Wr=class{constructor(e){this.subscription=new af;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 Zm(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:sf.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&&tf(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(ef(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(rf(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 nf,assertNonNullable as Xc,debounce as of,ErrorCategory as Jc,isHigherOrEqual as uf,isLowerOrEqual as cf,isNonNullable as lf,merge as df,observableFrom as pf,Subscription as hf,map as mf}from"@vkontakte/videoplayer-shared/evergreen";var Gr=class{constructor(e){this.subscription=new hf;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 nf(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(mf(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(Be(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&&lf(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=df(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,pf(["init"])).pipe(of(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?cf(r,e.max):!0,u=e.min?uf(r,e.min):!0;o&&u||i(e)}};import{assertNever as el,debounce as Sf,merge as tl,observableFrom as vf,Subscription as yf,map as il,ValueSubject as Tf,ErrorCategory as lo,VideoQuality as If}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as ff}from"@vkontakte/videoplayer-shared/evergreen";var Zc=["stun:videostun.mycdn.me:80"],bf=1e3,gf=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:ff.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),bf)}normalizeOptions(e={}){let t={stunServerList:Zc,maxRetryNumber:gf,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 Tf(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 yf,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(Be(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$,vf(["init"])).pipe(Sf(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:If.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 $f,map as Mf,merge as Rf,once as Df,Subject as J,Subscription as ll,ValueSubject as C,flattenObject as po,devNull as Lf,getWindow as Bf}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Ef,map as rl,Subscription as wf,Subject as xf}from"@vkontakte/videoplayer-shared/evergreen";var al=n=>new Ef(e=>{let t=new wf,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 xf,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 kf,Subscription as Pf,combine as Af,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 Pf;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(Af({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:kf.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var Cf={chunkDuration:5e3,maxParallelRequests:5},Xr=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new J;this.noAvailableProvidersError$=new J;this.volumeMultiplierError$=new J;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableVideoCodecs$:new C([]),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),availableAudioCodecs$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),currentNativeBuffer$:new C(void 0),isBuffering$:new C(!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 C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),severeStallOccurred$:new J,availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C(""),getCurrentTime$:new C(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($f(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:{...Cf,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 Ci({...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(Rf(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(Mf(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"),Df()).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
|
-
`,
|
|
181
|
-
`+
|
|
177
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var nc=o=>{if(!o?.startsWith("P"))return;let e=(a,n)=>{let u=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(u)?0:u)*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(o),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ue=(o,e)=>{let t=o;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,u)=>ac(s)?n:ac(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sa=(o,e)=>{let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),n=a.at(0)??"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),l=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:c?new Date(c).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],v=I.reduce((D,E)=>({...D,[E.id]:E.children}),{}),x=I.reduce((D,E)=>({...D,[E.id]:E.getAttribute("duration")}),{});S?g=nc(S):Object.values(x).filter(D=>D).length&&!u?g=Object.values(x).reduce((D,E)=>D+(nc(E)??0),0):f&&(g=parseInt(f,10));let A=0,R=s.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],V=E.getAttribute("profiles")?.split(",")??[],M=sc(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:M.language,isDefault:te==="main",label:F,codecs:T,hdr:ue==="video"&&Vn(T),mime:C,representations:[]};for(let U of W){let N=U.getAttribute("lang")??void 0,de=F??E.getAttribute("label")??U.getAttribute("label")??void 0,he=U.querySelector("BaseURL")?.textContent?.trim()??"",se=new URL(he||n,e).toString(),$e=U.getAttribute("mimeType")??C,dt=U.getAttribute("codecs")??T??"",Ve;if(y==="text"){let ke=U.getAttribute("id")||"",lt=M.privateuse?.includes("x-auto")||ke.includes("_auto"),Oe=U.querySelector("SegmentTemplate");if(Oe){let Ai={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},is=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,rs=parseInt(Oe.getAttribute("startNumber")??"",10)??1,Yt=parseInt(Oe.getAttribute("timescale")??"",10),Ha=Oe.querySelectorAll("SegmentTimeline S")??[],Kt=Oe.getAttribute("media");if(!Kt)continue;let ss=[],as=0,ns="",Xt=0,$i=rs,me=0;for(let Ne of Ha){let $t=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=$t/Yt*1e3,Jt=me/Yt*1e3;for(let je=0;je<Re+1;je++){let ht=Ue(Kt,{...Ai,segmentNumber:$i.toString(10),segmentTime:(me+je*$t).toString(10)}),Zt=(Jt??0)+je*Rt,Di=Zt+Rt;$i++,ss.push({time:{from:Zt,to:Di},url:ht})}me+=(Re+1)*$t,as+=(Re+1)*Rt}Xt=me/Yt*1e3,ns=Ue(Kt,{...Ai,segmentNumber:$i.toString(10),segmentTime:me.toString(10)});let Ri={time:{from:Xt,to:1/0},url:ns},Xe={type:"template",baseUrl:se,segmentTemplateUrl:Kt,initUrl:"",totalSegmentsDurationMs:as,segments:ss,nextSegmentBeyondManifest:Ri,timescale:Yt};Ve={id:ke,kind:"text",segmentReference:Xe,profiles:[],duration:g,bitrate:is,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else Ve={id:ke,isAuto:lt,kind:"text",url:se}}else{let ke=U.getAttribute("contentType")??$e?.split("/")[0]??y,lt=E.getAttribute("profiles")?.split(",")??[],Oe=parseInt(U.getAttribute("width")??"",10),Ai=parseInt(U.getAttribute("height")??"",10),is=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,rs=U.getAttribute("frameRate")??"",Yt=U.getAttribute("quality")??void 0,Ha=rs?rc(rs):void 0,Kt=U.getAttribute("id")??"id"+(A++).toString(10),ss=ke==="video"?`${Ai}p`:ke==="audio"?`${is}Kbps`:dt,as=`${Kt}@${ss}`,ns=[...R,...V,...lt],Xt,$i=U.querySelector("SegmentBase"),me=U.querySelector("SegmentTemplate")??Z;if($i){let Xe=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,$t]=Xe.split("-").map(ht=>parseInt(ht,10)),Re={from:Ne,to:$t},pt=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rt,Jt]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],je=pt?{from:Rt,to:Jt}:void 0;Xt={type:"byteRange",url:se,initRange:Re,indexRange:je}}else if(me){let Xe={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Ne=parseInt(me.getAttribute("timescale")??"",10),$t=me.getAttribute("initialization")??"",Re=me.getAttribute("media"),pt=parseInt(me.getAttribute("startNumber")??"",10)??1,Rt=Ue($t,Xe);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let Jt=me.querySelectorAll("SegmentTimeline S")??[],je=[],ht=0,Zt="",Di=0;if(Jt.length){let os=pt,_e=0;for(let ei of Jt){let Qe=parseInt(ei.getAttribute("d")??"",10),Dt=parseInt(ei.getAttribute("r")??"",10)||0,us=parseInt(ei.getAttribute("t")??"",10);_e=Number.isFinite(us)?us:_e;let ja=Qe/Ne*1e3,Cd=_e/Ne*1e3;for(let cs=0;cs<Dt+1;cs++){let Bd=Ue(Re,{...Xe,segmentNumber:os.toString(10),segmentTime:(_e+cs*Qe).toString(10)}),Po=(Cd??0)+cs*ja,Vd=Po+ja;os++,je.push({time:{from:Po,to:Vd},url:Bd})}_e+=(Dt+1)*Qe,ht+=(Dt+1)*ja}Di=_e/Ne*1e3,Zt=Ue(Re,{...Xe,segmentNumber:os.toString(10),segmentTime:_e.toString(10)})}else if(eh(g)){let _e=parseInt(me.getAttribute("duration")??"",10)/Ne*1e3,ei=Math.ceil(g/_e),Qe=0;for(let Dt=1;Dt<ei;Dt++){let us=Ue(Re,{...Xe,segmentNumber:Dt.toString(10),segmentTime:Qe.toString(10)});je.push({time:{from:Qe,to:Qe+_e},url:us}),Qe+=_e}Di=Qe,Zt=Ue(Re,{...Xe,segmentNumber:ei.toString(10),segmentTime:Qe.toString(10)})}let Ld={time:{from:Di,to:1/0},url:Zt};Xt={type:"template",baseUrl:se,segmentTemplateUrl:Re,initUrl:Rt,totalSegmentsDurationMs:ht,segments:je,nextSegmentBeyondManifest:Ld,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!$e)continue;let Ri={video:"video",audio:"audio",text:"text"}[ke];if(!Ri)continue;ue||=Ri,Ve={id:as,kind:Ri,segmentReference:Xt,profiles:ns,duration:g,bitrate:is,mime:$e,codecs:dt,width:Oe,height:Ai,fps:Ha,quality:Yt}}ce.language||=N,ce.label||=de,ce.mime||=$e,ce.codecs||=dt,ce.hdr||=ue==="video"&&Vn(dt),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 de=ce.representations.find($e=>$e.id===N.id);if(!de)continue;let he=de.segmentReference,se=N.segmentReference;se.segments.push(...he.segments),se.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ue].push(ce)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as oa}from"@vkontakte/videoplayer-shared/evergreen";var aa=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(aa||{});var na=o=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(o){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:oa(o)}},oc=({webmCodec:o,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...na(o),"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",...na(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...na(o),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...na(o),...s,"HLS","HLS_ONDEMAND"];default:oa(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:oa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},uc=({androidPreferredFormat:o,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:oa(o)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?n=a:u?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"]},On=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ua=o=>{if(o.size===0)return;if(o.size===1)return o.values().next().value.split(".").at(0);for(let t of o){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return o.values().next().value.split(".").at(0)},ca=o=>{let e=o.map(i=>fi(i)),{codecs:t}=$.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})},da=o=>{let e=o.map(i=>fi(i)),{codecs:t}=$.video;return sh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},fi=o=>o.split(".")[0].replace("0",""),rh=()=>["av1","vp9","hev1","avc1"],sh=()=>["opus","mp4a"];import{abortable as Hn,assertNonNullable as Ke,ErrorCategory as xh,fromEvent as kh,getExponentialDelay as Ph,getWindow as Sc,isHigher as Mh,isNonNullable as ee,isNullable as ne,once as Ah,Subject as $h,Subscription as Rh,ValueSubject as $r}from"@vkontakte/videoplayer-shared/evergreen";var la=o=>o.valid,j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var bi=class extends j{};import{assertNever as ah}from"@vkontakte/videoplayer-shared/evergreen";var ar=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:ah(e)}}};var nr=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var or=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var K=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var ur=class extends K{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var cr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var dr=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var _t=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,n=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:u,SAPDeltaTime:c})}}}};var lr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends K{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var mr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var fr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var br=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gr=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var vr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var yr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Tr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ir=class extends K{constructor(e,t){super(e,t),this.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 Er=class extends K{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var wr=class extends K{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var kr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Pr=class extends j{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var oh={ftyp:nr,moov:or,mvhd:ur,moof:cr,mdat:dr,sidx:_t,trak:lr,mdia:br,mfhd:yr,tkhd:gr,traf:Tr,tfhd:Ir,tfdt:Er,trun:wr,minf:Sr,sv3d:pr,st3d:hr,prhd:mr,proj:vr,equi:fr,uuid:ar,stbl:xr,stsd:kr,avc1:Pr,unknown:bi},it=class o{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!la(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=oh[e];return i?new i(t,new o):new bi(t,new o)}};var vt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{la(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"),dh=o=>ch.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",lh=o=>{let e=new _t(o,new it),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},ph=(o,e)=>{let i=new it().parse(o),r=new vt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],u=a[a.length-1],c=n.source.byteOffset,d=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,c,d)},hh=o=>{let t=new it().parse(o),i=new vt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},mh=o=>{let t=new it().parse(o);return new vt(t).find("sidx")?.timescale},fh=(o,e)=>{let i=new it().parse(o),s=new vt(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"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=a.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},bh=o=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new it().parse(o),r=new vt(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 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},cc={validateData:dh,parseInit:bh,getIndexRange:()=>{},parseSegments:lh,parseFeedableSegmentChunk:ph,getChunkEndTime:fh,getServerLatencyTimestamps:hh,getTimescaleFromIndex:mh};import{assertNonNullable as Nn,isNonNullable as hc,isNullable as Sh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as gh}from"@vkontakte/videoplayer-shared/evergreen";var dc={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"}},lc=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Mr(o,t),r=i in dc,s=r?dc[i].type:"binary",a=o.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 u=new DataView(o.buffer,o.byteOffset+t+1,n-1),c=a&255>>n,l=Mr(u),d=c*2**((n-1)*8)+l,p=t+n,h;return p+d>o.byteLength?h=new DataView(o.buffer,o.byteOffset+p):h=new DataView(o.buffer,o.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Mr=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return Mr(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:gh(e)}},Ft=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=lc(i);if(!e(r))return;r.type==="master"&&Ft(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},pc=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=lc(o);return Ft(r.value,({tag:s,type:a,value:n})=>(s===17143?e=He(n,a):s===17026?t=He(n,a):s===17029&&(i=He(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var mc=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],vh=[231,22612,22743,167,171,163,160,175],yh=o=>{let e,t,i,r,s=!1,a=!1,n=!1,u,c,l=!1,d=0;return Ft(o,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=He(m,h);c=Mr(b)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?s=!0:p===290298740?a=!0:p===2807729?i=He(m,h):p===17545?r=He(m,h):p===21420&&c===475249515?u=He(m,h):p===374648427?Ft(m,({tag:b,type:g,value:S})=>b===30321?(l=He(S,g)===1,!1):!0):s&&a&&mc.includes(p)&&(n=!0),!n}),Nn(e,"Failed to parse webm Segment start"),Nn(t,"Failed to parse webm Segment end"),Nn(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:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Th=o=>{if(Sh(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ih=(o,e)=>{let t=!1,i=!1,r=n=>hc(n.time)&&hc(n.position),s=[],a;return Ft(o,({tag:n,type:u,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=He(c,u));break;case 183:break;case 241:a&&(a.position=He(c,u));break;default:t&&mc.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,u)=>{let{time:c,position:l}=n,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Eh=o=>{let e=0,t=!1;try{Ft(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):vh.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},fc={validateData:pc,parseInit:yh,getIndexRange:Th,parseSegments:Ih,parseFeedableSegmentChunk:Eh};var Ut=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fc;case"mp4":return cc}}throw new ReferenceError(`Unsupported mime type ${o}`)};import{videoSizeToQuality as wh}from"@vkontakte/videoplayer-shared/evergreen";var yt=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?ft(s):void 0)??wh({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Ar=({id:o,bitrate:e})=>({id:o,bitrate:e}),bc=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),gc=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),_n=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Fn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Un=o=>"url"in o,Me=o=>o.type==="template";var gi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,manifest:n}){this.error$=new $h;this.playingRepresentation$=new $r(void 0);this.playingRepresentationInit$=new $r(void 0);this.currentSegmentLength$=new $r(0);this.onLastSegment$=new $r(!1);this.fullyBuffered$=new $r(!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=Hn(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=Ut(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);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(s)}.bind(this));this.switchTo=Hn(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 s=this.initData.get(r.id),a=this.segments.get(r.id);Ke(s,"No init buffer for switching representation"),Ke(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,u=d=>d.segment.networkStatus!=="downloaded"||d.segment.time.to-n>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=d=>{let p=this.representations.get(d.representationId);return Ke(p,"No itemRepresentation for previous track before switch"),d.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},l=d=>t?u(d)&&c(d):u(d);this.bufferPlaybackQueue.filter(l).forEach(d=>d.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(d=>!l(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=Hn(this.downloadAbortController.signal,async function*(){let e=Ph(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=Sc();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(kh(i,"online").pipe(Ah()).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(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(s=>s.time.from<=e&&s.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=Sc();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),s=yt(t);i=ee(r)&&ee(s)&&Mh(s.quality,r.quality)}else if(this.kind==="audio"){let r=Ar(e),s=Ar(t);i=ee(r?.bitrate)&&ee(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():ee(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:u}=await s??{};if(this.initDataPromises.delete(e.id),ne(n)||ne(u))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,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(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;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,a):await this.appendSegmentPartially(i,a)),ee(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,a),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(a=>e>=a.time.from&&e<a.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 s=this.selectItemsToLoad();await this.loadItems(s,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,s;ee(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:u}=t[r].time;s-=u-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 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),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||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 s=this.currentVirtualBufferSize-t+i;for(let a of this.segments.values())for(let n of a)ee(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())ee(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===n)&&!this.downloadingBufferItems.find(u=>u.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 Dh,isNonNullable as Lh,isNullable as vc,now as yc}from"@vkontakte/videoplayer-shared/evergreen";var pa=class extends gi{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=yc(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Fe(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(ve(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,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=yc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:u,signal:i,globalFrom:s?s.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:s,signal:a}){let n=this.representations.get(i);if(!(!this.downloadingBufferItems.length||vc(n)||vc(r)||a.aborted))for(let u of e){let{segment:c}=u,l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<s,m=d<=s;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+l,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-l),await this.onDownloadItem(u)):Lh(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-l),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+l,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 jn,now as Tc}from"@vkontakte/videoplayer-shared/evergreen";var Si=class extends gi{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=Tc(),jn(n))return;let u=e[0],c=new DataView(n);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(n){this.abortDownloadingItems(),Fe(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=Tc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,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:s}){let a=e[0],{segment:n}=a,u=this.representations.get(i);!this.downloadingBufferItems.length||jn(u)||jn(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(!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 Ic}from"@vkontakte/videoplayer-shared/evergreen";var ha=class extends Si{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Ic(0);this.currentLowLatencySegmentLength$=new Ic(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(rt(r)||!ve(r.segmentReference))return;let s=r.segmentReference.segments.map(l=>({...l,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],u=n.at(-1)?.time.to??0,c=s?.findIndex(l=>u>=l.time.from+a&&u<=l.time.to+a);if(c===-1){let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=s.slice(c+1);this.segments.set(r.id,[...n,...l])}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(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(rt(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(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: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(rt(t.segment.data)||rt(r)||!ve(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(!ve(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),l=Ue(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:l,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:u,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),rt(u)||rt(c))return;n&&this.parsedInitData.set(t.id,n);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,d),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:Vh.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 Rr=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new ha(e,t,i,r):ve(i[0].segmentReference)?new Si(e,t,i,r):new pa(e,t,i,r)}};import{ErrorCategory as _h,fromEvent as Fh,isNullable as vi,Subject as Uh,Subscription as Hh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Oh,ErrorCategory as Ec,Subject as wc}from"@vkontakte/videoplayer-shared/evergreen";var Nh=18,xc=!1;try{xc=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=Nh}catch(o){console.error(o)}var Qn=class{constructor(e,t=!1){this.bufferFull$=new wc;this.error$=new wc;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:Ec.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)};xc&&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:Ec.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)}}},kc=Qn;var Tt=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,s=o.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Dr=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 kc(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(vi(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(){!vi(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(vi(this.sourceBuffer)||!Y(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 vi(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||vi(e)?0:Tt(this.sourceBuffer.buffered,e)}async abortBuffer(e){return vi(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 ma=(o,e)=>{o.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{let a=e.find(([n])=>n===`${s}p`)?.[1];return a&&Number.isInteger(a)&&r&&Number.isInteger(r)?r<=a:!0});t.representations=i})};var Gh=["timeupdate","progress","play","seeked","stalled","waiting"],Ac=["timeupdate","progress","loadeddata","playing","seeked"],ba=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new Mc;this.subscriptionRemovable=new Wh;this.representationSubscription=new Mc;this.forceEnded$=new Et;this.destroyController=new AbortController;this.state$=new O("none");this.currentVideoRepresentation$=new G(void 0);this.currentVideoRepresentationInit$=new G(void 0);this.currentAudioRepresentation$=new G(void 0);this.currentVideoSegmentLength$=new G(0);this.currentAudioSegmentLength$=new G(0);this.error$=new Et;this.manifestRequested=new Et;this.manifestReceived=new Et;this.firstBytesRequested=new Et;this.firstBytesReceived=new Et;this.lastConnectionType$=new G(void 0);this.lastConnectionReused$=new G(void 0);this.lastRequestFirstBytes$=new G(void 0);this.lastConnectionMetrics$=new G(void 0);this.lastDownloadMetrics$=new G(void 0);this.currentLiveTextRepresentation$=new G(null);this.isLive$=new G(!1);this.isActiveLive$=new G(!1);this.isLowLatency$=new G(!1);this.liveDuration$=new G(0);this.liveSeekableDuration$=new G(0);this.liveAvailabilityStartTime$=new G(0);this.liveStreamStatus$=new G(void 0);this.currentBuffer$=new G({from:0,to:0});this.bufferLength$=new G(0);this.nativeBufferLength$=new G(0);this.liveLatency$=new G(void 0);this.liveLoadBufferLength$=new G(0);this.livePositionFromPlayer$=new G(0);this.currentStallDuration$=new G(0);this.videoLastDataObtainedTimestamp$=new G(0);this.fetcherRecoverableError$=new Et;this.fetcherError$=new Et;this.initRepresentations=Pc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",fa({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(),st(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=Pc(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Cr(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ht.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 ta({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.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:Ht.PARSER,message:"No playable video representations"})}initBuffer(){st(this.element),this.state$.setState("running"),this.subscription.add(Br(...Gh.map(t=>jt(this.element,t)),jt(Lr(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Ht.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Br(...e.map(t=>jt(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(jt(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=qh(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Ht.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){st(this.element),st(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",fa({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&&Lr().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(Cr(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(){st(this.element),st(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",fa(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=zh(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,l=It(this.videoBufferManager)&&u<s&&r-a>i,d=It(this.audioBufferManager)&&c<s&&r-n>i;return(l||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Cr(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",fa(i)),i}parseManifest(e){try{return sa(e??"",this.manifestUrlString)}catch(t){let i=Xs(e)??{id:"ManifestParsing",category:Ht.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,u,c)=>!!(this.element?.canPlayType?.(u)&&Pe()?.isTypeSupported?.(`${u}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p));t[n]=c;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:p})=>p);n==="audio"&&(s=da(d),l=s[0]),n==="video"&&(r=ca(d),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=r[0]),l&&(t[n]=c.filter(({codecs:p})=>fi(p)===l))}else{let d=new Set(c.map(({codecs:p})=>p));l=ua(d),l&&(t[n]=c.filter(({codecs:p})=>p.startsWith(l)))}if(n==="video"){let d=this.tuning.preferHDR,p=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&d&&p?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&ma(t,m)}}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){st(this.manifest),st(this.element);let s=c=>{this.representationSubscription.add(jt(c,"error").pipe(qn(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:Ht.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=ys();let a=Lr().document,n=a.createElement("source");if(s(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ti())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 u=this.manifest.streams.video.reduce((c,l)=>[...c,...l.representations],[]);if(this.videoNativeBufferManager=new Dr(this.source),this.videoBufferManager=Rr.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],It(i)){this.audioNativeBufferManager=new Dr(this.source);let c=this.manifest.streams.audio.reduce((l,d)=>[...l,...d.representations],[]);this.audioBufferManager=Rr.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=Lr().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Ht.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&&Lr().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(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add(Br(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),st(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(Br(...Ac.map(e=>jt(this.element,e))).pipe(zn(e=>this.videoBufferManager?.getPlaybackBufferState()),qn(It),zn(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Br(...Ac.map(e=>jt(this.element,e))).pipe(zn(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),jh()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(qn(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=Qh(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Cr(this.element)||Cr(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 ga,combine as Yh,ErrorCategory as Kh,filter as Wn,filterChanged as Xh,fromEvent as Jh,isNonNullable as Zh,map as Gn,merge as Vr}from"@vkontakte/videoplayer-shared/evergreen";var Sa=class extends ba{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){ga(this.manifest),ga(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){ga(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){ga(this.element);let e=Vr(Jh(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(Wn(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Vr(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Vr(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Gn(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=Vr(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Gn(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=Yh({allBuffersFull:e,someBufferEnded:t}).pipe(Xh(),Gn(({allBuffersFull:s,someBufferEnded:a})=>s&&a),Wn(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:Kh.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(Vr(this.forceEnded$,i).pipe(Wn(s=>Zh(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var yi=class extends er{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(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:u}]=a,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(n),e.currentVideoStream$.next(Qs(u));let l=this.player.calculateDurationFromSegments();l&&this.params.output.duration$.next(l/1e3)},r))}getPlayer(){return new Sa({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 Mm,debounce as Am,ErrorCategory as _c,filter as so,filterChanged as qr,fromEvent as $m,isNonNullable as Fc,isNullable as Rm,map as zr,merge as Wr,observableFrom as Ma,once as Uc,Subscription as Dm,throttle as Lm}from"@vkontakte/videoplayer-shared/evergreen";var wt=(o,e,t=0)=>{for(let i=0;i<o.length;i++)if(o.start(i)*1e3-t<=e&&o.end(i)*1e3+t>e)return!0;return!1};import{abortable as eo,assertNonNullable as wi,combine as xi,ErrorCategory as Be,filter as xa,filterChanged as Hr,flattenObject as jr,fromEvent as nt,getTraceSubscriptionMethod as mm,interval as to,isNonNullable as Qr,isNullable as Oc,map as ki,merge as Wt,now as io,Subject as ot,Subscription as Nc,SubscriptionRemovable as fm,tap as bm,throttle as gm,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as tm,ErrorCategory as $c,Subject as Rc}from"@vkontakte/videoplayer-shared/evergreen";var im=18,Dc=!1;try{Dc=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=im}catch(o){console.error(o)}var Yn=class{constructor(e,t=!1){this.bufferFull$=new Rc;this.error$=new Rc;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:$c.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)};Dc&&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:$c.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)}}},Lc=Yn;var Kn=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as xt,assertNonNullable as ye,ErrorCategory as at,fromEvent as Xn,getExponentialDelay as Jn,isHigher as rm,isNonNullable as kt,isNullable as ie,now as va,once as sm,Subject as am,Subscription as nm,ValueSubject as Qt}from"@vkontakte/videoplayer-shared/evergreen";var Or=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,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 am;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 Lc(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Xn(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,u=this.mediaSource.readyState;u!=="open"&&(n={id:`SegmentEjection_source_${u}`,category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(Xn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:at.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!Y(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kn(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(n),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<l).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);ye(i,"No init buffer for starting representation"),ye(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ye(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();kt(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ye(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();kt(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=xt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(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 l=this.representations.get(u);if(!l||!Me(l.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ye(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ye(s,"No segments for starting representation");let a=this.initData.get(i);if(ye(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let 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=u,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(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,xt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ye(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ie(n)||ie(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),ye(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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 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)||!Y(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),s=this.segments.get(this.playingRepresentationId);if(ye(t,`No such representation ${this.downloadingRepresentationId}`),ye(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(s))return;let a=r.find(p=>e>=p.time.from&&e<p.time.to);kt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=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),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+u&&(n=a?a.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)&&Kn(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 l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))p="high";else{let h=l.at(0);h&&h.time.from-a.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(l,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!l.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)<u),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;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=[],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||!Me(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,u=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);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,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ye(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}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(!Me(r))return;let s=this.segments.get(i.id)??[],a=s.find(u=>Math.floor(u.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(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});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:p,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,g=h>i||b||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"&&g&&I&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(wt(this.sourceBuffer.buffered,h)&&wt(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,u=0,c=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<a.length&&(n<=l||u<=d);p++){let h=a[p];if(n+=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"){Me(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:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await xt(n,async function*(){let l=Jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=va(),!l)return;let d=new DataView(l),p=Ut(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,f)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Fe(l)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Me(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:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await xt(a,async function*(){let u=Jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Xn(window,"online").pipe(sm()).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=va(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Fe(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Me(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,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=va(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Me(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=va();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,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||!Y(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:u}=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),l=Ut(a.mime).parseFeedableSegmentChunk(c,this.isLive);l?.byteLength&&(u.status="partially_fed",n.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),n.fedBytes+=l.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let l=c.byte.from-i,d=c.byte.to-i,p=d-l+1,h=l<r,m=d<=r;if(!h)continue;let f=Ut(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.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:at.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Un(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?xt(this.destroyAbortController.signal,async function*(){let u=Jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ut(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:l,segments:d}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let h=d;this.isLive&&Me(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=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:u})});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||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;let r=[],s=0,a=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},n=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let c=Un(u)?u.size??0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&n(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=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(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};n(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 l of c)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Y(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||!Y(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||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:Tt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Y(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,u=s.end(a)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),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||!Y(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 u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&n<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:at.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!Y(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),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),u=e.some(l=>l.from-t<=a&&l.to+t>=n),c=e.filter(l=>a>=l.from&&a<l.to-t||n>l.from+t&&n<=l.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:at.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Nr,assertNever as Cc,fromEvent as Bc,merge as om,now as qt,Subject as Ti,ValueSubject as _r,flattenObject as Ii,ErrorCategory as Ei,SubscriptionRemovable as um,getWindow as Fr}from"@vkontakte/videoplayer-shared/evergreen";var Ta=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Ti;this.firstBytesManifest$=new Ti;this.firstBytesRequested$=new Ti;this.firstBytesReceived$=new Ti;this.lastConnectionType$=new _r(void 0);this.lastConnectionReused$=new _r(void 0);this.lastRequestFirstBytes$=new _r(void 0);this.lastConnectionMetrics$=new _r(void 0);this.lastDownloadMetrics$=new _r(void 0);this.recoverableError$=new Ti;this.error$=new Ti;this.abortAllController=new AbortController;this.subscription=new um;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=Nr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Zs(i)),this.trackRequestStart(i,performance.now());let r=qt();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ya);if(s){let a=qt();t.log("success",Ii({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let n=s.headers.get("content-length"),u=0;n&&(u=parseInt(n,10));let c=await s.text();if((!n||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let l=a-r,p=u/(l/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",Ii({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=Nr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:l=!1}={}){let d=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(d,Fr().location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),d=y.toString();break}default:Cc(t)}this.requestQuic&&(d=St(d));let m=this.abortAllController.signal,f;if(a){let y=new AbortController;if(f=om(Bc(this.abortAllController.signal,"abort"),Bc(a,"abort")).subscribe(()=>{try{y.abort()}catch(V){ya(V)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(V){ya(V)}m=y.signal}let b=0,g=qt();h.log("startRequest",Ii({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested$.next();let S=yield this.doFetch(d,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:l}),I=qt();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(I-g),!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&&!n){this.unsubscribeAbortSubscription(f);let y=qt(),V={requestStartedAt:g,requestEndedAt:y,duration:y-g};return h.log("endRequest",Ii(V)),h.end(),S.arrayBuffer()}let v=S.body;if(n){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,ya(y)},_=Nr(m,async function*({done:y,value:V}){if(b===0&&(this.lastRequestFirstBytes$.next(qt()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!y&&V){if(c&&A)k.set(V,b),b+=V.byteLength;else{let M=new Uint8Array(k.length+V.length);M.set(k),M.set(V,k.length),k=M,b+=V.byteLength}r?.(new DataView(k.buffer),b),yield x?.read().then(_,E)}}.bind(this));yield x?.read().then(_,E),this.unsubscribeAbortSubscription(f);let C=qt(),T={failed:D,requestStartedAt:g,requestEndedAt:C,duration:C-g};if(D)return h.error("endRequest",Ii(T)),h.end(),null;if(b>0){let y=C-g,M=b/(y/1e3)*8/1024,F={bytes:b,speed:M,url:e};this.lastDownloadMetrics$.next(F)}return h.log("endRequest",Ii(T)),h.end(),k.buffer}.bind(this));this.fetchByteRangeRepresentation=Nr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(a=Math.min(c,r),n=Math.max(l,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 p=new DataView(d,r-a,s-a+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(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,h,m);return{init:h,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Nr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{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,Fr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Js(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(Fr()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in Fr().navigator))return"unknown";let e=Fr().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,a=new URL(i.url),n=a.origin+a.pathname;if(s===n&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch{this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:Ei.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}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:Cc(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),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:Ei.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ei.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ei.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ei.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Ei.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ya=o=>{if(!Fe(o))throw o};import{isNullable as cm,ValueSubject as Vc}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 Vc(e.initial),this.debounced$=new Vc(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 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)&&(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 Ia=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 Ea=class extends Pt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=xn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=tt(this.emaSmoothed,e,this.params.emaAlpha);let i=Gu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var wa=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 zt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ia({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ea({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 wa({initial:e,label:"liveEdgeDelay",...t})}};var Zn=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};import{isNullable as dm,ValueSubject as lm}from"@vkontakte/videoplayer-shared/evergreen";var Ur=class o{constructor(e,t){this.currentRepresentation$=new lm(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(!dm(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 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=o.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Me(t.segmentReference))}};var Sm=["timeupdate","progress","play","seeked","stalled","waiting"],vm=["timeupdate","progress","loadeddata","playing","seeked"];var ka=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Nc;this.subscriptionRemovable=new fm;this.representationSubscription=new Nc;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new 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.lastConnectionMetrics$=new X(void 0);this.lastDownloadMetrics$=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=eo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(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=eo(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=sa(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let c=Xs(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,l)=>!!(this.element?.canPlayType?.(c)&&Pe()?.isTypeSupported?.(`${c}; codecs="${l}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:c,streamIsUnpublished:l,streamIsAlive:d}=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(d||(h=l?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),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:Be.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h));r[u]=l;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let p=l.map(({codecs:h})=>h);u==="audio"&&(a=da(p),d=a[0]),u==="video"&&(s=ca(p),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[u]=l.filter(({codecs:h})=>fi(h)===d))}else{let p=new Set(l.map(({codecs:h})=>h));d=ua(p),d&&(r[u]=l.filter(({codecs:h})=>h.startsWith(d)))}if(u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);$.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:f}=this.tuning.dash;f.length&&ma(r,f)}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",jr(n)),n}.bind(this));this.initRepresentations=eo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",jr({initialVideo:e,initialAudio:t,sourceHls:i})),wi(this.manifest),wi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(nt(d,"error").pipe(xa(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=ys();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ti())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Or("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Qr(t)){let d=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Or("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}if(Ur.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ur(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Wt(...vm.map(d=>nt(this.element,d))).pipe(ki(d=>this.element?Tt(this.element.buffered,this.element.currentTime*1e3):0),Hr(),bm(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Wt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Hr()).subscribe(p=>this.liveStreamEndTimestamp=io())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=to(p).subscribe(h=>{let m=hs(this.manifestUrlString,2);this.manifestUrlString=le(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(xi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ki(({isActiveLive:p,isLowLatency:h})=>p&&h),Hr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Zn(this.element,1)})),this.representationSubscription.add(xi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xa(({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(xi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xa(({isLive:p})=>p),Hr((p,h)=>h.bufferLength<p.bufferLength),ki(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=hs(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xi({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,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=p-f;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(S)>b&&(I=1+Math.sign(S)*g),Zn(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(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let d=0;this.representationSubscription.add(xi({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=hs(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,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(p)?p:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=b<=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<g?R="live_forward_buffering":v<g+I&&(R="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),R==="live_forward_buffering"||R==="live_with_target_offset"){let k=d-(g+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=le(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(d=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=Wt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(ki(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Wt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(ki(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),l=xi({allBuffersFull:u,someBufferEnded:c}).pipe(Hr(),ki(({allBuffersFull:d,someBufferEnded:p})=>d&&p),xa(d=>d));if(this.representationSubscription.add(Wt(this.forceEnded$,l).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Be.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Wt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category: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 d=[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),Me(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Qr(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=to(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 Ta({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.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.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=zt.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){wi(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"?io()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(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(){wi(this.element),this.state$.setState("running"),this.subscription.add(Wt(...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:s,stallWatchdogInterval:a}=this.tuning.dash,n=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let l=this.currentStallDuration$.getValue();l+=a,this.currentStallDuration$.next(l);let d={timeInWaiting:l},p=io(),h=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<h&&p-m>r,I=this.audioBufferManager&&g<h&&p-f>r;if((!t||c)&&((S||I)&&l>r||l>=i))throw new Error(`Stall timeout exceeded: ${l} ms`);if(n&&l%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(x=>{this.error$.next({id:"stallIntervalCallback",category:Be.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),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",jr(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=to(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){wi(this.element),wi(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()]),!(Oc(this.element)||Oc(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",jr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Qr(this.element)&&Qr(this.source)&&Qr(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 s=this.element.currentTime*1e3,a=[],n=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-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 u=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:a,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",jr(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 ro,noop as wm}from"@vkontakte/videoplayer-shared/evergreen";var Pa=class{constructor(){this.subscription=new Em;this.pipSize$=new ro(void 0);this.videoSize$=new ro(void 0);this.elementSize$=new ro(void 0);this.pictureInPictureWindowRemoveEventListener=wm}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.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:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Gt=class{constructor(e){this.subscription=new Dm;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new Gs;this.elementSizeManager=new Pa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.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 di(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 ka({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=a=>{e.error$.next({id:i,category:_c.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(so(d=>!!d.length),Uc()).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(zr(d=>d.to.state!=="none"),qr());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.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(so(Fc),Uc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(zr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(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}),s(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:d})=>{if(d==="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 b of p.audio){f.push(_n(b));let g=[];for(let S of b.representations){let I=Ar(S);g.push(I),this.audioTracksMap.set(I,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Fn(f));let b=[];for(let g of f.representations){let S=yt({...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 p.text)for(let b of f.representations){let g=bc(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Wr(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$,$m(this.video,"progress")).pipe(so(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(n=n.pipe(Lm(u))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,f]=h,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);Fc(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(Mm({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Wr(Ma([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(zr(d=>d.to)))}).pipe(zr(({videoState:d,autoVideoTrackState:p})=>d.to!=="stopped"&&p),qr()).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(qr()).subscribe(d=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);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(Fn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qr()).subscribe(d=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);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(_n(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(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(zr(({to:d})=>d==="ready"),qr());this.subscription.add(Wr(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ma(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Wr(c,this.player.state$.stateChangeEnded$,Ma(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Wr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ma(["init"])).pipe(Am(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?qi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?_s:Ns,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Os,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:k})=>k===n),c=s.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let d=[...this.videoStreamsMap.keys()].find(({id:k})=>k===l.id),p=d&&this.videoStreamsMap.get(d);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=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:k})=>k===g?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(u&&!a){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;(a||!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: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 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:b,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:_c.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 Gr=class extends Gt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ao,merge as Hc,filter as jc,filterChanged as Qc,isNullable as no,map as qc,ValueSubject as oo,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/evergreen";var Yr=class extends Gt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new oo(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Qc()).subscribe(u=>{let c=i.position$.getValue(),l=i.volume$.getValue(),d=!l.volume||l.muted;!u&&!c&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(qc(u=>u.to)).subscribe(this.player.isLowLatency$)).add(ao({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qc(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(ao({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Hc(r.playbackRateState$,new oo(1))}).pipe(jc(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let l=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-p||this.video.paused||no(l)||(t=u-l)})).add(ao({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Hc(r.playbackRateState$,new oo(1))}).pipe(Qc((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:l})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-p||no(u)||no(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=gc(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(jc(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 zc="X-Playback-Duration",uo=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(zc)?parseInt(e.headers.get(zc),10):void 0};import{assertNever as qm,combine as zm,debounce as Wm,ErrorCategory as Ra,filter as Gm,filterChanged as Ym,isNonNullable as Yc,isNullable as Da,map as Kc,merge as Km,observableFrom as Xm,Subscription as Jm,ValueSubject as lo,VideoQuality as Zm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Bm,getExponentialDelay as Vm}from"@vkontakte/videoplayer-shared/evergreen";var Om=o=>{let e=null;if(o.QUALITY&&(e=ft(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Bm({width:t,height:i})}return e??null},Nm=(o,e)=>{let t=o.split(`
|
|
178
|
+
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],n=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!n&&!u)){if(n){let c=Object.fromEntries(n[1].split(",").map(b=>b.split("="))),l=c.QUALITY??`stream-${c.BANDWIDTH}`,d=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[b,g]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();d&&i.push({id:l,quality:d,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,"")])),l=c.URI?.replace(/playlist$/,"subtitles.vtt"),d=c.LANGUAGE,p=c.NAME;l&&d&&r.push({type:"internal",id:d,label:p,language:d,url:l,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},_m=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),co=0,Wc=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();co+=1;try{let{qualityManifests:a,textTracks:n}=Nm(s,e);return{qualityManifests:a,textTracks:n}}catch{if(co<=t.manifestRetryMaxCount)return await _m(Vm(co-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Wc(o,e,t)}return{qualityManifests:[],textTracks:[]}},Aa=Wc;import{isNonNullable as Fm,Subscription as Um,throttle as Hm,ValueSubject as Gc,Subject as jm,ErrorCategory as Qm}from"@vkontakte/videoplayer-shared/evergreen";var $a=class{constructor(e,t,i,r,s){this.subscription=new Um;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Gc(null);this.getCurrentTime$=new Gc(null);this.error$=new jm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Hm(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),n=this.parsePlaylist(a,r);return{textTrack:i,playlist:n}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
179
|
+
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let u=r[++a],c=new URL(u,t).toString(),l=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+l},url:c}),s=s+l,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-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 u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=u;let c=new Date(u);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(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 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:Qm.WTF,thrown:t,message:e})}};var Kr=class{constructor(e){this.subscription=new Jm;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lo([]);this.liveOffset=new Vt;this.manifestStartTime$=new lo(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"),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(s||a||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),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"?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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else r?.to==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return qm(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)=>Aa(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 $a(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:Ra.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:Ra.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 lo(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(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Ra.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,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(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(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"),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(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(Ym(),Kc(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&Yc(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(pe(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.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(zm({startTime:this.manifestStartTime$.pipe(Gm(Yc)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Kc(n=>n.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=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(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Da(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:u}=t?.to??i??{};for(let[c,l]of[[n,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&r.searchParams.set(l,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=le(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),uo(a).then(n=>{if(!Da(n))this.maxSeekBackTime$.next(n);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Da(u)||!isFinite(u))&&fetch(a).then(c=>c.text()).then(c=>{let l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(l){let d=new URL(l,a).toString();uo(d).then(p=>{Da(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:Ra.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=le(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 po,fromEvent as ho,isNonNullable as rf,isNullable as sf,map as Xc,merge as Jc,observableFrom as Zc,Subscription as af,ValueSubject as ed,VideoQuality as nf}from"@vkontakte/videoplayer-shared/evergreen";var Xr=class{constructor(e){this.subscription=new af;this.videoState=new O("stopped");this.manifests$=new ed([]);this.unmuteAfterBrowserResetsHappened=new ed(!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"),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(s||a||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);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"?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(),Aa(le(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:po.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(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:po.WTF,message:"HlsProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u));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(Xc(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),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 n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=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 d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.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(Xc(n=>n.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Jc(ho(n,"addtrack"),ho(n,"removetrack"),ho(n,"change"),Zc(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let a=Jc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zc(["init"])).pipe(tf(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(sf(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,u]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));u&&n&&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:po.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as of,assertNonNullable as td,debounce as uf,ErrorCategory as id,isHigherOrEqual as cf,isLowerOrEqual as df,isNonNullable as lf,merge as pf,observableFrom as hf,Subscription as mf,map as ff}from"@vkontakte/videoplayer-shared/evergreen";var Jr=class{constructor(e){this.subscription=new mf;this.videoState=new O("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 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:u}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.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 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:id.WTF,message:"MpegProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,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(ff(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(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)),s(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 n=this.params.desiredState.videoTrack.getTransition();if(n&&lf(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let u=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(u!==c){let l=this.params.output.element$.getValue();l&&(this.params.desiredState.playbackRate.setState(u),l.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 a=pf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,hf(["init"])).pipe(uf(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;td(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];td(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:id.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 l=Ye(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(l)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||ai(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?df(r,e.max):!0,u=e.min?cf(r,e.min):!0;n&&u||i(e)}};import{assertNever as sd,debounce as vf,merge as ad,observableFrom as yf,Subscription as Tf,map as nd,ValueSubject as If,ErrorCategory as fo,VideoQuality as Ef}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as bf}from"@vkontakte/videoplayer-shared/evergreen";var rd=["stun:videostun.mycdn.me:80"],gf=1e3,Sf=3,mo=()=>null,La=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=mo;this.externalStopCallback=mo;this.externalErrorCallback=mo;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:rd}]};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:rd,maxRetryNumber:Sf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Zr=class{constructor(e){this.videoState=new O("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 s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return sd(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 La(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:fo.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(ad(this.videoState.stateChangeStarted$.pipe(nd(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nd(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=we(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(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return sd(a.to)}},i)).add(ad(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:fo.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:fo.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Pi=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 es,assertNonNullable as ut,ErrorCategory as Ca,filter as pd,isNonNullable as hd,isNullable as $f,map as Rf,merge as Df,once as Lf,Subject as J,Subscription as md,ValueSubject as B,flattenObject as bo,devNull as Cf,getWindow as Bf}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as wf,map as od,Subscription as xf,Subject as kf}from"@vkontakte/videoplayer-shared/evergreen";var ud=o=>new wf(e=>{let t=new xf,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(od(({from:c,to:l})=>`${c}-${l}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(od(({type:c})=>c!==void 0)),a=new kf,n=0,u="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),u=c,n=window.setTimeout(()=>a.next(c),o.maxTransitionInterval),L({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{L({m:"hangup.cl",id:n}),window.clearTimeout(n),u="unknown",n=0})),t.add(s.subscribe(c=>{n&&(L({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(u),o.maxTransitionInterval),L({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Pf,Subscription as Mf,combine as Af,filter as dd,once as ld}from"@vkontakte/videoplayer-shared/evergreen";function cd(){return new(window.AudioContext||window.webkitAudioContext)}var Mi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Mf;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(dd(s=>!!s.type),ld()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Af({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(dd(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),ld()).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=cd();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:o.errorId,category:Pf.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var Vf={chunkDuration:5e3,maxParallelRequests:5},ts=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),httpConnectionMetrics$:new B(void 0),httpDownloadMetrics$: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 md;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=Ja([...uc(this.params.tuning),...oc(this.params.tuning)]).filter(c=>hd(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",bo(s)),this.screenFormatsIterator=new Pi(s);let a=[...On(!0),...On(!1)];this.chromecastFormatsIterator=new Pi(a.filter(c=>hd(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&n!==1&&Mi.isSupported()&&(this.volumeMultiplierManager=new Mi(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}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 Pi(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($f(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Ca.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 es(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 u=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ut(u),this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new yi({...n,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new yi({...n,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Gr({...n,source:u,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ut(u),new Yr({...n,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return ut(u),new Xr({...n,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ut(u),new Kr({...n,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ut(u),new Jr({...n,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ut(u),new Hu({...n,source:u,config:{...Vf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ut(u),new Zr({container:i,source:u,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 es(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 Ze){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return ut(c),new Bi({...n,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return ut(u),new _i({...n,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 es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return es(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 es(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 md,t=!1,i=0;e.add(Df(this.providerOutput.error$.pipe(pd(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),ud({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Rf(s=>({id:`ProviderHangup:${s}`,category:Ca.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(pd(({to:a})=>a==="playing"),Lf()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=L.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&Bf().console.log(`===== DASH_LIVE DEBUG START ====
|
|
180
|
+
`,s.map(({time:u,data:c,stack:l})=>`${u}: ${JSON.stringify(c)}${l?`
|
|
181
|
+
`+l:""}`).join(`
|
|
182
182
|
`),`
|
|
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},"");Lf.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 Vf,combine as Of,Subscription as dl,ValueSubject as ho,map as pl,filter as Nf,isNonNullable as Ms,now as $e,safeStorage as mo,getWindow as _f}from"@vkontakte/videoplayer-shared/evergreen";var Ff=5e3,hl="one_video_throughput",ml="one_video_rtt",bo=()=>{let{navigator:n}=_f();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)||Ff,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(Of({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pl(({throughput:r,rtt:a})=>gl(r,a,e.rttPenaltyRequestSize)),Nf(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(Vf()).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 Uf,VideoQuality as Rs}from"@vkontakte/videoplayer-shared/evergreen";var Hf={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},vl=n=>Uf(n,Hf);import{assertNonNullable as vo,combine as ct,ErrorCategory as Ds,filter as re,filterChanged as z,fromEvent as yo,isNonNullable as wl,isNullable as Zf,Logger as eb,map as j,mapTo as xl,merge as At,now as Ls,once as oe,Subject as H,Subscription as kl,tap as To,ValueSubject as P,isHigher as tb,isInvariantQuality as Pl,flattenObject as $t,throttle as Io,getTraceSubscriptionMethod as Al,TracerFactory as ib,InternalsExposure as rb,getPlayerId as ab,devNull as Bs}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Qf,map as jf,filter as yl,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),yl(zf)),e.pipe(yl(()=>n.getState().state==="none")));import{assertNonNullable as qf}from"@vkontakte/videoplayer-shared/evergreen";var Tl=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 Il=(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 El=()=>{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 Cs=class{constructor(e={},t=ib.createRootTracer(!1),i){this.subscription=new kl;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),enableDebugTelemetry$:new P(!1),dumpTelemetry:hu,getCurrentTime$:new P(null)};this.initLogs(),this.tuning=vl(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)));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,Bs.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=Tl(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?(Bs.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=El())):Bs.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(),Bs.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(()=>{Il(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 wl(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)=>Pl(u)?1:Pl(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=>wl(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(xl(!0)),e.providerOutput.seekedEvent$.pipe(xl(!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 kl;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=Al(this.tracer.log.bind(this.tracer)),t=Al(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,Cs 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,rd as areValidLiveRecordSources,M as clientChecker,Bt as isMobile};
|
|
183
|
+
===== DASH_LIVE DEBUG END ====`),n){let u=s.reduce((c,{time:l,data:d,stack:p})=>{let h=Object.entries(d).map(([m,f])=>`${m}:${f}`).join(",");return c+=`${l}: ${h}${p?`: ${p}`:""};`,c},"");Cf.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(L({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{L({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 u=s.category===Ca.NETWORK,c=s.category===Ca.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!c,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=l&&!c&&(u&&t||!d);n={...n,isNetworkError:u,isFatalError:c,haveFailoverHost:l,tryFailover:h,canReinitProvider:d},d?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",bo(n)):this.tracer.error("providerError",bo(n))})),e}};import{fromEvent as Ba,once as Of,combine as Nf,Subscription as fd,ValueSubject as go,map as bd,filter as _f,isNonNullable as Va,now as Ae,safeStorage as So,getWindow as Ff}from"@vkontakte/videoplayer-shared/evergreen";var Uf=5e3,gd="one_video_throughput",Sd="one_video_rtt",yo=()=>{let{navigator:o}=Ff();if(o)return o.connection},vd=()=>{let o=yo()?.downlink;if(Va(o)&&o!==10)return o*1e3},yd=()=>{let o=yo()?.rtt;if(Va(o)&&o!==3e3)return o},Td=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},vo=class o{constructor(e){this.subscription=new fd;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(gd)||(e.useBrowserEstimation?vd():void 0)||Uf,i=o.load(Sd)??(e.useBrowserEstimation?yd():void 0)??0;if(this.throughput$=new go(t),this.rtt$=new go(i),this.rttAdjustedThroughput$=new go(Td(t,i,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=vd();n&&this.throughput.next(n);let u=yd();Va(u)&&this.rtt.next(u)},s=yo();s&&"onchange"in s&&this.subscription.add(Ba(s,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{So.set(gd,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{So.set(Sd,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(bd(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(bd(({throughput:r,rtt:s})=>Td(r,s,e.rttPenaltyRequestSize)),_f(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=Ae(),r=new fd;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ba(e,"progress").pipe(Of()).subscribe(s=>{t=s.loaded,i=Ae()}));break;case 1:case 0:r.add(Ba(e,"loadstart").subscribe(()=>{t=0,i=Ae()}));break}r.add(Ba(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=Ae(),u=a-t,c=n-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,s=Ae(),a=0,n=Ae(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(r,Ae()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ae();if(p-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=Ae()}else a+=d.byteLength;n=Ae()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Ae()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Ae()-n,this.concurrentDownloads.size),a=0,n=Ae());await i?.read().then(c,u)}};this.concurrentDownloads.add(e),i?.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(o.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=So.get(e);if(Va(t))return parseInt(t,10)??void 0}},Id=vo;import{fillWithDefault as Hf,VideoQuality as Oa}from"@vkontakte/videoplayer-shared/evergreen";var jf={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:Oa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Oa.Q_720P,trafficSavingLimit:Oa.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:Oa.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,videoStreamRepresentaionsFilter:[]},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},Ed=o=>Hf(o,jf);import{assertNonNullable as Eo,combine as ct,ErrorCategory as Na,filter as re,filterChanged as q,fromEvent as wo,isNonNullable as Md,isNullable as eb,Logger as tb,map as Q,mapTo as Ad,merge as Mt,now as _a,once as oe,Subject as H,Subscription as $d,tap as xo,ValueSubject as P,isHigher as ib,isInvariantQuality as Rd,flattenObject as At,throttle as ko,getTraceSubscriptionMethod as Dd,TracerFactory as rb,InternalsExposure as sb,getPlayerId as ab,devNull as Fa}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Qf,map as qf,filter as wd,isNonNullable as zf}from"@vkontakte/videoplayer-shared/evergreen";var To=({seekState:o,position$:e})=>Qf(o.stateChangeEnded$.pipe(qf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),wd(zf)),e.pipe(wd(()=>o.getState().state==="none")));import{assertNonNullable as Wf}from"@vkontakte/videoplayer-shared/evergreen";var xd=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return Wf(e,`Wrong container or containerId {${o.container}}`),e};import{filter as Gf,once as Yf}from"@vkontakte/videoplayer-shared/evergreen";var kd=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Gf(r=>r.length>0),Yf()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};import{devNull as Kf,getWindow as Io}from"@vkontakte/videoplayer-shared/evergreen";var Pd=()=>{let o="mediaCapabilities"in Io().navigator?Xf:Jf,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Zf).map(async([r,s])=>({codec:r,supported:await o(s)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Kf.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},Xf=async o=>{if(!o)return Promise.resolve({supported:!1});let e={["channels"in o?"audio":"video"]:o};return await Io().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Jf=o=>{if(!o)return Promise.resolve({supported:!1});let e=Io().document,t="channels"in o?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(o?.contentType??"")==="probably"})},Zf={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 Ua=class{constructor(e={},t=rb.createRootTracer(!1),i){this.subscription=new $d;this.logger=new tb;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 O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new 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),httpConnectionMetrics$:new P(void 0),httpDownloadMetrics$: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),enableDebugTelemetry$:new P(!1),dumpTelemetry:gu,getCurrentTime$:new P(null)};this.initLogs(),this.tuning=Ed(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 Ze(r):new ps(r),this.throughputEstimator=new Id(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new sb("core",ab(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Fa.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let u=Reflect.get(s,a,n);return typeof u!="function"?u:(...c)=>{try{return u.apply(s,c)}catch(l){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}>`})),p=`Player.${String(a)}`,h=`Exception calling ${p} (${d.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Na.WTF,message:h,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",At(a)),this.domContainer=xd(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ts({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?(Fa.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Pd())):Fa.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(re(s=>!!s),oe()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),wo(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(),Fa.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(),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 Ze)?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 Ze)?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(()=>{Eo(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",At(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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{kd(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(eb(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Md(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(Mt(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(vu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),oe()).subscribe(()=>{this.initedAt=_a(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",At(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:Na.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 a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(u=>n?n.id===u.streamId:!0).map(({quality:u})=>u).sort((u,c)=>Rd(u)?1:Rd(c)?-1:ib(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let u of a)u.fps&&(n[u.quality]=u.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(re(a=>Md(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.httpConnectionMetrics$.pipe(q()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe(q()).subscribe(this.info.httpDownloadMetrics$)).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(xo(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(ct({hasLiveOffsetByPaused:Mt(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(ct({atLiveEdge:ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:To({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:n,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return a&&Math.abs(n)<c/1e3}),q(),xo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:n,duration:u})=>a&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),q(),xo(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(To({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(Mt(e.providerOutput.endedEvent$.pipe(Ad(!0)),e.providerOutput.seekedEvent$.pipe(Ad(!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:Na.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(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(),Q(a=>a??_a()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(oe(),Q(()=>_a()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(oe(),Q(()=>_a()-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:a})=>a==="playing"),oe()).subscribe(()=>i.next(!1)));let r=0,s=Mt(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(Mt(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(Mt(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(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?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 $d;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),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(Mt(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;Eo(this.providerContainer),Eo(e),bu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>fu(t)),this.providerContainer.current$.subscribe(({type:t})=>ji("provider",t)),e.duration$.subscribe(t=>ji("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),oe()).subscribe(t=>ji("tracks",t)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(t=>this.subscription.add(t)),ji("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=Dd(this.tracer.log.bind(this.tracer)),t=Dd(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(ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ct({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(ko(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(ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),ko(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),ko(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Na.DOM,message:String(r)})})};this.subscription.add(Mt(wo(document,"visibilitychange"),wo(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",At({quality:t,availableTracks:At(e),track:At(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ki()}};import{Subscription as D0,Observable as L0,Subject as C0,ValueSubject as B0,VideoQuality as V0}from"@vkontakte/videoplayer-shared/evergreen";var O0=`@vkontakte/videoplayer-core@${Mo}`;export{Li as ChromecastState,Qa as HttpConnectionType,L0 as Observable,fe as PlaybackState,Ua as Player,ds as PredefinedQualityLimits,O0 as SDK_VERSION,C0 as Subject,D0 as Subscription,qa as Surface,Mo as VERSION,B0 as ValueSubject,Je as VideoFormat,V0 as VideoQuality,aa as WebmCodecStrategy,ol as areValidLiveRecordSources,$ as clientChecker,Ct as isMobile};
|