@vkontakte/videoplayer-core 2.0.154-dev.ffe03d52.0 → 2.0.155
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 +25 -25
- package/es2015.esm.js +22 -22
- package/es2018.cjs +24 -24
- package/es2018.esm.js +22 -22
- package/es2024.cjs +27 -27
- package/es2024.esm.js +23 -23
- package/esnext.cjs +27 -27
- package/esnext.esm.js +23 -23
- package/evergreen.esm.js +23 -23
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -1
- package/types/player/types.d.ts +2 -0
- package/types/providers/DashProvider/lib/utils.d.ts +1 -1
- package/types/providers/utils/HTMLVideoElement/destroy.d.ts +1 -1
- package/types/providers/utils/HTMLVideoElement/pool.d.ts +3 -3
- package/types/providers/utils/parsers/types.d.ts +6 -0
- package/types/providers/utils/videoStreamRepresentaionsFilter.d.ts +1 -1
- package/types/utils/tuningConfig.d.ts +12 -0
package/evergreen.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
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.155
|
|
3
|
+
* Wed, 11 Mar 2026 06:02:14 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-155/doc/
|
|
5
5
|
*/
|
|
6
|
-
var _o="2.0.154-dev.ffe03d52.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),Xe=(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))(Xe||{}),Xa=(r=>(r.AV1="av1",r.VP9="vp9",r.AVC1="avc1",r.HEV1="hev1",r))(Xa||{});var Oi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Oi||{}),Ja=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ja||{});var Za=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Za||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});import{assertNever as qo,assertNonNullable as nd,isNonNullable as gs,ValueSubject as en,Subject as od,Subscription as ud,merge as cd,observableFrom as ld,fromEvent as Ho,map as jo,tap as Qo,filterChanged as dd,isNullable as tn,ErrorCategory as zo}from"@vkontakte/videoplayer-shared/evergreen";var Uo=u=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",u),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ss=class{constructor(e){this.connection$=new en(void 0);this.castState$=new en("NOT_AVAILABLE");this.errorEvent$=new od;this.realCastState$=new en("NOT_AVAILABLE");this.subscription=new ud;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=gs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Uo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zo.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(){gs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();tn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();tn(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(Ho(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 qo(r.sessionState)}})).add(cd(Ho(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),jo(r=>r.castState)),ld([i.getCastState()])).pipe(dd(),jo(pd),Qo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=gs(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();nd(n);let o=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(tn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?gs(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:zo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},pd=u=>{switch(u){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return qo(u)}};import{assertNonNullable as un,combine as cn,debounce as ln,ErrorCategory as Ld,filter as ni,filterChanged as su,isNonNullable as dn,isNullable as au,map as Rd,Subscription as Dd,ValueSubject as pn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as hd,assertNonNullable as Bt,ErrorCategory as md,getHighestQuality as fd,isNonNullable as Go}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Wo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(u,e=0,t=0)=>{switch(t){case 0:return u.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return u;let i=new URL(u);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(u);return!i.searchParams.get("offset_p")&&e===0?u:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Wo(t)}return u},mt=(u,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(u);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(u);return Number(t.searchParams.get("offset_p")??0)}default:Wo(e)}};var ys=u=>{let{source:e,format:t,meta:i,output:r}=u,s,a,n;switch(t){case"MPEG":{let l=e[t];Bt(l);let p=fd(Object.keys(l));Bt(p);let h=l[p];Bt(h),s=h,a="video/mp4",n=vs();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];Bt(l),s=l.url,a="application/x-mpegurl",n=vs();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];Bt(l),s=l.url,a="application/dash+xml",n=vs();break}case"DASH_LIVE_CMAF":{let l=e[t];Bt(l),s=l.url,a="application/dash+xml",n=Yo();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];Bt(l),s=ee(l.url),a="application/x-mpegurl",n=Yo();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:md.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return hd(t)}let o=bd(i.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=gd();let{title:c,subtitle:d}=i;return Go(c)&&(o.metadata.title=c),Go(d)&&(o.metadata.subtitle=d),o};function vs(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Yo(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function bd(u,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(u,e):{contentId:u,contentType:e,metadata:{title:"",subtitle:""},streamType:vs()}}function gd(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var w=(u,e,t=!1)=>{let i=u.getTransition();(t||!i||i.to===e)&&u.setState(e)};var Ts=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 ru}from"@vkontakte/videoplayer-shared/evergreen";import{isBrowserWindow as Md,ValueSubject as $d}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as Sd}from"@vkontakte/videoplayer-shared/evergreen";var Is=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,n=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||c||r||s||n||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=Sd().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 rn,isBrowserWindow as sn}from"@vkontakte/videoplayer-shared/evergreen";var Vt=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Es=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=rn();if(!sn(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Vt()}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=rn();if(!sn(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||a||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r.length>0,n=r.length>1,o="Unknown",c="Unknown";if(a){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(o=s[d]):o=d}if(n){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&a&&typeof r[0]=="string"&&(c=s[1]);o=this.normalizeOSName(o),c=this.normalizeOSVersion(c,o),o==="iOS"&&/ipad/i.test(e)?o="iPadOS":o==="iPadOS"&&/ip(hone|od)/i.test(e)&&(o="iOS"),this._os={name:o,version:c||"Unknown",full:c&&c!=="Unknown"?`${o} ${c}`:o};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r[0],n=r[1],o=typeof a=="number"?s[a]!==void 0?this.normalizeVendorName(s[a]):"Unknown":this.normalizeVendorName(a),c="Unknown";typeof n=="number"?c=s[n]!==void 0?s[n]:"Unknown":n!==void 0?c=n:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,o),this.details.vendor=o,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=rn();if(!sn(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 Ko,isBrowserWindow as vd}from"@vkontakte/videoplayer-shared/evergreen";var ws=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Ko()}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=Ko();if(!vd(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 an,isBrowserWindow as Jo}from"@vkontakte/videoplayer-shared/evergreen";var Pe=()=>window.ManagedMediaSource||window.MediaSource,ai=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Xo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),xs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var yd=an().document?.createElement("video"),Td='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Id='video/mp4; codecs="hev1.1.6.L93.B0"',Zo='video/webm; codecs="vp09.00.10.08"',eu='video/webm; codecs="av01.0.00M.08"',Ed='audio/mp4; codecs="mp4a.40.2"',wd='audio/webm; codecs="opus"',tu,xd=async()=>{let u=an();if(!Jo(u))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:eu}}),u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Zo}})]);tu={DASH_WEBM_AV1:t,DASH_WEBM:i}};xd().catch(u=>{console.log(yd),console.error(u)});var ks=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 tu}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=an();if(!Jo(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:ai(),mse:Xo(),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?.(Td),r=!!Pe()?.isTypeSupported?.(Id),s=!!Pe()?.isTypeSupported?.(Ed);this._codecs={h264:i,h265:r,vp9:!!Pe()?.isTypeSupported?.(Zo),av1:!!Pe()?.isTypeSupported?.(eu),aac:s,opus:!!Pe()?.isTypeSupported?.(wd),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 kd,isBrowserWindow as Pd}from"@vkontakte/videoplayer-shared/evergreen";var iu="audio/mpeg",Ps=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=kd();if(!Pd(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(iu)},this._codecs={mp3:!!Pe()?.isTypeSupported?.(iu)}}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 nn=class{constructor(){this.isInited$=new $d(!1);this._displayChecker=new ws,this._deviceChecker=new Es(this._displayChecker),this._browserChecker=new Is,this._videoChecker=new ks(this._deviceChecker,this._browserChecker),this._audioChecker=new Ps,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(){Md()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},A=new nn;var on=u=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=A.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return u.filter(n=>{switch(n){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return ru(n)}})},Ni=u=>{switch(u){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ru(u)}},Ad=u=>{let t=Object.keys(u).filter(i=>!Ni(i));return on(t).length>0};var Fi=class{constructor(e){this.subscription=new Dd;this.sessionId$=new pn(null);this.mediaSessionId$=new pn(null);this.contentId$=new pn(null);this.isMobile=Vt();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(au(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;dn(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(dn(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 Ts(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ni(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:Ld.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ni(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(ni(dn),su(),ln(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(su(),Rd(Boolean));this.subscription.add(cn({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ni(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=cn({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(ni(({mediaLoaded:r})=>r),ln(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(ni(({mediaLoaded:r,playbackState:{from:s,to:a}})=>!r&&s==="stopped"&&a==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(cn({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ln(30)),mediaLoaded:t}).pipe(ni(({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=ys(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();un(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();un(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();un(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(au(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 Cd,ErrorCategory as hn,filter as Bd,Subject as Vd,Subscription as mn,tap as Od,ValueSubject as oi,fromEvent as _i}from"@vkontakte/videoplayer-shared/evergreen";var nu=u=>({castDevice:{friendlyName:u},remotePlayer:{},remotePlayerController:{},session:{}}),ou=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ui=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new oi(null);this.sessionId$=new oi(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new mn;this.subscriptionEvents=new mn;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new oi(!1);this.presentationConnection$=new oi(null);this.message$=new oi(null);this.friendlyName$=new oi(null);this.errorEvent$=new Vd;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(_i(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();Cd(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:hn.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(_i(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(Od(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Bd(e=>!!e)).subscribe(e=>{let t=_i(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=_i(e,"connect").subscribe(()=>{this.send("client_connect")}),r=_i(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:hn.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:hn.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]||ou()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new mn}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 uu,Subject as Nd,map as Fd,Subscription as _d,combine as Ud,filterChanged as cu,assertNonNullable as Hd}from"@vkontakte/videoplayer-shared/evergreen";var Je=class u{constructor(e){this.subscription=new _d;this.connection$=new uu(void 0);this.castState$=new uu("NOT_AVAILABLE");this.errorEvent$=new Nd;let t=u.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ui({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){Hd(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Ud({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(cu())});this.subscription.add(e.pipe(Fd(({connection:t,friendlyName:i})=>!!(t&&i)),cu()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?nu(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 jd,Subject as Ms,merge as lu}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new Ms;this.transitionEnded$=new Ms;this.transitionUpdated$=new Ms;this.forceChanged$=new Ms;this.stateChangeStarted$=lu(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=lu(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||jd(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 Hi,debounce as du,ErrorCategory as Qd,fromEvent as Ot,map as pu,merge as hu,observableFrom as zd,Subject as qd,Subscription as fn,timeout as Wd}from"@vkontakte/videoplayer-shared/evergreen";var Gd=5,Yd=5,Kd=500,mu=7e3,ji=class{constructor(e){this.subscription=new fn;this.loadMediaTimeoutSubscription=new fn;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:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ni(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 fn;this.subscription.add(e),this.subscription.add(hu(this.videoState.stateChangeStarted$.pipe(pu(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(pu(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 qd;e.add(r.pipe(du(Kd)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ot(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)>Gd)&&r.next(n),s=n})),e.add(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Yd&&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:Hi(a)}}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=hu(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zd(["init"])).pipe(du(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=ys(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(Wd(mu).subscribe(()=>s(`timeout(${mu})`)))});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:Qd.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as bu,getWindow as Jd}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Xd}from"@vkontakte/videoplayer-shared/evergreen";var fu=u=>{try{u.pause(),u.playbackRate=0,Xd(u),u.remove()}catch(e){console.error(e)}};import{fromEvent as Zd,Subscription as ep}from"@vkontakte/videoplayer-shared/evergreen";var bn=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)}},$s=Jd(),gn=$s.WeakMap?new $s.WeakMap:new bn,Sn=$s.WeakMap?new $s.WeakMap:new Map,tp=(u,e=20)=>{let t=0;return Zd(u,"ratechange").subscribe(i=>{t++,t>=e&&(u.currentTime=u.currentTime,t=0)})},Te=(u,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=u.querySelector("video"),r=!!i;i?bu(i):(i=document.createElement("video"),u.appendChild(i)),gn.set(i,r);let s=new ep;return s.add(tp(i,e)),Sn.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=u=>{Sn.get(u)?.unsubscribe(),Sn.delete(u);let t=gn.get(u);gn.delete(u),t?bu(u):fu(u)};import{assertNonNullable as zi,isNonNullable as qe,isNullable as sp,fromEvent as ui,merge as gu,observableFrom as Su,filterChanged as vu,map as qi,Subject as yu,Subscription as ap,ValueSubject as np,ErrorCategory as op}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as vn,isNullable as ip,Subscription as rp}from"@vkontakte/videoplayer-shared/evergreen";var As=(u,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=u.getState(),n=e(),o=ip(r),c=new rp;return r&&c.add(r.subscribe(d=>{let l=u.getState();i(d,l)&&u.setState(d)},s)),i(n,a)||(t(a),o&&u.setState(a)),c.add(u.stateChangeStarted$.subscribe(d=>{t(d.to),o&&u.setState(d.to)},s)),c},ze=(u,e,t)=>As(e,()=>u.loop,i=>{vn(i)&&(u.loop=i)},{onError:t}),Ee=(u,e,t,i)=>As(e,()=>({muted:u.muted,volume:u.volume}),r=>{vn(r)&&(u.muted=r.muted,u.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(u,e,t,i)=>As(e,()=>u.playbackRate,r=>{vn(r)&&(u.playbackRate=r)},{changed$:t,onError:i}),Qi=As;var up=u=>["__",u.language,u.label].join("|"),cp=(u,e)=>{if(u.id===e)return!0;let[t,i,r]=e.split("|");return u.language===i&&u.label===r},yn=class u{constructor(e){this.available$=new yu;this.current$=new np(void 0);this.error$=new yu;this.subscription=new ap;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:op.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Qi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{qe(s)&&this.setInternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Qi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{qe(s)&&this.setExternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Qi(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(Qi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){zi(this.video);let{textTracks:e}=this.video;this.subscription.add(ui(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(gu(ui(e,"addtrack"),ui(e,"removetrack"),Su(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),vu((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(gu(ui(e,"change"),Su(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),qi(i=>i&&this.htmlTextTrackToITextTrack(i).id),vu()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ui(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(ui(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;qe(t.align)&&(r.align=t.align),qe(t.position)&&(r.position=t.position),qe(t.size)&&(r.size=t.size),qe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){zi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(u.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:up(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){zi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(sp(e)||!cp(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){zi(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){zi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ce=yn;var Nt=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 Tu=u=>{let e=u;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Tn=u=>{let e=Tu(u);return!!(e&&e.fullscreenElement&&e.fullscreenElement===u)},Iu=u=>{let e=Tu(u);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===u)};import{fromEvent as ge,map as We,merge as Ls,filterChanged as wu,isNonNullable as xu,Subject as dp,filter as In,mapTo as En,combine as pp,once as hp,shareReplay as Se,throttle as mp,ErrorCategory as fp,ValueSubject as ku,Subscription as bp}from"@vkontakte/videoplayer-shared/evergreen";var lp=3,Eu=(u,e,t=lp)=>{let i=0,r=0;for(let s=0;s<u.length;s++){let a=u.start(s),n=u.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)u.end(o)+t>=i&&(i=u.start(o));for(let o=s+1;o<u.length;o++)u.start(o)-t<=r&&(r=u.end(o))}}return{from:i,to:r}};var we=u=>{let e=E=>ge(u,E).pipe(En(void 0),Se(1)),t=new bp,i=()=>t.unsubscribe(),r=Ls(ge(u,"progress"),ge(u,"timeupdate")).pipe(We(()=>Eu(u.buffered,u.currentTime)),Se(1)),s=A.browser.isSafari?pp({play:e("play").pipe(hp()),playing:e("playing")}).pipe(En(void 0),Se(1)):e("playing"),a=ge(u,"volumechange").pipe(We(()=>({muted:u.muted,volume:u.volume})),Se(1)),n=ge(u,"ratechange").pipe(We(()=>u.playbackRate),Se(1)),o=ge(u,"error").pipe(In(()=>!!(u.error||u.played.length)),We(()=>{let E=u.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:fp.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:u.error??void 0}}),Se(1)),c=ge(u,"timeupdate").pipe(We(()=>u.currentTime),Se(1)),d=["waiting","seeking","seeked","timeupdate"],l=new dp,p=.3,h;t.add(Ls(...d.map(E=>ge(u,E))).subscribe(E=>{let F=u.currentTime;u.loop&&xu(h)&&xu(F)&&h>=u.duration-p&&F<=p&&l.next(h),h=F}));let m=e("pause").pipe(In(()=>!u.error&&h!==u.duration),Se(1)),f=ge(u,"enterpictureinpicture").pipe(Se(1)),b=ge(u,"leavepictureinpicture").pipe(Se(1)),g=new ku(Iu(u));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new ku(Tn(u)),T=ge(u,"fullscreenchange").pipe(Se(1));t.add(T.pipe(We(()=>Tn(u))).subscribe(S));let v=.1,x=1e3,$=ge(u,"timeupdate").pipe(We(E=>u.duration-u.currentTime<v),wu(),Se(1)),L=Ls($.pipe(In(E=>!u.loop&&E)),ge(u,"ended")).pipe(mp(x),En(void 0),Se(1)),R=Ls(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>ge(u,E)),$.pipe(We(E=>({type:E?"ended":"unknown"})))).pipe(We(E=>A.browser.isFirefox&&E.type==="ended"?u.readyState<2:u.readyState<3),wu(),Se(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:l,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ge(u,"durationchange").pipe(We(()=>u.duration),Se(1)),isBuffering$:R,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared/evergreen";var bt=u=>{switch(u){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};import{isNonNullable as q,isNullable as Bs,now as Ou,isHigher as Vs,isHigherOrEqual as Ft,isInvariantQuality as Os,isLowerOrEqual as li,videoSizeToQuality as Nu,assertNotEmptyArray as Ns,assertNonNullable as Fu}from"@vkontakte/videoplayer-shared/evergreen";var wn=!1,Ze={},Pu=u=>{wn=u},Mu=()=>{Ze={}},$u=u=>{u(Ze)},Wi=(u,e)=>{wn&&(Ze.meta=Ze.meta??{},Ze.meta[u]=e)},ve=class{constructor(e){this.name=e}next(e){if(!wn)return;Ze.series=Ze.series??{};let t=Ze.series[this.name]??[];t.push([Date.now(),e]),Ze.series[this.name]=t}};import{isHigher as gp,isHigherOrEqual as _v,isLower as Au,isLowerOrEqual as Uv,isNonNullable as Rs,isNullable as Sp,videoHeightToQuality as Ds}from"@vkontakte/videoplayer-shared/evergreen";function Lu(u,e,t){return!u.max&&u.min===e?"high_quality":!u.min&&u.max===t?"traffic_saving":"unknown"}function ci(u,e,t){return Sp(u)||Rs(u.min)&&Rs(u.max)&&Au(u.max,u.min)||Rs(u.min)&&e&&gp(u.min,e)||Rs(u.max)&&t&&Au(u.max,t)}function Ru({limits:u,highestAvailableHeight:e,lowestAvailableHeight:t}){return ci({max:u?.max?Ds(u.max):void 0,min:u?.min?Ds(u.min):void 0},e?Ds(e):void 0,t?Ds(t):void 0)}var _u=new ve("best_bitrate"),Fs=(u,e,t)=>(e-t)*Math.pow(2,-10*u)+t;var di=u=>(e,t)=>u*(Number(e.bitrate)-Number(t.bitrate)),gt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ou()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_s='Assertion "ABR Tracks is empty array" failed',Cs=new WeakMap,Du=new WeakMap,Cu=new WeakMap,Gi=(u,e,t,i)=>{let r=[...e].sort(di(1)),s=[...t].sort(di(1)),a=s.filter(o=>q(o.bitrate)&&q(u.bitrate)?u.bitrate/o.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Yi=(u,e,t,i)=>{let r=Cs.get(e);r||(r=[...e].sort(di(1)),Cs.set(e,r));let s=Cs.get(t);s||(s=[...t].sort(di(1)),Cs.set(t,s));let a=Cu.get(u);a||(a=s.filter(o=>q(o.bitrate)&&q(u.bitrate)?u.bitrate/o.bitrate>i:!0),Cu.set(u,a));let n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Bu=u=>"quality"in u,Us=(u,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?u.trackCooldownIncreaseQuality:u.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Ou()-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=Bu(a)?"video":"audio",o=Bu(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var _o="2.0.155";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),Xe=(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))(Xe||{}),Xa=(r=>(r.AV1="av1",r.VP9="vp9",r.AVC1="avc1",r.HEV1="hev1",r))(Xa||{});var Oi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Oi||{}),Ja=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ja||{});var Za=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Za||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});import{assertNever as qo,assertNonNullable as od,isNonNullable as gs,ValueSubject as en,Subject as ud,Subscription as cd,merge as ld,observableFrom as dd,fromEvent as Ho,map as jo,tap as Qo,filterChanged as pd,isNullable as tn,ErrorCategory as zo}from"@vkontakte/videoplayer-shared/evergreen";var Uo=u=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",u),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ss=class{constructor(e){this.connection$=new en(void 0);this.castState$=new en("NOT_AVAILABLE");this.errorEvent$=new ud;this.realCastState$=new en("NOT_AVAILABLE");this.subscription=new cd;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=gs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Uo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zo.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(){gs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();tn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();tn(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(Ho(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 qo(r.sessionState)}})).add(ld(Ho(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),jo(r=>r.castState)),dd([i.getCastState()])).pipe(pd(),jo(hd),Qo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=gs(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();od(n);let o=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(tn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?gs(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:zo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},hd=u=>{switch(u){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return qo(u)}};import{assertNonNullable as un,combine as cn,debounce as ln,ErrorCategory as Rd,filter as ni,filterChanged as su,isNonNullable as dn,isNullable as au,map as Dd,Subscription as Cd,ValueSubject as pn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as md,assertNonNullable as Bt,ErrorCategory as fd,getHighestQuality as bd,isNonNullable as Go}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Wo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(u,e=0,t=0)=>{switch(t){case 0:return u.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return u;let i=new URL(u);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(u);return!i.searchParams.get("offset_p")&&e===0?u:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Wo(t)}return u},mt=(u,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(u);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(u);return Number(t.searchParams.get("offset_p")??0)}default:Wo(e)}};var ys=u=>{let{source:e,format:t,meta:i,output:r}=u,s,a,n;switch(t){case"MPEG":{let l=e[t];Bt(l);let p=bd(Object.keys(l));Bt(p);let h=l[p];Bt(h),s=h,a="video/mp4",n=vs();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];Bt(l),s=l.url,a="application/x-mpegurl",n=vs();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];Bt(l),s=l.url,a="application/dash+xml",n=vs();break}case"DASH_LIVE_CMAF":{let l=e[t];Bt(l),s=l.url,a="application/dash+xml",n=Yo();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];Bt(l),s=ee(l.url),a="application/x-mpegurl",n=Yo();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:fd.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return md(t)}let o=gd(i.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=Sd();let{title:c,subtitle:d}=i;return Go(c)&&(o.metadata.title=c),Go(d)&&(o.metadata.subtitle=d),o};function vs(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Yo(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function gd(u,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(u,e):{contentId:u,contentType:e,metadata:{title:"",subtitle:""},streamType:vs()}}function Sd(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var w=(u,e,t=!1)=>{let i=u.getTransition();(t||!i||i.to===e)&&u.setState(e)};var Ts=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 ru}from"@vkontakte/videoplayer-shared/evergreen";import{isBrowserWindow as $d,ValueSubject as Ad}from"@vkontakte/videoplayer-shared/evergreen";import{getWindow as vd}from"@vkontakte/videoplayer-shared/evergreen";var Is=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,n=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||c||r||s||n||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=vd().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 rn,isBrowserWindow as sn}from"@vkontakte/videoplayer-shared/evergreen";var Vt=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Es=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=rn();if(!sn(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Vt()}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=rn();if(!sn(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||a||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r.length>0,n=r.length>1,o="Unknown",c="Unknown";if(a){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(o=s[d]):o=d}if(n){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&a&&typeof r[0]=="string"&&(c=s[1]);o=this.normalizeOSName(o),c=this.normalizeOSVersion(c,o),o==="iOS"&&/ipad/i.test(e)?o="iPadOS":o==="iPadOS"&&/ip(hone|od)/i.test(e)&&(o="iOS"),this._os={name:o,version:c||"Unknown",full:c&&c!=="Unknown"?`${o} ${c}`:o};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r[0],n=r[1],o=typeof a=="number"?s[a]!==void 0?this.normalizeVendorName(s[a]):"Unknown":this.normalizeVendorName(a),c="Unknown";typeof n=="number"?c=s[n]!==void 0?s[n]:"Unknown":n!==void 0?c=n:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,o),this.details.vendor=o,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=rn();if(!sn(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 Ko,isBrowserWindow as yd}from"@vkontakte/videoplayer-shared/evergreen";var ws=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Ko()}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=Ko();if(!yd(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 an,isBrowserWindow as Jo}from"@vkontakte/videoplayer-shared/evergreen";var Pe=()=>window.ManagedMediaSource||window.MediaSource,ai=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Xo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ks=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Td=an().document?.createElement("video"),Id='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ed='video/mp4; codecs="hev1.1.6.L93.B0"',Zo='video/webm; codecs="vp09.00.10.08"',eu='video/webm; codecs="av01.0.00M.08"',wd='audio/mp4; codecs="mp4a.40.2"',kd='audio/webm; codecs="opus"',tu,xd=async()=>{let u=an();if(!Jo(u))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:eu}}),u.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Zo}})]);tu={DASH_WEBM_AV1:t,DASH_WEBM:i}};xd().catch(u=>{console.log(Td),console.error(u)});var xs=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 tu}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=an();if(!Jo(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:ai(),mse:Xo(),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?.(Id),r=!!Pe()?.isTypeSupported?.(Ed),s=!!Pe()?.isTypeSupported?.(wd);this._codecs={h264:i,h265:r,vp9:!!Pe()?.isTypeSupported?.(Zo),av1:!!Pe()?.isTypeSupported?.(eu),aac:s,opus:!!Pe()?.isTypeSupported?.(kd),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 Pd,isBrowserWindow as Md}from"@vkontakte/videoplayer-shared/evergreen";var iu="audio/mpeg",Ps=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=Pd();if(!Md(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(iu)},this._codecs={mp3:!!Pe()?.isTypeSupported?.(iu)}}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 nn=class{constructor(){this.isInited$=new Ad(!1);this._displayChecker=new ws,this._deviceChecker=new Es(this._displayChecker),this._browserChecker=new Is,this._videoChecker=new xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Ps,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(){$d()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},A=new nn;var on=u=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=A.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return u.filter(n=>{switch(n){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return ru(n)}})},Ni=u=>{switch(u){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ru(u)}},Ld=u=>{let t=Object.keys(u).filter(i=>!Ni(i));return on(t).length>0};var Fi=class{constructor(e){this.subscription=new Cd;this.sessionId$=new pn(null);this.mediaSessionId$=new pn(null);this.contentId$=new pn(null);this.isMobile=Vt();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(au(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;dn(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(dn(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 Ts(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ni(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:Rd.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ni(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(ni(dn),su(),ln(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(su(),Dd(Boolean));this.subscription.add(cn({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ni(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=cn({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(ni(({mediaLoaded:r})=>r),ln(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(ni(({mediaLoaded:r,playbackState:{from:s,to:a}})=>!r&&s==="stopped"&&a==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(cn({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ln(30)),mediaLoaded:t}).pipe(ni(({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=ys(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();un(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();un(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();un(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(au(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 Bd,ErrorCategory as hn,filter as Vd,Subject as Od,Subscription as mn,tap as Nd,ValueSubject as oi,fromEvent as _i}from"@vkontakte/videoplayer-shared/evergreen";var nu=u=>({castDevice:{friendlyName:u},remotePlayer:{},remotePlayerController:{},session:{}}),ou=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ui=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new oi(null);this.sessionId$=new oi(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new mn;this.subscriptionEvents=new mn;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new oi(!1);this.presentationConnection$=new oi(null);this.message$=new oi(null);this.friendlyName$=new oi(null);this.errorEvent$=new Od;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(_i(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();Bd(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:hn.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(_i(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(Nd(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Vd(e=>!!e)).subscribe(e=>{let t=_i(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=_i(e,"connect").subscribe(()=>{this.send("client_connect")}),r=_i(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:hn.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:hn.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]||ou()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new mn}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 uu,Subject as Fd,map as _d,Subscription as Ud,combine as Hd,filterChanged as cu,assertNonNullable as jd}from"@vkontakte/videoplayer-shared/evergreen";var Je=class u{constructor(e){this.subscription=new Ud;this.connection$=new uu(void 0);this.castState$=new uu("NOT_AVAILABLE");this.errorEvent$=new Fd;let t=u.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ui({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){jd(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Hd({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(cu())});this.subscription.add(e.pipe(_d(({connection:t,friendlyName:i})=>!!(t&&i)),cu()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?nu(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 Qd,Subject as Ms,merge as lu}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new Ms;this.transitionEnded$=new Ms;this.transitionUpdated$=new Ms;this.forceChanged$=new Ms;this.stateChangeStarted$=lu(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=lu(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||Qd(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 Hi,debounce as du,ErrorCategory as zd,fromEvent as Ot,map as pu,merge as hu,observableFrom as qd,Subject as Wd,Subscription as fn,timeout as Gd}from"@vkontakte/videoplayer-shared/evergreen";var Yd=5,Kd=5,Xd=500,mu=7e3,ji=class{constructor(e){this.subscription=new fn;this.loadMediaTimeoutSubscription=new fn;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:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ni(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 fn;this.subscription.add(e),this.subscription.add(hu(this.videoState.stateChangeStarted$.pipe(pu(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(pu(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 Wd;e.add(r.pipe(du(Xd)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ot(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)>Yd)&&r.next(n),s=n})),e.add(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Kd&&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:Hi(a)}}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=hu(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qd(["init"])).pipe(du(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=ys(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(Gd(mu).subscribe(()=>s(`timeout(${mu})`)))});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:zd.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as bu,getWindow as Zd}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Jd}from"@vkontakte/videoplayer-shared/evergreen";var fu=(u,e)=>{try{u.pause(),u.playbackRate=0,Jd(u,e),u.remove()}catch(t){console.error(t)}};import{fromEvent as ep,Subscription as tp}from"@vkontakte/videoplayer-shared/evergreen";var bn=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)}},$s=Zd(),gn=$s.WeakMap?new $s.WeakMap:new bn,Sn=$s.WeakMap?new $s.WeakMap:new Map,ip=(u,e=20)=>{let t=0;return ep(u,"ratechange").subscribe(i=>{t++,t>=e&&(u.currentTime=u.currentTime,t=0)})},Te=(u,{audioVideoSyncRate:e,disableYandexPiP:t,clearVideoElementInnerHTML:i})=>{let r=u.querySelector("video"),s=!!r;r?bu(r,i):(r=document.createElement("video"),u.appendChild(r)),gn.set(r,s);let a=new tp;return a.add(ip(r,e)),Sn.set(r,a),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ie=(u,e=!1,t=!1)=>{Sn.get(u)?.unsubscribe(),Sn.delete(u);let r=gn.get(u);gn.delete(u),r||e?bu(u,t):fu(u,t)};import{assertNonNullable as zi,isNonNullable as qe,isNullable as ap,fromEvent as ui,merge as gu,observableFrom as Su,filterChanged as vu,map as qi,Subject as yu,Subscription as np,ValueSubject as op,ErrorCategory as up}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as vn,isNullable as rp,Subscription as sp}from"@vkontakte/videoplayer-shared/evergreen";var As=(u,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=u.getState(),n=e(),o=rp(r),c=new sp;return r&&c.add(r.subscribe(d=>{let l=u.getState();i(d,l)&&u.setState(d)},s)),i(n,a)||(t(a),o&&u.setState(a)),c.add(u.stateChangeStarted$.subscribe(d=>{t(d.to),o&&u.setState(d.to)},s)),c},ze=(u,e,t)=>As(e,()=>u.loop,i=>{vn(i)&&(u.loop=i)},{onError:t}),Ee=(u,e,t,i)=>As(e,()=>({muted:u.muted,volume:u.volume}),r=>{vn(r)&&(u.muted=r.muted,u.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(u,e,t,i)=>As(e,()=>u.playbackRate,r=>{vn(r)&&(u.playbackRate=r)},{changed$:t,onError:i}),Qi=As;var cp=u=>["__",u.language,u.label].join("|"),lp=(u,e)=>{if(u.id===e)return!0;let[t,i,r]=e.split("|");return u.language===i&&u.label===r},yn=class u{constructor(e){this.available$=new yu;this.current$=new op(void 0);this.error$=new yu;this.subscription=new np;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:up.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(Qi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{qe(s)&&this.setInternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Qi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{qe(s)&&this.setExternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Qi(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(Qi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){zi(this.video);let{textTracks:e}=this.video;this.subscription.add(ui(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(gu(ui(e,"addtrack"),ui(e,"removetrack"),Su(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),vu((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(gu(ui(e,"change"),Su(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),qi(i=>i&&this.htmlTextTrackToITextTrack(i).id),vu()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ui(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(ui(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;qe(t.align)&&(r.align=t.align),qe(t.position)&&(r.position=t.position),qe(t.size)&&(r.size=t.size),qe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){zi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(u.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:cp(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){zi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ap(e)||!lp(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){zi(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){zi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ce=yn;var Nt=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 Tu=u=>{let e=u;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Tn=u=>{let e=Tu(u);return!!(e&&e.fullscreenElement&&e.fullscreenElement===u)},Iu=u=>{let e=Tu(u);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===u)};import{fromEvent as ge,map as We,merge as Ls,filterChanged as wu,isNonNullable as ku,Subject as pp,filter as In,mapTo as En,combine as hp,once as mp,shareReplay as Se,throttle as fp,ErrorCategory as bp,ValueSubject as xu,Subscription as gp}from"@vkontakte/videoplayer-shared/evergreen";var dp=3,Eu=(u,e,t=dp)=>{let i=0,r=0;for(let s=0;s<u.length;s++){let a=u.start(s),n=u.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)u.end(o)+t>=i&&(i=u.start(o));for(let o=s+1;o<u.length;o++)u.start(o)-t<=r&&(r=u.end(o))}}return{from:i,to:r}};var we=u=>{let e=E=>ge(u,E).pipe(En(void 0),Se(1)),t=new gp,i=()=>t.unsubscribe(),r=Ls(ge(u,"progress"),ge(u,"timeupdate")).pipe(We(()=>Eu(u.buffered,u.currentTime)),Se(1)),s=A.browser.isSafari?hp({play:e("play").pipe(mp()),playing:e("playing")}).pipe(En(void 0),Se(1)):e("playing"),a=ge(u,"volumechange").pipe(We(()=>({muted:u.muted,volume:u.volume})),Se(1)),n=ge(u,"ratechange").pipe(We(()=>u.playbackRate),Se(1)),o=ge(u,"error").pipe(In(()=>!!(u.error||u.played.length)),We(()=>{let E=u.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:bp.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:u.error??void 0}}),Se(1)),c=ge(u,"timeupdate").pipe(We(()=>u.currentTime),Se(1)),d=["waiting","seeking","seeked","timeupdate"],l=new pp,p=.3,h;t.add(Ls(...d.map(E=>ge(u,E))).subscribe(E=>{let F=u.currentTime;u.loop&&ku(h)&&ku(F)&&h>=u.duration-p&&F<=p&&l.next(h),h=F}));let m=e("pause").pipe(In(()=>!u.error&&h!==u.duration),Se(1)),f=ge(u,"enterpictureinpicture").pipe(Se(1)),b=ge(u,"leavepictureinpicture").pipe(Se(1)),g=new xu(Iu(u));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new xu(Tn(u)),I=ge(u,"fullscreenchange").pipe(Se(1));t.add(I.pipe(We(()=>Tn(u))).subscribe(S));let v=.1,k=1e3,$=ge(u,"timeupdate").pipe(We(E=>u.duration-u.currentTime<v),wu(),Se(1)),L=Ls($.pipe(In(E=>!u.loop&&E)),ge(u,"ended")).pipe(fp(k),En(void 0),Se(1)),R=Ls(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>ge(u,E)),$.pipe(We(E=>({type:E?"ended":"unknown"})))).pipe(We(E=>A.browser.isFirefox&&E.type==="ended"?u.readyState<2:u.readyState<3),wu(),Se(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:l,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ge(u,"durationchange").pipe(We(()=>u.duration),Se(1)),isBuffering$:R,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared/evergreen";var bt=u=>{switch(u){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};import{isNonNullable as q,isNullable as Bs,now as Ou,isHigher as Vs,isHigherOrEqual as Ft,isInvariantQuality as Os,isLowerOrEqual as li,videoSizeToQuality as Nu,assertNotEmptyArray as Ns,assertNonNullable as Fu}from"@vkontakte/videoplayer-shared/evergreen";var wn=!1,Ze={},Pu=u=>{wn=u},Mu=()=>{Ze={}},$u=u=>{u(Ze)},Wi=(u,e)=>{wn&&(Ze.meta=Ze.meta??{},Ze.meta[u]=e)},ve=class{constructor(e){this.name=e}next(e){if(!wn)return;Ze.series=Ze.series??{};let t=Ze.series[this.name]??[];t.push([Date.now(),e]),Ze.series[this.name]=t}};import{isHigher as Sp,isHigherOrEqual as Uv,isLower as Au,isLowerOrEqual as Hv,isNonNullable as Rs,isNullable as vp,videoHeightToQuality as Ds}from"@vkontakte/videoplayer-shared/evergreen";function Lu(u,e,t){return!u.max&&u.min===e?"high_quality":!u.min&&u.max===t?"traffic_saving":"unknown"}function ci(u,e,t){return vp(u)||Rs(u.min)&&Rs(u.max)&&Au(u.max,u.min)||Rs(u.min)&&e&&Sp(u.min,e)||Rs(u.max)&&t&&Au(u.max,t)}function Ru({limits:u,highestAvailableHeight:e,lowestAvailableHeight:t}){return ci({max:u?.max?Ds(u.max):void 0,min:u?.min?Ds(u.min):void 0},e?Ds(e):void 0,t?Ds(t):void 0)}var _u=new ve("best_bitrate"),Fs=(u,e,t)=>(e-t)*Math.pow(2,-10*u)+t;var di=u=>(e,t)=>u*(Number(e.bitrate)-Number(t.bitrate)),gt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ou()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_s='Assertion "ABR Tracks is empty array" failed',Cs=new WeakMap,Du=new WeakMap,Cu=new WeakMap,Gi=(u,e,t,i)=>{let r=[...e].sort(di(1)),s=[...t].sort(di(1)),a=s.filter(o=>q(o.bitrate)&&q(u.bitrate)?u.bitrate/o.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Yi=(u,e,t,i)=>{let r=Cs.get(e);r||(r=[...e].sort(di(1)),Cs.set(e,r));let s=Cs.get(t);s||(s=[...t].sort(di(1)),Cs.set(t,s));let a=Cu.get(u);a||(a=s.filter(o=>q(o.bitrate)&&q(u.bitrate)?u.bitrate/o.bitrate>i:!0),Cu.set(u,a));let n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Bu=u=>"quality"in u,Us=(u,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?u.trackCooldownIncreaseQuality:u.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Ou()-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=Bu(a)?"video":"audio",o=Bu(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),a}return i?.recordSwitch(t),t},
|
|
8
|
+
`}),a}return i?.recordSwitch(t),t},yp=(u,e)=>Math.log(e)/Math.log(u),Uu=({tuning:u,container:e,limits:t,panelSize:i})=>{let r=u.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(u.usePixelRatio&&A.display.pixelRatio){let s=A.display.pixelRatio;if(u.pixelRatioMultiplier)r*=u.pixelRatioMultiplier*(s-1)+1;else{let a=u.pixelRatioLogBase,[n=0,o=0,c=0]=u.pixelRatioLogCoefficients,d=yp(a,n*s+o)+c;Number.isFinite(d)&&(r*=d)}}return q(t?.min)&&Ft(t.min,u.highQualityLimit)&&(r*=2),{containerSizeLimit:u.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Vu=new WeakMap,Ge=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{Ns(u,_s);let{containerSizeFactor:b,containerSizeLimit:g}=Uu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(n)?n:1,I=Vu.get(u);I||(I=u.filter(T=>!Os(T.quality)).sort((T,y)=>Vs(T.quality,y.quality)?-1:1),Vu.set(u,I));let v=I.at(-1)?.quality,k=I.at(0)?.quality,$=ci(r,k,v),L=S*Fs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},R=null;for(let T of I){if(T.tvDisabled){x[T.quality]="TvDisabled";continue}let y=!0;if(g)if(T.size)y=T.size.width<=g.width&&T.size.height<=g.height;else{let U=g&&Nu(g);y=U?li(T.quality,U):!0}if(!y){x[T.quality]="FitsContainer";continue}let V=h||t,M=q(V)&&isFinite(V)&&q(T.bitrate)?V-s>=T.bitrate*L:!0,_=r?.min===T.quality;if(!M&&!_){x[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&o&&!Os(o.quality)&&(a??0)<i.minBufferToSwitchUp&&Vs(T.quality,o.quality)){x[T.quality]="Buffer";continue}if(!!l&&Ft(T.quality,l)&&!_){x[T.quality]="DroppedFramesLimit";continue}if(!!p&&Ft(T.quality,p)&&!_){x[T.quality]="StallsLimit";continue}let le=$||(Bs(r?.max)||li(T.quality,r.max))&&(Bs(r?.min)||Ft(T.quality,r.min)),de=q(d)&&!d?li(T.quality,i.backgroundVideoQualityLimit):!0;if(!le||!de){x[T.quality]="FitsQualityLimits";continue}R||(R=T)}R&&R.bitrate&&_u.next(R.bitrate);let E=R??I.at(-1)??u[0],F=c?.last,C=Us(i,m,E,c);return q(c)&&C.quality!==F?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${u.map(
|
|
11
|
+
${u.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i??{}).map(([
|
|
15
|
+
${Object.entries(i??{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -33,12 +33,12 @@ var _o="2.0.154-dev.ffe03d52.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
33
33
|
minQualityLimit: ${r?.min},
|
|
34
34
|
|
|
35
35
|
[limited video tracks]
|
|
36
|
-
${Object.entries(
|
|
36
|
+
${Object.entries(x).map(([T,y])=>`${T}: ${y}`).join(`
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
39
|
[best video track] ${R?.quality}
|
|
40
40
|
[selected video track] ${C?.quality}
|
|
41
|
-
`}),C},Hs=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{Ns(u,_s);let{containerSizeFactor:b,containerSizeLimit:g}=Uu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(n)?n:1,
|
|
41
|
+
`}),C},Hs=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{Ns(u,_s);let{containerSizeFactor:b,containerSizeLimit:g}=Uu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(n)?n:1,I=u.filter(y=>!Os(y.quality)).sort((y,V)=>Vs(y.quality,V.quality)?-1:1),v=I.at(-1)?.quality,k=I.at(0)?.quality,$=ci(r,k,v),L=S*Fs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},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&&Nu(g);V=N?li(y.quality,N):!0}if(!V)return x[y.quality]="FitsContainer",!1;let M=h||t,_=q(M)&&isFinite(M)&&q(y.bitrate)?M-s>=y.bitrate*L:!0,W=r?.min===y.quality;if(!_&&!W)return x[y.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&o&&!Os(o.quality)&&(a??0)<i.minBufferToSwitchUp&&Vs(y.quality,o.quality))return x[y.quality]="Buffer",!1;if(!!l&&Ft(y.quality,l)&&!W)return x[y.quality]="DroppedFramesLimit",!1;if(!!p&&Ft(y.quality,p)&&!W)return x[y.quality]="StallsLimit",!1;let de=$||(Bs(r?.max)||li(y.quality,r.max))&&(Bs(r?.min)||Ft(y.quality,r.min)),U=q(d)&&!d?li(y.quality,i.backgroundVideoQualityLimit):!0;return!de||!U?(x[y.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&_u.next(E.bitrate);let F=E??I.at(-1)??u[0],C=c?.last,T=Us(i,m,F,c);return q(c)&&T.quality!==C?.quality&&m({message:`
|
|
42
42
|
[VIDEO TRACKS ABR]
|
|
43
43
|
[available video tracks]
|
|
44
44
|
${u.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate}, size: ${y.size?.width}:${y.size?.height} }`).join(`
|
|
@@ -66,19 +66,19 @@ var _o="2.0.154-dev.ffe03d52.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
66
66
|
minQualityLimit: ${r?.min},
|
|
67
67
|
|
|
68
68
|
[limited video tracks]
|
|
69
|
-
${Object.entries(
|
|
69
|
+
${Object.entries(x).map(([y,V])=>`${y}: ${V}`).join(`
|
|
70
70
|
`)||"All tracks are available"}
|
|
71
71
|
|
|
72
72
|
[best video track] ${E?.quality}
|
|
73
|
-
[selected video track] ${
|
|
74
|
-
`}),
|
|
73
|
+
[selected video track] ${T?.quality}
|
|
74
|
+
`}),T},js=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ns(t,_s);let d=r.considerPlaybackRate&&q(s)?s:1,l=[...t].sort(di(-1)),p=u.bitrate;Fu(p);let h=d*Fs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Gi(u,e,t,r.minVideoAudioRatio),b=c||i;q(b)&&isFinite(b)&&(m=l.find(I=>q(I.bitrate)&&q(f?.bitrate)?b-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Us(r,o,m,n);return q(n)&&S?.bitrate!==g?.bitrate&&o({message:`
|
|
75
75
|
[AUDIO TRACKS ABR]
|
|
76
76
|
[available audio tracks]
|
|
77
|
-
${t.map(
|
|
77
|
+
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
78
78
|
`)}
|
|
79
79
|
|
|
80
80
|
[tuning]
|
|
81
|
-
${Object.entries(r??{}).map(([
|
|
81
|
+
${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
|
|
82
82
|
`)}
|
|
83
83
|
|
|
84
84
|
[limit params]
|
|
@@ -92,14 +92,14 @@ var _o="2.0.154-dev.ffe03d52.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
92
92
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
93
93
|
|
|
94
94
|
[selected audio track] ${S?.id}
|
|
95
|
-
`}),S},Qs=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ns(t,_s);let d=r.considerPlaybackRate&&q(s)?s:1,l=Du.get(t);l||(l=[...t].sort(di(-1)),Du.set(t,l));let p=u.bitrate;Fu(p);let h=d*Fs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Yi(u,e,t,r.minVideoAudioRatio),b=c||i;q(b)&&isFinite(b)&&(m=l.find(
|
|
95
|
+
`}),S},Qs=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ns(t,_s);let d=r.considerPlaybackRate&&q(s)?s:1,l=Du.get(t);l||(l=[...t].sort(di(-1)),Du.set(t,l));let p=u.bitrate;Fu(p);let h=d*Fs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Yi(u,e,t,r.minVideoAudioRatio),b=c||i;q(b)&&isFinite(b)&&(m=l.find(I=>q(I.bitrate)&&q(f?.bitrate)?b-p>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Us(r,o,m,n);return q(n)&&S?.bitrate!==g?.bitrate&&o({message:`
|
|
96
96
|
[AUDIO TRACKS ABR]
|
|
97
97
|
[available audio tracks]
|
|
98
|
-
${t.map(
|
|
98
|
+
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
99
99
|
`)}
|
|
100
100
|
|
|
101
101
|
[tuning]
|
|
102
|
-
${Object.entries(r??{}).map(([
|
|
102
|
+
${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
|
|
103
103
|
`)}
|
|
104
104
|
|
|
105
105
|
[limit params]
|
|
@@ -113,7 +113,7 @@ var _o="2.0.154-dev.ffe03d52.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
113
113
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
114
114
|
|
|
115
115
|
[selected audio track] ${S?.id}
|
|
116
|
-
`}),S};var he=u=>new URL(u).hostname;import{assertNever as Gu,assertNonNullable as Yu,combine as jp,debounce as Qp,ErrorCategory as Ku,filter as Xu,filterChanged as zp,isNonNullable as An,map as Gs,merge as Ju,observableFrom as qp,once as Wp,Subscription as Gp,ValueSubject as Ln,videoQualityToHeight as Zu,videoSizeToQuality as Yp}from"@vkontakte/videoplayer-shared/evergreen";var Hu=u=>{if(u instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(u.message))throw u;return!(u instanceof DOMException&&(u.code===20||u.name==="AbortError"))},xe=async(u,e)=>{let t=u.muted;try{await u.play()}catch(i){if(!Hu(i))return!1;if(e&&e(),t)return console.warn(i),!1;u.muted=!0;try{await u.play()}catch(r){return Hu(r)&&(u.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as qs,isNullable as xp,assertNonNullable as Ji}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ju,assertNonNullable as zs,now as yp}from"@vkontakte/videoplayer-shared/evergreen";function ne(){return yp()}function xn(u){return ne()-u}function kn(u){let e=u.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,o=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let c=a.indexOf("?")>-1?"&":"?";return o&&(a+=c+"lowLat=1",c="&"),n&&(a+=c+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Qu(u,e,t){let i=(...r)=>{t.apply(null,r),u.removeEventListener(e,i)};u.addEventListener(e,i)}function pi(u,e,t,i){let r=window.XMLHttpRequest,s,a,n,o=!1,c=0,d,l,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;zs(d);let C=xn(d),I;if(C<f){I=f-C,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,$()},g=C=>(s=C,F),S=C=>(l=C,F),T=()=>(h="json",F),v=()=>{if(!o){if(--c>=0){b(),i&&i();return}o=!0,l&&l(),t&&t()}},x=C=>(p=C,F),$=()=>{d=ne(),a=new r,a.open("get",u);let C=0,I,y=0,V=()=>(zs(d),Math.max(d,Math.max(I||0,y||0)));if(s&&a.addEventListener("progress",M=>{let _=ne();s.updateChunk&&M.loaded>C&&(s.updateChunk(V(),M.loaded-C),C=M.loaded,I=_)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;zs(a);let M=a.status;if(M>=200&&M<300){let{response:_,responseType:W}=a,Z=_?.byteLength;if(typeof Z=="number"&&s){let ie=Z-C;ie&&s.updateChunk&&s.updateChunk(V(),ie)}W==="json"&&(!_||!Object.values(_).length)?v():(l&&l(),e(_))}else v()}),a.addEventListener("error",()=>{v()}),p){let M=()=>{zs(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(y=ne(),a.removeEventListener("readystatechange",M))};a.addEventListener("readystatechange",M)}return a.responseType=h,a.send(),F},F={withBitrateReporting:g,withParallel:x,withJSONResponse:T,withRetryCount:C=>(c=C,F),withRetryInterval:(C,I)=>(ju(C)&&(f=C),ju(I)&&(m=I),F),withTimeout:C=>(n=C,F),withFinally:S,send:$,abort:()=>{a&&(a.abort(),a=void 0),o=!0,l&&l()}};return F}var Ki=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,n=s.end-s.start;i+=a;let o=s.bytes*a/n;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Xi=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ne(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=ne()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pi(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=ne()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ne();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let 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 kp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as zu}from"@vkontakte/videoplayer-shared/evergreen";var Y=(u,e)=>zu(u)&&zu(e)&&u.readyState==="open"&&Tp(u,e);function Tp(u,e){for(let t=0;t<u.activeSourceBuffers.length;++t)if(u.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Ip}from"@vkontakte/videoplayer-shared/evergreen";var Pn=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=(u,e="warn")=>{let t=Ip(),i=[];function r(s,a=!1){let n=t.performance?.timing?.navigationStart??0,o=new Pn(u,Math.round((Date.now()-n)/1e3),s,a?new Error().stack:void 0);i.push(o),e&&t.console[e](o.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},D=Ep("vp_dash_live_debug",!1);var Ws=1e4,Mn=3;var Pp=6e4,Mp=10,$p=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 kp,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=kn(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&&(D({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",D({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()?(D({m:"ldp.play.1"}),this._playVideoElement()):(D({m:"ldp.play.2"}),this._notifyBuffering(!0))):(D({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,D({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=kn(e),D({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;D({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(D({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"),D({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(A.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:o,min:c}=this.autoQualityLimits||{};!Ru({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(o&&s.video.height>o||c&&s.video.height<c)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||qs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{if(this.mediaSource?.readyState!=="open"){D({m:"sourceopen",err:`not open: ${this.mediaSource?.readyState}`});return}D({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t()}),this.mediaSource?.addEventListener("sourceclose",n=>{D({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{D({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{Qu(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 Xi(Mn,Ws,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,n=null,o=null,c=null,d=!1,l=()=>{let v=s&&(!d||d===this.rep);return v||t("Not running!"),v},p=(v,x,$)=>{o&&o.abort(),o=pi(this.urlResolver.resolve(v,!1),x,$,()=>this._retryCallback()).withTimeout(Ws).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mn).withFinally(()=>{o=null}).send()},h=(v,x,$)=>{Ji(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),x,$,()=>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 $=ne()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let E=this.bufferStates[R];v=Math.min(v,E.buf),E.ts<$&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${v} drop=${L} jitter=${this.sourceJitter}`);let k=v-$p;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,$=()=>x&&x.start?x.start.length:0,L=M=>x.start[M]/1e3,k=M=>x.dur[M]/1e3,R=M=>x.fragIndex+M,E=(M,_)=>({chunkIdx:R(M),startTS:L(M),dur:k(M),discontinuity:_}),F=()=>{let M=0;if(x&&x.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=_;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ie=x.dur.length-1;for(;ie>=0&&(Z-=x.dur[ie],!(Z<=0));--ie);M=Math.min(ie,x.dur.length-1-W),M=Math.max(M,0)}return E(M,!0)},C=M=>{let _=$();if(!(_<=0)){if(qs(M)){for(let W=0;W<_;W++)if(L(W)>M)return E(W)}return F()}},I=M=>{let _=$(),W=M?M.chunkIdx+1:0,Z=W-x.fragIndex;if(!(_<=0)){if(!M||Z<0||Z-_>Mp)return t(`Resync: offset=${Z} bChunks=${_} chunk=`+JSON.stringify(M)),F();if(!(Z>=_))return E(W-x.fragIndex,!1)}},y=(M,_,W)=>{c&&c.abort(),c=pi(this.urlResolver.resolve(M,!0,this.lowLatency),_,W,()=>this._retryCallback()).withTimeout(Ws).withRetryCount(Mn).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(M,_)=>{y(v,W=>{if(!l())return;x=W;let Z=!!x.lowLatency;Z!==this.lowLatency&&f(Z);let ie=0;for(let le=0;le<x.dur.length;++le)ie+=x.dur[le];ie>0&&(Ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,M(C(_))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,n&&n.abort(),o&&o.abort(),c&&c.abort(),Ji(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:v=>{let{videoElement:x,logger:$}=this.params,L=g(e.jidxUrl),k,R,E,F,C=0,I,y,V,M=()=>{I&&(clearTimeout(I),I=void 0);let N=Math.max(Ap,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),pe=C+N,me=ne(),ae=Math.min(1e4,pe-me);C=me;let Ae=()=>{c||l()&&L.seek(()=>{l()&&(C=ne(),_(),M())})};ae>0?I=window.setTimeout(()=>{this.paused?M():Ae()},ae):Ae()},_=()=>{let N;for(;N=L.nextChunk(F);)F=N,de(N);let pe=L.nextChunk(E);if(pe){if(E&&pe.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?M():(S(),D({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}le(pe)}else M()},W=(N,pe)=>{if(!l()||!this.sourceBuffer){D({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let me,ae,Ae,lt=Oe=>{D({m:"ldp.postpone",t:Oe}),window.setTimeout(()=>{l()&&W(N,pe)},Oe)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),D({m:"ldp.ab.1"}),lt(100);else{let Oe=ne(),ke=x.currentTime;!this.paused&&x.buffered.length>1&&y===ke&&Oe-V>500&&($("Stall suspected; trying to fix"),this._fixupStall()),y!==ke&&(y=ke,V=Oe);let dt=this._getBufferSizeSec();if(dt>30)D({m:"ldp.ab.3"}),$(`Buffered ${dt} seconds; delaying appendBuffer`),lt(2e3);else try{if(this.params.config.useInvalidBufferFix&&Y(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(D({m:"ldp.ab.5"}),this.bufferStates.push({ts:Oe,buf:dt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(D({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),pe&&pe()}catch(Le){D({m:"ldp.ab.err",e:Le.name}),Le.name==="QuotaExceededError"?($("QuotaExceededError; delaying appendBuffer"),Ae=this.sourceBuffer.buffered.length,Ae!==0&&(me=this.sourceBuffer.buffered.start(0),ae=ke,ae-me>4&&this.sourceBuffer.remove(me,ae-3)),lt(1e3)):($(Le.name),r({name:"error",type:"buffer",message:`appendBuffer failed due to ${Le.name}`}))}}},Z=()=>{R&&k&&($([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(E)]),W(R,function(){R=null,_()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),le=N=>{l()&&h(ie(N),(pe,me)=>{if(l()){if(me/=1e3,R=pe,E=N,a=N.startTS,me){let ae=Math.min(10,N.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ae:ae}Z()}},()=>this._handleNetworkError())},de=N=>{l()&&(Ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},U=N=>{l()&&(e.cachedHeader=N,W(N,()=>{k=!0,Z()}))};s=!0,L.seek(N=>{if(l()){if(C=ne(),!N){M();return}F=N,!xp(v)||N.startTS>v?le(N):(E=N,_())}},v),e.cachedHeader?U(e.cachedHeader):p(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),qs(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return qs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let 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}`)},s={updateChunk:(p,h)=>{let m=ne();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,o=!0,c=()=>{let l=s.get();if(l&&n&&this.autoQuality){if(o&&l>n&&xn(a)<3e4)return;i(l)}o=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=ne();l<n&&(a=p),n=l}}}_fetchManifest(e,t,i){this.manifestRequest=pi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ws).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=>{D({m:"ldp.pve.1"}),t||(D({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let n=[];return a?.length?(a.forEach((o,c)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=c,n.push(o))}),n.sort(function(o,c){return o.video&&c.video?c.video.height-o.video.height:c.bitrate-o.bitrate}),n):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Pp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Lp,filter as qu,fromEvent as Rp,interval as Dp,isHigher as Cp,isInvariantQuality as Bp,isLower as Vp,merge as Op,Subject as Wu,Subscription as Np}from"@vkontakte/videoplayer-shared/evergreen";var $n=class{constructor(){this.onDroopedVideoFramesLimit$=new Wu;this.subscription=new Np;this.playing=!1;this.tracks=[];this.forceChecker$=new Wu;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&&!Bp(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Cp(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Rp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Dp(this.droppedFramesChecker.checkTime).pipe(qu(()=>this.playing),qu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Lp(this.droppedFramesChecker.checkTime)),i=Op(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])=>Vp(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}},hi=$n;import{map as Fp,Observable as _p}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Up}from"@vkontakte/videoplayer-shared/evergreen";var er=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Hp=(u,e)=>new _p(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(o=>t.next(o.isIntersecting||er()))},{...i,...e});r.observe(u);let s=Up(document,"visibilitychange").pipe(Fp(a=>!document.hidden||er())).subscribe(a=>t.next(a));return()=>{r.unobserve(u),s.unsubscribe()}}),Be=Hp;var Kp=["paused","playing","ready"],Xp=["paused","playing","ready"],tr=class{constructor(e){this.subscription=new Gp;this.videoState=new O("stopped");this.representations$=new Ln([]);this.droppedFramesManager=new hi;this.maxSeekBackTime$=new Ln(1/0);this.zeroTime$=new Ln(void 0);this.liveOffset=new Nt;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:Ku.WTF,message:`LiveDashPlayer reported error${e.message?`: ${e.message}`:""}`});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=bt(r.name)??Yp(r.video),n=r.bitrate/1e3,o={...r.video};if(!a)continue;let c={id:s,quality:a,bitrate:n,size:o};i.push({track:c,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),An(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(Xp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Kp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){D({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&(D({m:"dlp.sync.2"}),this.dash.catchUp()),D({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ee(this.params.source.url,o))}return;default:return Gu(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ku.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ju(this.videoState.stateChangeStarted$.pipe(Gs(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Gs(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{D({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(he(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(Gs(r=>r.map(({track:s})=>s)),Xu(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(zp(),Gs(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jp({zeroTime:this.zeroTime$.pipe(Xu(An)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>{s===0&&this.videoState.getTransition()||this.params.output.liveTime$.next(r+s*1e3)},t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Zu(r),min:s&&Zu(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),D({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(D({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":D({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":D({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Gu(r.to)}},t)).add(Ju(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qp(["init"])).pipe(Qp(0)).subscribe(this.syncPlayback,t))}destroy(){D({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&&An(t)?t:Ge(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==n){let c=e.find(({track:d})=>d.id===s)?.representation;Yu(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Yu(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),D({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var ec=tr;import{filter as wm,filterChanged as xm,isNonNullable as km}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as hh,assertNonNullable as mh,debounce as fh,ErrorCategory as dc,filter as _n,filterChanged as ea,fromEvent as bh,isNonNullable as pc,isNullable as gh,map as Un,merge as ta,observableFrom as Hn,once as hc,Subscription as Sh,throttle as vh}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Jp}from"@vkontakte/videoplayer-shared/evergreen";var tc=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?bt(s):void 0)??Jp({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},ic=({id:u,bitrate:e})=>({id:u,bitrate:e}),rc=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),sc=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Rn=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Dn=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var oe=u=>u.type==="template";var Ys=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ks=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 ac=`attribute vec2 a_vertex;
|
|
116
|
+
`}),S};var he=u=>new URL(u).hostname;import{assertNever as Gu,assertNonNullable as Yu,combine as Qp,debounce as zp,ErrorCategory as Ku,filter as Xu,filterChanged as qp,isNonNullable as An,map as Gs,merge as Ju,observableFrom as Wp,once as Gp,Subscription as Yp,ValueSubject as Ln,videoQualityToHeight as Zu,videoSizeToQuality as Kp}from"@vkontakte/videoplayer-shared/evergreen";var Hu=u=>{if(u instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(u.message))throw u;return!(u instanceof DOMException&&(u.code===20||u.name==="AbortError"))},ke=async(u,e)=>{let t=u.muted;try{await u.play()}catch(i){if(!Hu(i))return!1;if(e&&e(),t)return console.warn(i),!1;u.muted=!0;try{await u.play()}catch(r){return Hu(r)&&(u.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as qs,isNullable as xp,assertNonNullable as Ji}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ju,assertNonNullable as zs,now as Tp}from"@vkontakte/videoplayer-shared/evergreen";function ne(){return Tp()}function kn(u){return ne()-u}function xn(u){let e=u.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,o=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let c=a.indexOf("?")>-1?"&":"?";return o&&(a+=c+"lowLat=1",c="&"),n&&(a+=c+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Qu(u,e,t){let i=(...r)=>{t.apply(null,r),u.removeEventListener(e,i)};u.addEventListener(e,i)}function pi(u,e,t,i){let r=window.XMLHttpRequest,s,a,n,o=!1,c=0,d,l,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;zs(d);let C=kn(d),T;if(C<f){T=f-C,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,$()},g=C=>(s=C,F),S=C=>(l=C,F),I=()=>(h="json",F),v=()=>{if(!o){if(--c>=0){b(),i&&i();return}o=!0,l&&l(),t&&t()}},k=C=>(p=C,F),$=()=>{d=ne(),a=new r,a.open("get",u);let C=0,T,y=0,V=()=>(zs(d),Math.max(d,Math.max(T||0,y||0)));if(s&&a.addEventListener("progress",M=>{let _=ne();s.updateChunk&&M.loaded>C&&(s.updateChunk(V(),M.loaded-C),C=M.loaded,T=_)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;zs(a);let M=a.status;if(M>=200&&M<300){let{response:_,responseType:W}=a,Z=_?.byteLength;if(typeof Z=="number"&&s){let ie=Z-C;ie&&s.updateChunk&&s.updateChunk(V(),ie)}W==="json"&&(!_||!Object.values(_).length)?v():(l&&l(),e(_))}else v()}),a.addEventListener("error",()=>{v()}),p){let M=()=>{zs(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(y=ne(),a.removeEventListener("readystatechange",M))};a.addEventListener("readystatechange",M)}return a.responseType=h,a.send(),F},F={withBitrateReporting:g,withParallel:k,withJSONResponse:I,withRetryCount:C=>(c=C,F),withRetryInterval:(C,T)=>(ju(C)&&(f=C),ju(T)&&(m=T),F),withTimeout:C=>(n=C,F),withFinally:S,send:$,abort:()=>{a&&(a.abort(),a=void 0),o=!0,l&&l()}};return F}var Ki=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,n=s.end-s.start;i+=a;let o=s.bytes*a/n;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Xi=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ne(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=ne()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pi(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=ne()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ne();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Pp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as zu}from"@vkontakte/videoplayer-shared/evergreen";var Y=(u,e)=>zu(u)&&zu(e)&&u.readyState==="open"&&Ip(u,e);function Ip(u,e){for(let t=0;t<u.activeSourceBuffers.length;++t)if(u.activeSourceBuffers[t]===e)return!0;return!1}import{getWindow as Ep}from"@vkontakte/videoplayer-shared/evergreen";var Pn=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=Object.entries(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},wp=(u,e="warn")=>{let t=Ep(),i=[];function r(s,a=!1){let n=t.performance?.timing?.navigationStart??0,o=new Pn(u,Math.round((Date.now()-n)/1e3),s,a?new Error().stack:void 0);i.push(o),e&&t.console[e](o.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},D=wp("vp_dash_live_debug",!1);var Ws=1e4,Mn=3;var Mp=6e4,$p=10,Ap=1,Lp=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 Pp,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=xn(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&&(D({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",D({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()?(D({m:"ldp.play.1"}),this._playVideoElement()):(D({m:"ldp.play.2"}),this._notifyBuffering(!0))):(D({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,D({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=xn(e),D({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;D({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(D({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"),D({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(A.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:o,min:c}=this.autoQualityLimits||{};!Ru({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(o&&s.video.height>o||c&&s.video.height<c)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||qs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{if(this.mediaSource?.readyState!=="open"){D({m:"sourceopen",err:`not open: ${this.mediaSource?.readyState}`});return}D({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t()}),this.mediaSource?.addEventListener("sourceclose",n=>{D({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{D({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{Qu(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 Xi(Mn,Ws,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,n=null,o=null,c=null,d=!1,l=()=>{let v=s&&(!d||d===this.rep);return v||t("Not running!"),v},p=(v,k,$)=>{o&&o.abort(),o=pi(this.urlResolver.resolve(v,!1),k,$,()=>this._retryCallback()).withTimeout(Ws).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mn).withFinally(()=>{o=null}).send()},h=(v,k,$)=>{Ji(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),k,$,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let k=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${k}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=ne()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let E=this.bufferStates[R];v=Math.min(v,E.buf),E.ts<$&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${v} drop=${L} jitter=${this.sourceJitter}`);let x=v-Ap;this.sourceJitter>=0?x-=this.sourceJitter/2:this.sourceJitter-=1,x>3?m(1.15):x>1?m(1.1):x>.3?m(1.05):m(1)}},g=v=>{let k,$=()=>k&&k.start?k.start.length:0,L=M=>k.start[M]/1e3,x=M=>k.dur[M]/1e3,R=M=>k.fragIndex+M,E=(M,_)=>({chunkIdx:R(M),startTS:L(M),dur:x(M),discontinuity:_}),F=()=>{let M=0;if(k&&k.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=_;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ie=k.dur.length-1;for(;ie>=0&&(Z-=k.dur[ie],!(Z<=0));--ie);M=Math.min(ie,k.dur.length-1-W),M=Math.max(M,0)}return E(M,!0)},C=M=>{let _=$();if(!(_<=0)){if(qs(M)){for(let W=0;W<_;W++)if(L(W)>M)return E(W)}return F()}},T=M=>{let _=$(),W=M?M.chunkIdx+1:0,Z=W-k.fragIndex;if(!(_<=0)){if(!M||Z<0||Z-_>$p)return t(`Resync: offset=${Z} bChunks=${_} chunk=`+JSON.stringify(M)),F();if(!(Z>=_))return E(W-k.fragIndex,!1)}},y=(M,_,W)=>{c&&c.abort(),c=pi(this.urlResolver.resolve(M,!0,this.lowLatency),_,W,()=>this._retryCallback()).withTimeout(Ws).withRetryCount(Mn).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(M,_)=>{y(v,W=>{if(!l())return;k=W;let Z=!!k.lowLatency;Z!==this.lowLatency&&f(Z);let ie=0;for(let le=0;le<k.dur.length;++le)ie+=k.dur[le];ie>0&&(Ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,M(C(_))},()=>this._handleNetworkError())},nextChunk:T}},S=()=>{s=!1,n&&n.abort(),o&&o.abort(),c&&c.abort(),Ji(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:v=>{let{videoElement:k,logger:$}=this.params,L=g(e.jidxUrl),x,R,E,F,C=0,T,y,V,M=()=>{T&&(clearTimeout(T),T=void 0);let N=Math.max(Lp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),pe=C+N,me=ne(),ae=Math.min(1e4,pe-me);C=me;let Ae=()=>{c||l()&&L.seek(()=>{l()&&(C=ne(),_(),M())})};ae>0?T=window.setTimeout(()=>{this.paused?M():Ae()},ae):Ae()},_=()=>{let N;for(;N=L.nextChunk(F);)F=N,de(N);let pe=L.nextChunk(E);if(pe){if(E&&pe.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?M():(S(),D({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}le(pe)}else M()},W=(N,pe)=>{if(!l()||!this.sourceBuffer){D({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let me,ae,Ae,lt=Oe=>{D({m:"ldp.postpone",t:Oe}),window.setTimeout(()=>{l()&&W(N,pe)},Oe)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),D({m:"ldp.ab.1"}),lt(100);else{let Oe=ne(),xe=k.currentTime;!this.paused&&k.buffered.length>1&&y===xe&&Oe-V>500&&($("Stall suspected; trying to fix"),this._fixupStall()),y!==xe&&(y=xe,V=Oe);let dt=this._getBufferSizeSec();if(dt>30)D({m:"ldp.ab.3"}),$(`Buffered ${dt} seconds; delaying appendBuffer`),lt(2e3);else try{if(this.params.config.useInvalidBufferFix&&Y(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(D({m:"ldp.ab.5"}),this.bufferStates.push({ts:Oe,buf:dt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(D({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),pe&&pe()}catch(Le){D({m:"ldp.ab.err",e:Le.name}),Le.name==="QuotaExceededError"?($("QuotaExceededError; delaying appendBuffer"),Ae=this.sourceBuffer.buffered.length,Ae!==0&&(me=this.sourceBuffer.buffered.start(0),ae=xe,ae-me>4&&this.sourceBuffer.remove(me,ae-3)),lt(1e3)):($(Le.name),r({name:"error",type:"buffer",message:`appendBuffer failed due to ${Le.name}`}))}}},Z=()=>{R&&x&&($([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(E)]),W(R,function(){R=null,_()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),le=N=>{l()&&h(ie(N),(pe,me)=>{if(l()){if(me/=1e3,R=pe,E=N,a=N.startTS,me){let ae=Math.min(10,N.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ae:ae}Z()}},()=>this._handleNetworkError())},de=N=>{l()&&(Ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},U=N=>{l()&&(e.cachedHeader=N,W(N,()=>{x=!0,Z()}))};s=!0,L.seek(N=>{if(l()){if(C=ne(),!N){M();return}F=N,!xp(v)||N.startTS>v?le(N):(E=N,_())}},v),e.cachedHeader?U(e.cachedHeader):p(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),qs(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return qs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let 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}`)},s={updateChunk:(p,h)=>{let m=ne();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,o=!0,c=()=>{let l=s.get();if(l&&n&&this.autoQuality){if(o&&l>n&&kn(a)<3e4)return;i(l)}o=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=ne();l<n&&(a=p),n=l}}}_fetchManifest(e,t,i){this.manifestRequest=pi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ws).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ke(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{D({m:"ldp.pve.1"}),t||(D({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let n=[];return a?.length?(a.forEach((o,c)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=c,n.push(o))}),n.sort(function(o,c){return o.video&&c.video?c.video.height-o.video.height:c.bitrate-o.bitrate}),n):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Mp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Rp,filter as qu,fromEvent as Dp,interval as Cp,isHigher as Bp,isInvariantQuality as Vp,isLower as Op,merge as Np,Subject as Wu,Subscription as Fp}from"@vkontakte/videoplayer-shared/evergreen";var $n=class{constructor(){this.onDroopedVideoFramesLimit$=new Wu;this.subscription=new Fp;this.playing=!1;this.tracks=[];this.forceChecker$=new Wu;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Vp(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Bp(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(Dp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Cp(this.droppedFramesChecker.checkTime).pipe(qu(()=>this.playing),qu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Rp(this.droppedFramesChecker.checkTime)),i=Np(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Op(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},hi=$n;import{map as _p,Observable as Up}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Hp}from"@vkontakte/videoplayer-shared/evergreen";var er=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var jp=(u,e)=>new Up(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(o=>t.next(o.isIntersecting||er()))},{...i,...e});r.observe(u);let s=Hp(document,"visibilitychange").pipe(_p(a=>!document.hidden||er())).subscribe(a=>t.next(a));return()=>{r.unobserve(u),s.unsubscribe()}}),Be=jp;var Xp=["paused","playing","ready"],Jp=["paused","playing","ready"],tr=class{constructor(e){this.subscription=new Yp;this.videoState=new O("stopped");this.representations$=new Ln([]);this.droppedFramesManager=new hi;this.maxSeekBackTime$=new Ln(1/0);this.zeroTime$=new Ln(void 0);this.liveOffset=new Nt;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:Ku.WTF,message:`LiveDashPlayer reported error${e.message?`: ${e.message}`:""}`});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=bt(r.name)??Kp(r.video),n=r.bitrate/1e3,o={...r.video};if(!a)continue;let c={id:s,quality:a,bitrate:n,size:o};i.push({track:c,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),An(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Jp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Xp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){D({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&(D({m:"dlp.sync.2"}),this.dash.catchUp()),D({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ee(this.params.source.url,o))}return;default:return Gu(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ku.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ju(this.videoState.stateChangeStarted$.pipe(Gs(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Gs(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{D({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(he(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(Gs(r=>r.map(({track:s})=>s)),Xu(r=>!!r.length),Gp()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(qp(),Gs(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Qp({zeroTime:this.zeroTime$.pipe(Xu(An)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>{s===0&&this.videoState.getTransition()||this.params.output.liveTime$.next(r+s*1e3)},t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Zu(r),min:s&&Zu(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),D({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(D({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":D({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":D({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Gu(r.to)}},t)).add(Ju(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Wp(["init"])).pipe(zp(0)).subscribe(this.syncPlayback,t))}destroy(){D({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,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}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&&An(t)?t:Ge(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==n){let c=e.find(({track:d})=>d.id===s)?.representation;Yu(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Yu(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),D({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var ec=tr;import{filter as km,filterChanged as xm,isNonNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as mh,assertNonNullable as fh,debounce as bh,ErrorCategory as dc,filter as _n,filterChanged as ea,fromEvent as gh,isNonNullable as pc,isNullable as Sh,map as Un,merge as ta,observableFrom as Hn,once as hc,Subscription as vh,throttle as yh}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Zp}from"@vkontakte/videoplayer-shared/evergreen";var tc=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?bt(s):void 0)??Zp({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},ic=({id:u,bitrate:e})=>({id:u,bitrate:e}),rc=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),sc=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Rn=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Dn=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var oe=u=>u.type==="template";var Ys=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ks=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 ac=`attribute vec2 a_vertex;
|
|
117
117
|
attribute vec2 a_texel;
|
|
118
118
|
|
|
119
119
|
varying vec2 v_texel;
|
|
@@ -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 mi=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 Ys(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ks(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(ac,this.gl.VERTEX_SHADER),i=this.createShader(nc,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,n=e+i,o=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[s,a,n,o,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 th,now as rr,once as ih,Subscription as rh,ValueSubject as Bn,isNonNullable as sh,safeStorage as Vn,filterChanged as ah}from"@vkontakte/videoplayer-shared/evergreen";var et=(u,e,t)=>t*e+(1-t)*u,Cn=(u,e)=>u.reduce((t,i)=>t+i,0)/e,oc=(u,e,t,i)=>{let r=0,s=t,a=Cn(u,e),n=e<i?e:i;for(let o=0;o<n;o++)u[s]>a?r++:r--,s=(u.length+s-1)%u.length;return Math.abs(r)===n};var Xs="stalls_manager_metrics",On="stalls_manager_abr_params",uc="stalls_manager_default_tuning_abr_params",Nn=class{constructor(){this.isSeeked$=new Bn(!1);this.isBuffering$=new Bn(!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 rh;this.severeStallOccurred$=new Bn(!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(On):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=rr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(rr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(uc)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(On),this.setStoredData(uc,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Xs,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Xs,[]),this.setStoredData(On,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n}=this.tuning,o=a*Math.min(t/n,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Vn.get(e)??t)}setStoredData(e,t){Vn.set(e,JSON.stringify(t))}removeStoredData(e){Vn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Xs,"[]"),r=t/e,s=i.length?et(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(Xs,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(ih()).subscribe(t=>this.providerStartWatchingTimestamp=rr())),this.subscription.add(this.currentStallDuration$.pipe(ah()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(th(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),o=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=rr(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&d-c>=i+n&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,sh(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&rr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Js=Nn;import{combine as nh,map as oh,observeElementSize as uh,Subscription as ch,ValueSubject as Fn,noop as lh}from"@vkontakte/videoplayer-shared/evergreen";var Zs=class{constructor(){this.subscription=new ch;this.pipSize$=new Fn(void 0);this.videoSize$=new Fn(void 0);this.elementSize$=new Fn(void 0);this.pictureInPictureWindowRemoveEventListener=lh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(uh(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(nh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(oh(({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 cc,map as dh,once as lc}from"@vkontakte/videoplayer-shared/evergreen";var St=({subscription:u,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!A.browser.isSafari)return;let r=0,s=!1;u.add(e.volume.stateChangeStarted$.pipe(dh(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),cc(a=>!!a),lc()).subscribe(()=>{r=performance.now(),s=!0})),u.add(i.playbackRateState$.pipe(cc(()=>s),lc()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var _t=class{constructor(e){this.subscription=new Sh;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new hi;this.stallsManager=new Js;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new gt;this.audioTrackSwitchHistory=new gt;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 hh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(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;gh(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:dc.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(_n(l=>!!l.length),hc()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Un(l=>l.to.state!=="none"),ea());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(_n(pc),hc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),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(mh(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Rn(b));let g=[];for(let S of b.representations){let T=ic(S);g.push(T),this.audioTracksMap.set(T,{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(Dn(f));let b=[];for(let g of f.representations){let S=tc({...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=rc(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=ta(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$,bh(this.video,"progress")).pipe(_n(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(vh(o))),this.subscription.add(n.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,b]=m,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===f.id);pc(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="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: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(ea()).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(Dn(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ea()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.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(Rn(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(Un(({to:l})=>l==="ready"),ea());this.subscription.add(ta(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Hn(["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(ta(c,this.player.state$.stateChangeEnded$,Hn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ta(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Hn(["init"])).pipe(fh(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Yi:Gi,t=this.params.tuning.useNewAutoSelectVideoTrack?Qs:js,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:Hs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:k})=>k===n),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.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=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,T=0;if(S){if(o&&!a){let k=e(o,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,k?.bitrate??-1/0)}if(c){let k=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,k?.bitrate??-1/0)}}let v=o;(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:T,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}),$=this.videoTracksMap.get(v)?.representation,L=x&&this.audioTracksMap.get(x)?.representation;if($&&L)return[$,L];if($&&!L&&this.audioTracksMap.size===0)return[$,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:dc.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 sr}from"@vkontakte/videoplayer-shared/evergreen";var ia=u=>{if(!u)return{id:"EmptyResponse",category:sr.PARSER,message:"Empty response"};if(u.length<=2&&u.match(/^\d+$/))return{id:`UVError#${u}`,category:sr.NETWORK,message:`UV Error ${u}`};let e=u.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:sr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(u,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:sr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:sr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as _c,assertNonNullable as rt,ErrorCategory as qt,filter as Zn,filterChanged as mm,flattenObject as ya,fromEvent as Wt,getTraceSubscriptionMethod as fm,getWindow as Vr,interval as Uc,isNonNullable as wt,isNullable as Or,map as eo,merge as Nr,now as bm,Subject as xt,Subscription as Hc,SubscriptionRemovable as gm,ValueSubject as G}from"@vkontakte/videoplayer-shared/evergreen";var vt=u=>{let e=new URL(u);return e.searchParams.set("quic","1"),e.toString()};var ra=u=>{let e=u.get("X-Delivery-Type"),t=u.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ar,assertNever as mc,ErrorCategory as fi,flattenObject as bi,fromEvent as fc,getWindow as nr,merge as yh,now as Ht,Subject as gi,Subscription as Th,suppressAbort as aa,ValueSubject as or}from"@vkontakte/videoplayer-shared/evergreen";var sa=u=>{let e=new URL(u);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var na=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new gi;this.manifestReceived=new gi;this.firstBytesRequested=new gi;this.firstBytesReceived=new gi;this.lastConnectionType$=new or(void 0);this.lastConnectionReused$=new or(void 0);this.lastRequestFirstBytes$=new or(void 0);this.lastConnectionMetrics$=new or(void 0);this.lastDownloadMetrics$=new or(void 0);this.recoverableError$=new gi;this.error$=new gi;this.abortAllController=new AbortController;this.subscription=new Th;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=ar(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sa(i)),this.trackRequestStart(i,performance.now());let r=Ht();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(aa);if(s){let a=Ht();t.log("success",bi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let n=s.headers.get("content-length"),o=0;n&&(o=parseInt(n,10));let c=await s.text();if((!n||isNaN(o)||o<=0)&&(o=new TextEncoder().encode(c).length),o>0){let d=a-r,p=o/(d/1e3)*8/1024,h={bytes:o,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",bi({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=ar(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let 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 I=new URL(d,nr().location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),d=I.toString();break}default:mc(t)}this.requestQuic&&(d=vt(d));let h=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=yh(fc(this.abortAllController.signal,"abort"),fc(a,"abort")).subscribe(()=>{try{I.abort()}catch(y){aa(y)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(y){aa(y)}h=I.signal}let f=0,b=Ht();p.log("startRequest",bi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:l,signal:h}),S=Ht();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 I=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:I}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){m?.unsubscribe();let I=Ht(),y={requestStartedAt:b,requestEndedAt:I,duration:I-b};return p.log("endRequest",bi(y)),p.end(),g.arrayBuffer()}let T=g.body;if(n){let I;[T,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=T.getReader(),x,$=parseInt(g.headers.get("content-length")??"",10);Number.isFinite($)&&(x=$),!x&&i&&(x=i.to-i.from+1);let L=x?new Uint8Array(x):new Uint8Array(0),k=!1,R=I=>{m?.unsubscribe(),k=!0,aa(I)},E=ar(h,async function*({done:I,value:y}){if(f===0&&(this.lastRequestFirstBytes$.next(Ht()-b),this.firstBytesReceived.next()),h.aborted){m?.unsubscribe();return}if(!I&&y){if(c&&x)L.set(y,f),f+=y.byteLength;else{let V=new Uint8Array(L.length+y.length);V.set(L),V.set(y,L.length),L=V,f+=y.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(E,R)}}.bind(this));yield v?.read().then(E,R),m?.unsubscribe();let F=Ht(),C={failed:k,requestStartedAt:b,requestEndedAt:F,duration:F-b};if(k)return p.error("endRequest",bi(C)),p.end(),null;if(f>0){let I=F-b,V=f/(I/1e3)*8/1024,M={bytes:f,speed:V,url:e};this.lastDownloadMetrics$.next(M)}return p.log("endRequest",bi(C)),p.end(),L.buffer}.bind(this));this.fetchByteRangeRepresentation=ar(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(d,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,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(o)f=new DataView(l,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:b}}.bind(this));this.fetchTemplateRepresentation=ar(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,nr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=ra(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(nr()).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 nr().navigator))return"unknown";let e=nr().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:fi.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:mc(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:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r})}}};var Qn=u=>{let e=u.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as Eh,isNullable as Sc}from"@vkontakte/videoplayer-shared/evergreen";var bc=u=>{if(u.includes("/")){let e=u.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(u)};var gc=u=>{try{let e=Ih(),t=u.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let n=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(n||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(n=>n!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(n=>{let o=a[n];(typeof o>"u"||o==="")&&delete a[n]}),a}return null}catch{return null}};function Ih(){let u="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
170
|
+
`;var mi=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 Ys(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ks(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(ac,this.gl.VERTEX_SHADER),i=this.createShader(nc,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,n=e+i,o=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[s,a,n,o,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 ih,now as rr,once as rh,Subscription as sh,ValueSubject as Bn,isNonNullable as ah,safeStorage as Vn,filterChanged as nh}from"@vkontakte/videoplayer-shared/evergreen";var et=(u,e,t)=>t*e+(1-t)*u,Cn=(u,e)=>u.reduce((t,i)=>t+i,0)/e,oc=(u,e,t,i)=>{let r=0,s=t,a=Cn(u,e),n=e<i?e:i;for(let o=0;o<n;o++)u[s]>a?r++:r--,s=(u.length+s-1)%u.length;return Math.abs(r)===n};var Xs="stalls_manager_metrics",On="stalls_manager_abr_params",uc="stalls_manager_default_tuning_abr_params",Nn=class{constructor(){this.isSeeked$=new Bn(!1);this.isBuffering$=new Bn(!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 sh;this.severeStallOccurred$=new Bn(!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(On):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=rr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(rr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(uc)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(On),this.setStoredData(uc,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Xs,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Xs,[]),this.setStoredData(On,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n}=this.tuning,o=a*Math.min(t/n,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Vn.get(e)??t)}setStoredData(e,t){Vn.set(e,JSON.stringify(t))}removeStoredData(e){Vn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Xs,"[]"),r=t/e,s=i.length?et(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(Xs,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(rh()).subscribe(t=>this.providerStartWatchingTimestamp=rr())),this.subscription.add(this.currentStallDuration$.pipe(nh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(ih(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),o=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=rr(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&d-c>=i+n&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ah(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&rr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Js=Nn;import{combine as oh,map as uh,observeElementSize as ch,Subscription as lh,ValueSubject as Fn,noop as dh}from"@vkontakte/videoplayer-shared/evergreen";var Zs=class{constructor(){this.subscription=new lh;this.pipSize$=new Fn(void 0);this.videoSize$=new Fn(void 0);this.elementSize$=new Fn(void 0);this.pictureInPictureWindowRemoveEventListener=dh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ch(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(oh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(uh(({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 cc,map as ph,once as lc}from"@vkontakte/videoplayer-shared/evergreen";var St=({subscription:u,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!A.browser.isSafari)return;let r=0,s=!1;u.add(e.volume.stateChangeStarted$.pipe(ph(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),cc(a=>!!a),lc()).subscribe(()=>{r=performance.now(),s=!0})),u.add(i.playbackRateState$.pipe(cc(()=>s),lc()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var _t=class{constructor(e){this.subscription=new vh;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new hi;this.stallsManager=new Js;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new gt;this.audioTrackSwitchHistory=new gt;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 mh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(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;Sh(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:dc.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(_n(l=>!!l.length),hc()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Un(l=>l.to.state!=="none"),ea());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(_n(pc),hc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),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(fh(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Rn(b));let g=[];for(let S of b.representations){let I=ic(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(Dn(f));let b=[];for(let g of f.representations){let S=tc({...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=rc(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=ta(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$,gh(this.video,"progress")).pipe(_n(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(yh(o))),this.subscription.add(n.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,b]=m,g=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===f.id);pc(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="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: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(ea()).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(Dn(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ea()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.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(Rn(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(Un(({to:l})=>l==="ready"),ea());this.subscription.add(ta(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Hn(["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(ta(c,this.player.state$.stateChangeEnded$,Hn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ta(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Hn(["init"])).pipe(bh(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Yi:Gi,t=this.params.tuning.useNewAutoSelectVideoTrack?Qs:js,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:Hs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:x})=>x===n),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:x})=>x===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=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:x})=>x===g?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(o&&!a){let x=e(o,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,x?.bitrate??-1/0)}if(c){let x=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,x?.bitrate??-1/0)}}let v=o;(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 k=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}),$=this.videoTracksMap.get(v)?.representation,L=k&&this.audioTracksMap.get(k)?.representation;if($&&L)return[$,L];if($&&!L&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dc.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.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML),this.tracer.end()}};import{ErrorCategory as sr}from"@vkontakte/videoplayer-shared/evergreen";var ia=u=>{if(!u)return{id:"EmptyResponse",category:sr.PARSER,message:"Empty response"};if(u.length<=2&&u.match(/^\d+$/))return{id:`UVError#${u}`,category:sr.NETWORK,message:`UV Error ${u}`};let e=u.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:sr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(u,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:sr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:sr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as Uc,assertNonNullable as rt,ErrorCategory as qt,filter as Zn,filterChanged as fm,flattenObject as ya,fromEvent as Wt,getTraceSubscriptionMethod as bm,getWindow as Vr,interval as Hc,isNonNullable as wt,isNullable as Or,map as eo,merge as Nr,now as gm,Subject as kt,Subscription as jc,SubscriptionRemovable as Sm,ValueSubject as G}from"@vkontakte/videoplayer-shared/evergreen";var vt=u=>{let e=new URL(u);return e.searchParams.set("quic","1"),e.toString()};var ra=u=>{let e=u.get("X-Delivery-Type"),t=u.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ar,assertNever as mc,ErrorCategory as fi,flattenObject as bi,fromEvent as fc,getWindow as nr,merge as Th,now as Ht,Subject as gi,Subscription as Ih,suppressAbort as aa,ValueSubject as or}from"@vkontakte/videoplayer-shared/evergreen";var sa=u=>{let e=new URL(u);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var na=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new gi;this.manifestReceived=new gi;this.firstBytesRequested=new gi;this.firstBytesReceived=new gi;this.lastConnectionType$=new or(void 0);this.lastConnectionReused$=new or(void 0);this.lastRequestFirstBytes$=new or(void 0);this.lastConnectionMetrics$=new or(void 0);this.lastDownloadMetrics$=new or(void 0);this.recoverableError$=new gi;this.error$=new gi;this.abortAllController=new AbortController;this.subscription=new Ih;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=ar(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sa(i)),this.trackRequestStart(i,performance.now());let r=Ht();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(aa);if(s){let a=Ht();t.log("success",bi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let n=s.headers.get("content-length"),o=0;n&&(o=parseInt(n,10));let c=await s.text();if((!n||isNaN(o)||o<=0)&&(o=new TextEncoder().encode(c).length),o>0){let d=a-r,p=o/(d/1e3)*8/1024,h={bytes:o,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",bi({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=ar(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let 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,nr().location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:mc(t)}this.requestQuic&&(d=vt(d));let h=this.abortAllController.signal,m;if(a){let T=new AbortController;if(m=Th(fc(this.abortAllController.signal,"abort"),fc(a,"abort")).subscribe(()=>{try{T.abort()}catch(y){aa(y)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(y){aa(y)}h=T.signal}let f=0,b=Ht();p.log("startRequest",bi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:l,signal:h}),S=Ht();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=Ht(),y={requestStartedAt:b,requestEndedAt:T,duration:T-b};return p.log("endRequest",bi(y)),p.end(),g.arrayBuffer()}let I=g.body;if(n){let T;[I,T]=g.body.tee(),this.throughputEstimator?.trackStream(T,o)}let v=I.getReader(),k,$=parseInt(g.headers.get("content-length")??"",10);Number.isFinite($)&&(k=$),!k&&i&&(k=i.to-i.from+1);let L=k?new Uint8Array(k):new Uint8Array(0),x=!1,R=T=>{m?.unsubscribe(),x=!0,aa(T)},E=ar(h,async function*({done:T,value:y}){if(f===0&&(this.lastRequestFirstBytes$.next(Ht()-b),this.firstBytesReceived.next()),h.aborted){m?.unsubscribe();return}if(!T&&y){if(c&&k)L.set(y,f),f+=y.byteLength;else{let V=new Uint8Array(L.length+y.length);V.set(L),V.set(y,L.length),L=V,f+=y.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(E,R)}}.bind(this));yield v?.read().then(E,R),m?.unsubscribe();let F=Ht(),C={failed:x,requestStartedAt:b,requestEndedAt:F,duration:F-b};if(x)return p.error("endRequest",bi(C)),p.end(),null;if(f>0){let T=F-b,V=f/(T/1e3)*8/1024,M={bytes:f,speed:V,url:e};this.lastDownloadMetrics$.next(M)}return p.log("endRequest",bi(C)),p.end(),L.buffer}.bind(this));this.fetchByteRangeRepresentation=ar(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(d,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,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(o)f=new DataView(l,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:b}}.bind(this));this.fetchTemplateRepresentation=ar(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,nr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=ra(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(nr()).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 nr().navigator))return"unknown";let e=nr().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:fi.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:mc(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:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:fi.FATAL,httpCode:i.status,UVBackendErrorCode:r})}}};var Qn=u=>{let e=u.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as wh,isNullable as Sc}from"@vkontakte/videoplayer-shared/evergreen";var bc=u=>{if(u.includes("/")){let e=u.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(u)};var gc=u=>{try{let e=Eh(),t=u.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let n=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(n||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(n=>n!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(n=>{let o=a[n];(typeof o>"u"||o==="")&&delete a[n]}),a}return null}catch{return null}};function Eh(){let u="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
171
171
|
(?<language>${`(?:[a-z]{2,3}(?:-${u})?|[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 vc=u=>{if(!u?.startsWith("P"))return;let e=(a,n)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(u),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(u,e)=>{let t=u;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,o)=>Sc(s)?n:Sc(o)?s:s.padStart(parseInt(o,10),"0"))}return t},ca=(u,e)=>{let i=new DOMParser().parseFromString(u,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(R=>R.textContent?.trim()??""),n=a.at(0)??"",o=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.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,b;o&&(b={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 g,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],v=T.reduce((R,E)=>({...R,[E.id]:E.children}),{}),x=T.reduce((R,E)=>({...R,[E.id]:E.getAttribute("duration")}),{});S?g=vc(S):Object.values(x).filter(R=>R).length&&!o?g=Object.values(x).reduce((R,E)=>R+(vc(E)??0),0):f&&(g=parseInt(f,10));let $=0,L=s.getAttribute("profiles")?.split(",")??[];for(let R of T.map(E=>E.id))for(let E of v[R]){let F=E.getAttribute("id")??"id"+($++).toString(10),C=E.getAttribute("mimeType")??"",I=E.getAttribute("codecs")??"",y=E.getAttribute("contentType")??C?.split("/")[0],V=E.getAttribute("profiles")?.split(",")??[],M=gc(E.getAttribute("lang")??"")??{},_=E.querySelector("Label")?.textContent?.trim()??void 0,W=E.querySelectorAll("Representation"),Z=E.querySelector("SegmentTemplate"),ie=E.querySelector("Role")?.getAttribute("value")??void 0,le=y,de={id:F,language:M.language,isDefault:ie==="main",label:_,codecs:I,hdr:le==="video"&&Qn(I),mime:C,representations:[]};for(let U of W){let N=U.getAttribute("lang")??void 0,pe=_??E.getAttribute("label")??U.getAttribute("label")??void 0,me=U.querySelector("BaseURL")?.textContent?.trim()??"",ae=new URL(me||n,e).toString(),Ae=U.getAttribute("mimeType")??C,lt=U.getAttribute("codecs")??I??"",Oe;if(y==="text"){let ke=U.getAttribute("id")||"",dt=M.privateuse?.includes("x-auto")||ke.includes("_auto"),Le=U.querySelector("SegmentTemplate");if(Le){let Di={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},us=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,cs=parseInt(Le.getAttribute("startNumber")??"",10)??1,Zt=parseInt(Le.getAttribute("timescale")??"",10),Ya=Le.querySelectorAll("SegmentTimeline S")??[],ei=Le.getAttribute("media");if(!ei)continue;let ls=[],ds=0,ps="",ti=0,Ci=cs,fe=0;for(let Ne of Ya){let Rt=parseInt(Ne.getAttribute("d")??"",10),Re=parseInt(Ne.getAttribute("r")??"",10)||0,pt=parseInt(Ne.getAttribute("t")??"",10);fe=Number.isFinite(pt)?pt:fe;let Dt=Rt/Zt*1e3,ii=fe/Zt*1e3;for(let He=0;He<Re+1;He++){let ht=_e(ei,{...Di,segmentNumber:Ci.toString(10),segmentTime:(fe+He*Rt).toString(10)}),ri=(ii??0)+He*Dt,Vi=ri+Dt;Ci++,ls.push({time:{from:ri,to:Vi},url:ht})}fe+=(Re+1)*Rt,ds+=(Re+1)*Dt}ti=fe/Zt*1e3,ps=_e(ei,{...Di,segmentNumber:Ci.toString(10),segmentTime:fe.toString(10)});let Bi={time:{from:ti,to:1/0},url:ps},Ke={type:"template",baseUrl:ae,segmentTemplateUrl:ei,initUrl:"",totalSegmentsDurationMs:ds,segments:ls,nextSegmentBeyondManifest:Bi,timescale:Zt};Oe={id:ke,kind:"text",segmentReference:Ke,profiles:[],duration:g,bitrate:us,mime:"",codecs:"",width:0,height:0,isAuto:dt}}else Oe={id:ke,isAuto:dt,kind:"text",url:ae}}else{let ke=U.getAttribute("contentType")??Ae?.split("/")[0]??y,dt=E.getAttribute("profiles")?.split(",")??[],Le=parseInt(U.getAttribute("width")??"",10),Di=parseInt(U.getAttribute("height")??"",10),us=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,cs=U.getAttribute("frameRate")??"",Zt=U.getAttribute("quality")??void 0,Ya=cs?bc(cs):void 0,ei=U.getAttribute("id")??"id"+($++).toString(10),ls=ke==="video"?`${Di}p`:ke==="audio"?`${us}Kbps`:lt,ds=`${ei}@${ls}`,ps=[...L,...V,...dt],ti,Ci=U.querySelector("SegmentBase"),fe=U.querySelector("SegmentTemplate")??Z;if(Ci){let Ke=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Rt]=Ke.split("-").map(ht=>parseInt(ht,10)),Re={from:Ne,to:Rt},pt=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Dt,ii]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],He=pt?{from:Dt,to:ii}:void 0;ti={type:"byteRange",url:ae,initRange:Re,indexRange:He}}else if(fe){let Ke={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Ne=parseInt(fe.getAttribute("timescale")??"",10),Rt=fe.getAttribute("initialization")??"",Re=fe.getAttribute("media"),pt=parseInt(fe.getAttribute("startNumber")??"",10)??1,Dt=_e(Rt,Ke);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let ii=fe.querySelectorAll("SegmentTimeline S")??[],He=[],ht=0,ri="",Vi=0;if(ii.length){let hs=pt,Fe=0;for(let si of ii){let je=parseInt(si.getAttribute("d")??"",10),Ct=parseInt(si.getAttribute("r")??"",10)||0,ms=parseInt(si.getAttribute("t")??"",10);Fe=Number.isFinite(ms)?ms:Fe;let Ka=je/Ne*1e3,rd=Fe/Ne*1e3;for(let fs=0;fs<Ct+1;fs++){let sd=_e(Re,{...Ke,segmentNumber:hs.toString(10),segmentTime:(Fe+fs*je).toString(10)}),Fo=(rd??0)+fs*Ka,ad=Fo+Ka;hs++,He.push({time:{from:Fo,to:ad},url:sd})}Fe+=(Ct+1)*je,ht+=(Ct+1)*Ka}Vi=Fe/Ne*1e3,ri=_e(Re,{...Ke,segmentNumber:hs.toString(10),segmentTime:Fe.toString(10)})}else if(Eh(g)){let Fe=parseInt(fe.getAttribute("duration")??"",10)/Ne*1e3,si=Math.ceil(g/Fe),je=0;for(let Ct=1;Ct<si;Ct++){let ms=_e(Re,{...Ke,segmentNumber:Ct.toString(10),segmentTime:je.toString(10)});He.push({time:{from:je,to:je+Fe},url:ms}),je+=Fe}Vi=je,ri=_e(Re,{...Ke,segmentNumber:si.toString(10),segmentTime:je.toString(10)})}let id={time:{from:Vi,to:1/0},url:ri};ti={type:"template",baseUrl:ae,segmentTemplateUrl:Re,initUrl:Dt,totalSegmentsDurationMs:ht,segments:He,nextSegmentBeyondManifest:id,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let Bi={video:"video",audio:"audio",text:"text"}[ke];if(!Bi)continue;le||=Bi,Oe={id:ds,kind:Bi,segmentReference:ti,profiles:ps,duration:g,bitrate:us,mime:Ae,codecs:lt,width:Le,height:Di,fps:Ya,quality:Zt}}de.language||=N,de.label||=pe,de.mime||=Ae,de.codecs||=lt,de.hdr||=le==="video"&&Qn(lt),de.representations.push(Oe)}if(le){let U=r[le].find(N=>N.id===de.id);if(U&&de.representations.every(N=>N.segmentReference.type==="template"))for(let N of U.representations){let pe=de.representations.find(Ae=>Ae.id===N.id);if(!pe)continue;let me=pe.segmentReference,ae=N.segmentReference;ae.segments.push(...me.segments),ae.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[le].push(de)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as pa}from"@vkontakte/videoplayer-shared/evergreen";var la=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(la||{});var da=u=>{let{webmDecodingInfo:e}=A.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(u){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:pa(u)}},yc=({webmCodec:u,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...da(u),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(A.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",...da(u),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...da(u),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...da(u),...s,"HLS","HLS_ONDEMAND"];default:pa(e)}if(A.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:pa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tc=({androidPreferredFormat:u,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,o=A.device.isMac&&A.browser.isSafari;if(A.device.isAndroid)switch(u){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:pa(u)}else A.video.nativeHlsSupported&&!o&&!A.browser.isChromiumBased?n=a:o?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},zn=u=>u?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ha=u=>{if(u.size===0)return;if(u.size===1)return u.values().next().value.split(".").at(0);for(let t of u){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return u.values().next().value.split(".").at(0)},ma=u=>{let e=u.map(i=>yt(i)),{codecs:t}=A.video;return kh().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})},fa=u=>{let e=u.map(i=>yt(i)),{codecs:t}=A.video;return Ph().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},yt=u=>u.split(".")[0].replace("0",""),kh=()=>["av1","vp9","hev1","avc1"],Ph=()=>["opus","mp4a"];import{abortable as Kn,assertNonNullable as Ye,ErrorCategory as Gh,fromEvent as Yh,getExponentialDelay as Kh,getWindow as Lc,isHigher as Xh,isNonNullable as te,isNullable as ue,once as Jh,Subject as Zh,Subscription as em,ValueSubject as Dr}from"@vkontakte/videoplayer-shared/evergreen";var ba=u=>u.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 Si=class extends j{};import{assertNever as Mh}from"@vkontakte/videoplayer-shared/evergreen";var ur=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:Mh(e)}}};var cr=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 lr=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 dr=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 pr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var jt=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 o=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var br=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 gr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Sr=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 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.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 Tr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Er=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var wr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xr=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 kr=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 Pr=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 Mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $r=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 Ar=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 Ah={ftyp:cr,moov:lr,mvhd:dr,moof:pr,mdat:hr,sidx:jt,trak:mr,mdia:vr,mfhd:Er,tkhd:yr,traf:wr,tfhd:xr,tfdt:kr,trun:Pr,minf:Tr,sv3d:fr,st3d:br,prhd:gr,proj:Ir,equi:Sr,uuid:ur,stbl:Mr,stsd:$r,avc1:Ar,unknown:Si},tt=class u{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!ba(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=Ah[e];return i?new i(t,new u):new Si(t,new u)}};var Tt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ba(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 Rh=new TextDecoder("ascii"),Dh=u=>Rh.decode(new DataView(u.buffer,u.byteOffset+4,4))==="ftyp",Ch=u=>{let e=new jt(u,new tt),t=e.earliestPresentationTime/e.timescale*1e3,i=u.byteOffset+u.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},Bh=(u,e)=>{let i=new tt().parse(u),r=new Tt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],o=a[a.length-1],c=n.source.byteOffset,l=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(u.buffer,c,l)},Vh=u=>{let t=new tt().parse(u),i=new Tt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Oh=u=>{let t=new tt().parse(u);return new Tt(t).find("sidx")?.timescale},Nh=(u,e)=>{let i=new tt().parse(u),s=new Tt(i).findAll("traf"),a=s[s.length-1].children.find(l=>l.type==="tfhd"),n=s[s.length-1].children.find(l=>l.type==="tfdt"),o=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return o.sampleDuration.length?c=o.sampleDuration.reduce((l,p)=>l+p,0):c=a.defaultSampleDuration*o.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},Fh=u=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new tt().parse(u),r=new Tt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Ic={validateData:Dh,parseInit:Fh,getIndexRange:()=>{},parseSegments:Ch,parseFeedableSegmentChunk:Bh,getChunkEndTime:Nh,getServerLatencyTimestamps:Vh,getTimescaleFromIndex:Oh};import{assertNonNullable as qn,isNonNullable as kc,isNullable as Uh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as _h}from"@vkontakte/videoplayer-shared/evergreen";var Ec={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"}},wc=u=>{let e=u.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Lr(u,t),r=i in Ec,s=r?Ec[i].type:"binary",a=u.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let o=new DataView(u.buffer,u.byteOffset+t+1,n-1),c=a&255>>n,d=Lr(o),l=c*2**((n-1)*8)+d,p=t+n,h;return p+l>u.byteLength?h=new DataView(u.buffer,u.byteOffset+p):h=new DataView(u.buffer,u.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Lr=(u,e=u.byteLength)=>{switch(e){case 1:return u.getUint8(0);case 2:return u.getUint16(0);case 3:return u.getUint8(0)*2**16+u.getUint16(1);case 4:return u.getUint32(0);case 5:return u.getUint8(0)*2**32+u.getUint32(1);case 6:return u.getUint16(0)*2**32+u.getUint32(2);case 7:{let t=u.getUint8(0)*281474976710656+u.getUint16(1)*4294967296+u.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(u,e)=>{switch(e){case"int":return u.getInt8(0);case"uint":return Lr(u);case"float":return u.byteLength===4?u.getFloat32(0):u.getFloat64(0);case"string":return new TextDecoder("ascii").decode(u);case"utf8":return new TextDecoder("utf-8").decode(u);case"date":return new Date(Date.UTC(2001,0)+u.getInt8(0)).getTime();case"master":return u;case"binary":return u;default:_h(e)}},Qt=(u,e)=>{let t=0;for(;t<u.byteLength;){let i=new DataView(u.buffer,u.byteOffset+t),r=wc(i);if(!e(r))return;r.type==="master"&&Qt(r.value,e),t=r.value.byteOffset-u.byteOffset+r.valueSize}},xc=u=>{if(u.getUint32(0)!==440786851)return!1;let e,t,i,r=wc(u);return Qt(r.value,({tag:s,type:a,value:n})=>(s===17143?e=Ue(n,a):s===17026?t=Ue(n,a):s===17029&&(i=Ue(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Pc=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Hh=[231,22612,22743,167,171,163,160,175],jh=u=>{let e,t,i,r,s=!1,a=!1,n=!1,o,c,d=!1,l=0;return Qt(u,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=Ue(m,h);c=Lr(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=Ue(m,h):p===17545?r=Ue(m,h):p===21420&&c===475249515?o=Ue(m,h):p===374648427?Qt(m,({tag:b,type:g,value:S})=>b===30321?(d=Ue(S,g)===1,!1):!0):s&&a&&Pc.includes(p)&&(n=!0),!n}),qn(e,"Failed to parse webm Segment start"),qn(t,"Failed to parse webm Segment end"),qn(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Qh=u=>{if(Uh(u.cuesSeekPosition))return;let e=u.segmentStart+u.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zh=(u,e)=>{let t=!1,i=!1,r=n=>kc(n.time)&&kc(n.position),s=[],a;return Qt(u,({tag:n,type:o,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Ue(c,o));break;case 183:break;case 241:a&&(a.position=Ue(c,o));break;default:t&&Pc.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,o)=>{let{time:c,position:d}=n,l=s[o+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}}})},qh=u=>{let e=0,t=!1;try{Qt(u,i=>i.tag===524531317?i.tagSize<=u.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Hh.includes(i.tag)?(e+i.tagSize<=u.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=u.byteLength&&t?new DataView(u.buffer,u.byteOffset,e):null},Mc={validateData:xc,parseInit:jh,getIndexRange:Qh,parseSegments:zh,parseFeedableSegmentChunk:qh};var zt=u=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(u);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Mc;case"mp4":return Ic}}throw new ReferenceError(`Unsupported mime type ${u}`)};import{videoSizeToQuality as Wh}from"@vkontakte/videoplayer-shared/evergreen";var It=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?bt(s):void 0)??Wh({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Rr=({id:u,bitrate:e})=>({id:u,bitrate:e}),$c=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Ac=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Wn=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Gn=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Yn=u=>"url"in u,Me=u=>u.type==="template";var vi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,getCurrentStallDuration:n,manifest:o}){this.error$=new Zh;this.playingRepresentation$=new Dr(void 0);this.playingRepresentationInit$=new Dr(void 0);this.currentSegmentLength$=new Dr(0);this.onLastSegment$=new Dr(!1);this.fullyBuffered$=new Dr(!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 em;this.startWith=Kn(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.containerParser=zt(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);Ye(i,"No init buffer for starting representation"),Ye(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Kn(this.destroyAbortController.signal,async function*(e,t=!0){if(ue(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);Ye(r,`No such representation ${e}`),Ye(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),a=this.segments.get(r.id);Ye(s,"No init buffer for switching representation"),Ye(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,o=l=>l.segment.bufferStatus!=="fed",c=l=>{let p=this.representations.get(l.representationId);return Ye(p,"No itemRepresentation for previous track before switch"),l.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},d=l=>t?o(l)&&c(l):o(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(n),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Kn(this.downloadAbortController.signal,async function*(){let e=Kh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=Lc();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(Yh(i,"online").pipe(Jh()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=a,this.getCurrentStallDuration=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(c=>[c.id,c]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ue(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(s=>s.segment.networkStatus==="downloaded"),i=t[t.length-1],r=te(e)&&te(i)?i.segment.time.to-e:0;return Math.max(r,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 ue(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(e){let t=this.segments.get(e);return(t?t.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=Lc();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=It(e),s=It(t);i=te(r)&&te(s)&&Xh(s.quality,r.quality)}else if(this.kind==="audio"){let r=Rr(e),s=Rr(t);i=te(r?.bitrate)&&te(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():te(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:a,initDataView:n,segments:o}=await s??{};if(this.initDataPromises.delete(e.id),ue(n)||ue(o))return;a&&this.parsedInitData.set(e.id,a);let c=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,o),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:Gh.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition(),t=this.segments.get(this.downloadingRepresentationId??""),i=t?.[t?.length-1];if(ue(e)||ue(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(h=>this.withinInterval(e,h.segment.time)),s=this.bufferPlaybackQueue.find(h=>h.segment.bufferStatus!=="fed"),a=this.initData.get(s?.representationId??""),n=this.bufferPlaybackQueue[0],o=this.downloadAbortController.signal,d=(this.getCurrentStallDuration()??0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&(d&&=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=d?this.getForwardPlaybackBufferDuration()>=l:!0;te(a)&&te(s)&&te(r)&&this.playingRepresentationId!==s.representationId&&this.withinAppendInterval(e,s.segment.time)&&(s===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(a,this.downloadAbortController.signal),this.playingRepresentationId=s.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),te(s)&&this.withinAppendInterval(e,s.segment.time)&&p&&(s.segment.loadedBytes===s.segment.size&&s.segment.bufferStatus==="none"?await this.appendSegmentFully(s,o):await this.appendSegmentPartially(s,o)),te(n)&&this.withinRemoveInterval(e,n.segment.time)&&await this.removeSegment(n,o),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Ye(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ue(t)||ue(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);te(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(ue(t)||t.length===0)return;let i=t[t?.length-1];ue(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){Ye(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;te(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(n=>this.withinInterval(e,n.time))),r=r===-1?0:r;let a=[];for(;r<t.length&&s>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:n,to:o}=t[r].time;s-=o-n,r++}return a}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return te(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return te(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 te(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ue(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(ue(e.segment.data)||ue(e.segment.loadedBytes)||ue(e.segment.feedingBytes)||ue(e.segment.fedBytes)||ue(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||te(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)te(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())te(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(o=>o.segment===n)&&!this.downloadingBufferItems.find(o=>o.segment===n)&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as tm,isNonNullable as im,isNullable as Rc,now as Dc,isAbortError as rm}from"@vkontakte/videoplayer-shared/evergreen";var ga=class extends vi{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=Dc(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),rm(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(oe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(n,o)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Dc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:tm.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||Rc(n)||Rc(r)||a.aborted))for(let o of e){let{segment:c}=o,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<s,m=l<=s;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(o),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(o)):im(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(o))))}}updateRepresentationBaseUrl(e,t){if(oe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as sm,isAbortError as am,isNullable as Xn,now as Cc}from"@vkontakte/videoplayer-shared/evergreen";var yi=class extends vi{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=Cc(),Xn(n))return;let o=e[0],c=new DataView(n);o.segment.size=c.byteLength,o.segment.loadedBytes=c.byteLength,o.segment.data=c,this.onItemFullyDownloaded(o),await this.onDownloadItem(o),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),am(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=Cc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,signal:r,representationId:t.id})}catch(o){this.error$.next({id:"SegmentFeeding",category:sm.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:o})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!oe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let a=e[0],{segment:n}=a,o=this.representations.get(i);!this.downloadingBufferItems.length||Xn(o)||Xn(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(!oe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as nm,ErrorCategory as om,isNullable as it,ValueSubject as Bc}from"@vkontakte/videoplayer-shared/evergreen";var Sa=class extends yi{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Bc(0);this.currentLowLatencySegmentLength$=new Bc(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(it(r)||!oe(r.segmentReference))return;let s=r.segmentReference.segments.map(d=>({...d,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],o=n.at(-1)?.time.to??0,c=s?.findIndex(d=>o>=d.time.from+a&&o<=d.time.to+a);if(c===-1){let d=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,d)}else{let d=s.slice(c+1);this.segments.set(r.id,[...n,...d])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;nm(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(it(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(it(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return it(t)||!oe(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),it(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(it(t.segment.data)||it(r)||!oe(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(!oe(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),d=_e(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: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 s=this.tuning.dash.useFetchPriorityHints?i:"auto",a=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,a);let{initMetadata:n,initDataView:o,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),it(o)||it(c))return;n&&this.parsedInitData.set(t.id,n);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(t.id,l),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:om.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 Cr=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new Sa(e,t,i,r):oe(i[0].segmentReference)?new yi(e,t,i,r):new ga(e,t,i,r)}};import{ErrorCategory as lm,fromEvent as dm,isNullable as Ti,Subject as pm,Subscription as hm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as um,ErrorCategory as Vc,Subject as Oc}from"@vkontakte/videoplayer-shared/evergreen";var cm=18,Nc=!1;try{Nc=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=cm}catch(u){console.error(u)}var Jn=class{constructor(e,t=!1){this.bufferFull$=new Oc;this.error$=new Oc;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 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)};Nc&&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: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:um(t)}}},Fc=Jn;var Et=(u,e)=>{let t=0;for(let i=0;i<u.length;i++){let r=u.start(i)*1e3,s=u.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Br=class{constructor(e){this.error$=new pm;this.subscription=new hm;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Fc(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(dm(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:lm.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(Ti(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(){!Ti(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Ti(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 Ti(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ti(e)?0:Et(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Ti(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 va=(u,e)=>{u.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s,codecs:a})=>{let n=e.find(([o,c,d])=>o===`${s}p`&&yt(a)===d)?.[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var Sm=["timeupdate","progress","play","seeked","stalled","waiting"],jc=["timeupdate","progress","loadeddata","playing","seeked"],Ii=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new Hc;this.subscriptionRemovable=new gm;this.representationSubscription=new Hc;this.forceEnded$=new xt;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 xt;this.manifestRequested=new xt;this.manifestReceived=new xt;this.firstBytesRequested=new xt;this.firstBytesReceived=new xt;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 xt;this.fetcherError$=new xt;this.initRepresentations=_c(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ya({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,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),rt(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=_c(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Or(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qt.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 na({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:qt.PARSER,message:"No playable video representations"})}initBuffer(){rt(this.element),this.state$.setState("running"),this.subscription.add(Nr(...Sm.map(t=>Wt(this.element,t)),Wt(Vr(),"online"),Uc(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:qt.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Nr(...e.map(t=>Wt(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Wt(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Uc(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:qt.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){rt(this.element),rt(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,A.browser.isSafari?(await this.audioBufferManager?.seek(i),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i)),this.tracer.log("seek",ya({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){wt(this.element)&&wt(this.source)&&wt(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(e){return Math.max(this.videoBufferManager?.calculateDurationFromSegments(e)||0,this.audioBufferManager?.calculateDurationFromSegments(e)||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&&Vr().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),wt(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(Or(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(){rt(this.element),rt(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)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",ya(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=bm(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,d=wt(this.videoBufferManager)&&o<s&&r-a>i,l=wt(this.audioBufferManager)&&c<s&&r-n>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Or(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",ya(i)),i}parseManifest(e){try{return ca(e??"",this.manifestUrlString)}catch(t){let i=ia(e)??{id:"ManifestParsing",category:qt.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&Pe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:l,codecs:p})=>i(n,l,p));t[n]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);n==="audio"&&(s=fa(l),d=s[0]),n==="video"&&(r=ma(l),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[n]=c.filter(({codecs:p})=>yt(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=ha(l),d&&(t[n]=c.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let l=this.tuning.preferHDR,p=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);A.display.isHDR&&l&&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&&va(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){rt(this.manifest),rt(this.element);let s=c=>{this.representationSubscription.add(Wt(c,"error").pipe(Zn(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=xs();let a=Vr().document,n=a.createElement("source");if(s(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ai())if(r){let c=a.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Br(this.source),this.videoBufferManager=Cr.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],wt(i)){this.audioNativeBufferManager=new Br(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=Cr.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=Vr().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:qt.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&&Vr().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(Nr(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),rt(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(Nr(...jc.map(e=>Wt(this.element,e))).pipe(eo(e=>this.videoBufferManager?.getPlaybackBufferState()),Zn(wt),eo(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Nr(...jc.map(e=>Wt(this.element,e))).pipe(eo(e=>Math.min(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),mm()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Zn(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=fm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Or(this.element)||Or(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 Ta,combine as vm,ErrorCategory as ym,filter as to,filterChanged as Tm,fromEvent as Im,isNonNullable as Em,map as io,merge as Fr}from"@vkontakte/videoplayer-shared/evergreen";var Ia=class extends Ii{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){Ta(this.manifest),Ta(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),oe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){Ta(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Ta(this.element);let e=Fr(Im(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(to(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Fr(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Fr(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(io(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=Fr(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(io(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=vm({allBuffersFull:e,someBufferEnded:t}).pipe(Tm(),io(({allBuffersFull:s,someBufferEnded:a})=>s&&a),to(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:ym.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(Fr(this.forceEnded$,i).pipe(to(s=>Em(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var _r=class extends _t{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(xm(),wm(s=>km(s))).subscribe(s=>{let a=this.player.calculateDurationFromSegments(s);a&&this.params.output.duration$.next(a/1e3)},r))}getPlayer(){return new Ia({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{combine as ao,merge as Yc,filter as Kc,filterChanged as Xc,isNullable as no,map as Jc,ValueSubject as oo,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/evergreen";import{isNullable as Pm,ValueSubject as Qc}from"@vkontakte/videoplayer-shared/evergreen";var kt=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 Qc(e.initial),this.debounced$=new Qc(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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)&&(Pm(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 Ea=class extends kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=et(this.slow,e,this.params.emaAlphaSlow),this.fast=et(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wa=class extends kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=et(this.emaSmoothed,e,this.params.emaAlpha);let i=oc(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var xa=class extends kt{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?et(this.smoothed,t,this.params.emaAlpha):t}};var st=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ea({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new wa({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 xa({initial:e,label:"liveEdgeDelay",...t})}};import{assertNonNullable as Gt,combine as Hr,ErrorCategory as ka,filter as Pa,filterChanged as ro,fromEvent as zc,interval as Lm,isNonNullable as Rm,isNullable as qc,map as so,now as Wc,throttle as Dm}from"@vkontakte/videoplayer-shared/evergreen";var Ei=(u,e)=>{u&&u.playbackRate!==e&&(u.playbackRate=e)};import{isNullable as Mm,ValueSubject as $m}from"@vkontakte/videoplayer-shared/evergreen";var Ur=class u{constructor(e,t){this.currentRepresentation$=new $m(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(!Mm(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&oe(t.segmentReference))}};var Ma=class extends Ii{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=st.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){Gt(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){let i=this.videoBufferManager?.getRepresentationInitialTime()??0;await super.seek(i,!1)}async tick(){await super.tick();let t=(this.element?.currentTime??0)*1e3;this.liveTextManager?.maintain(t)}setSourceDuration(){Gt(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,s=this.liveStreamStatus$.getValue()==="active";return(!i||s)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,s=this.currentStallDuration$.getValue(),n=this.liveStreamStatus$.getValue()==="active";if(s%i===0){let o=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=o,!n&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(o),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(o).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:ka.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){let t=await super.updateManifest();if(qc(t))return null;if(qc(t.live))return this.error$.next({id:"ManifestParsing",category:ka.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:s,streamIsAlive:a}=t.live,n=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*n),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let o="active";if(a||(o=s?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(o),this.bufferManagers.forEach(d=>d.updateManifest(t)),this.liveTextManager?.updateLive(t),a&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let d=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(d).catch(l=>{this.error$.next({id:"updateManifest",category:ka.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:l})})}return t}prepareManifestUrlString(t,i){return ee(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?Wc()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=ee(this.manifestUrlString,r,2)}createBuffers(t,i,r,s){Gt(this.manifest),super.createBuffers(t,i,r,s),Ur.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ur(this.manifest.streams.text,t))}initRepresentationSubscriptions(){Gt(this.element),Gt(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),Rm(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){Gt(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>Lm(t).subscribe(async r=>{let s=mt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,s+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add(zc(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add(zc(this.element,"play").subscribe(r=>this.livePauseWatchdogSubscription?.unsubscribe()))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe(ro()).subscribe(i=>this.liveStreamEndTimestamp=Wc())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add(Hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(so(({isActiveLive:t,isLowLatency:i})=>t&&i),ro(),Pa(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Ei(this.element,1))),this.representationSubscription.add(Hr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Pa(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let s=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,a=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,n=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=t-s,c=1;Math.abs(o)>a&&(c=1+Math.sign(o)*n),Ei(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add(Hr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Pa(({bufferLength:r,isActiveLive:s,isLowLatency:a})=>s&&a&&!!r),so(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{let s=0;if(r){let a=(this.element?.currentTime??0)*1e3;s=Math.min(...i.map(o=>o.getLiveSegmentsToLoadState(this.manifest)?.to??a))-a}this.liveLoadBufferLength$.getValue()!==s&&this.liveLoadBufferLength$.next(s)})),this.representationSubscription.add(Hr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe(Pa(({isLive:r})=>r),ro((r,s)=>s.bufferLength<r.bufferLength),so(({rtt:r,bufferLength:s,segmentServerLatency:a})=>{let n=mt(this.manifestUrlString,2);return(r/2+s+a+n)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add(Hr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Dm(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:s})=>{Gt(this.element);let a=this.element.playbackRate,n=mt(this.manifestUrlString,2),o=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(o,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*a),d=this.tuning.dashCmafLive.normalizedActualBufferOffset*a,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*a,p=isFinite(r)?r:s,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=o<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let f="none";if(h?f="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(b=>b.proceedLowLatencyLive()),f="active_low_latency"):n!==0&&p<c?f="live_forward_buffering":p<c+l&&(f="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),f==="live_forward_buffering"||f==="live_with_target_offset"){let b=i-(c+d),g=this.normalizeLiveOffset(Math.trunc(n+b/a)),S=Math.abs(g-n),T=0;!r||S<=this.tuning.dashCmafLive.offsetCalculationError?T=n:g>0&&S>this.tuning.dashCmafLive.offsetCalculationError&&(T=g),this.manifestUrlString=ee(this.manifestUrlString,T,2)}(f==="live_with_target_offset"||f==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:ka.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var wi=class extends _t{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Ma({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let n=new oo(1);a(r.playbackRateState$,n),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Xc()).subscribe(o=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!o&&!c&&l?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Jc(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ao({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Jc(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o+c:void 0)).subscribe(i.liveTime$)).add(ao({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Yc(r.playbackRateState$,new oo(1))}).pipe(Kc(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,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||no(d)||(t=o-d)})).add(ao({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Yc(r.playbackRateState$,new oo(1))}).pipe(Xc((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||no(o)||no(c))return;let h=-1*(c-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=sc(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Kc(o=>Cm(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as af,assertNonNullable as nf,combine as of,debounce as uf,ErrorCategory as ul,filter as go,filterChanged as Xr,fromEvent as cf,isNonNullable as cl,isNullable as lf,map as Jr,merge as Zr,observableFrom as Ba,once as ll,Subscription as df,throttle as pf}from"@vkontakte/videoplayer-shared/evergreen";var Pt=(u,e,t=0)=>{for(let i=0;i<u.length;i++)if(u.start(i)*1e3-t<=e&&u.end(i)*1e3+t>e)return!0;return!1};import{abortable as ho,assertNonNullable as Mi,combine as $i,ErrorCategory as Ve,filter as Ra,filterChanged as Gr,flattenObject as Yr,fromEvent as nt,getTraceSubscriptionMethod as qm,interval as mo,isNonNullable as Kr,isNullable as nl,map as Ai,merge as Xt,now as fo,Subject as ot,Subscription as ol,SubscriptionRemovable as Wm,tap as Gm,throttle as Ym,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Bm,ErrorCategory as Zc,Subject as el}from"@vkontakte/videoplayer-shared/evergreen";var Vm=18,tl=!1;try{tl=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=Vm}catch(u){console.error(u)}var uo=class{constructor(e,t=!1){this.bufferFull$=new el;this.error$=new el;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:Zc.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)};tl&&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:Zc.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:Bm(t)}}},il=uo;var co=u=>{let e=0;for(let t=0;t<u.length;t++)e+=u.end(t)-u.start(t);return e*1e3};import{abortable as Mt,assertNonNullable as ye,ErrorCategory as at,fromEvent as lo,getExponentialDelay as po,isHigher as Om,isNonNullable as $t,isNullable as re,now as $a,once as Nm,Subject as Fm,Subscription as _m,ValueSubject as Yt,isAbortError as rl}from"@vkontakte/videoplayer-shared/evergreen";var jr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new Yt(0);this.currentLowLatencySegmentLength$=new Yt(0);this.currentSegmentLength$=new Yt(0);this.onLastSegment$=new Yt(!1);this.fullyBuffered$=new Yt(!1);this.playingRepresentation$=new Yt(void 0);this.playingRepresentationInit$=new Yt(void 0);this.error$=new Fm;this.gaps=[];this.subscription=new _m;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=Mt(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 il(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(lo(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,o=this.mediaSource.readyState;o!=="open"&&(n={id:`SegmentEjection_source_${o}`,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(lo(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 o=Math.min(this.bufferLimit,co(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=this.getForwardBufferDuration(n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ye(i,"No init buffer for starting representation"),ye(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Mt(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(re(s)||re(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();$t(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=Mt(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(re(s)||re(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();$t(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=Mt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(p=>p.id===o);c&&this.representations.set(o,c);let d=this.representations.get(o);if(!d||!Me(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 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=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(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){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Mt(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(re(n)||re(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 o=this.getCurrentPosition();$t(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!re(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(re(e)||re(this.downloadingRepresentationId)||re(this.playingRepresentationId)||re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||$t(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}`),re(r)||re(s))return;let a=r.find(p=>e>=p.time.from&&e<p.time.to);$t(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),h=It(i),m=It(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&$t(h)&&$t(m)&&Om(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+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([T,v])=>{let x=v.find($=>e>=$.time.from&&e<$.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&co(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,n),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(d.includes(a))p="high";else{let h=d.at(0);h&&h.time.from-a.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.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)<o),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;$t(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,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;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(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status: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),T=this.preloadOnly&&h<=i+S||r<S&&m-h>=S||m<=i+S;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(Pt(this.sourceBuffer.buffered,h)&&Pt(this.sourceBuffer.buffered,m)))&&g&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<a.length&&(n<=d||o<=l);p++){let h=a[p];if(n+=h.byte.to+1-h.byte.from,o+=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:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Mt(n,async function*(){let d=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=$a(),!d)return;let l=new DataView(d),p=zt(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,n);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]),rl(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())Me(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Mt(a,async function*(){let o=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),lo(window,"online").pipe(Nm()).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=$a(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),rl(o)||(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,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$a(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category: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=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$a();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=zt(a.mime).parseFeedableSegmentChunk(c,this.isLive);d?.byteLength&&(o.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.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 o of this.activeSegments){let{segment:c}=o;if(o.representationId!==t)continue;if(s.aborted){await a();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=zt(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(p,r-d),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===p?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===p&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&A.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Pt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Pt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:at.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Yn(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,n=(!i&&this.failedDownloads>0?Mt(this.destroyAbortController.signal,async function*(){let o=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,zt(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:c,dataView:d,segments:l}=o,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;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,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||re(e))return!1;let r=[],s=0,a=o=>{o.sort((d,l)=>d.from-l.from);let c=[o[0]];for(let d=1;d<o.length;d++){let{from:l,to:p}=o[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(o[d])}return c},n=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let c=Yn(o)?o.size??0:o.byte.to-o.byte.from;s+=c};for(let o of this.segments.values())for(let c of o){let 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"&&n(c)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let c=this.sourceBuffer.buffered.start(o)*1e3,d=this.sourceBuffer.buffered.end(o)*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"};n(p)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+o&&d.status==="fed"&&n(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||!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||re(e)?0:Et(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,o=s.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!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 o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:at.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||re(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=e.some(d=>d.from-t<=a&&d.to+t>=n),c=e.filter(d=>a>=d.from&&a<d.to-t||n>d.from+t&&n<=d.to);o||(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:at.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Qr,assertNever as sl,fromEvent as al,merge as Um,now as Kt,Subject as xi,ValueSubject as zr,flattenObject as ki,ErrorCategory as Pi,SubscriptionRemovable as Hm,getWindow as qr,suppressAbort as Aa}from"@vkontakte/videoplayer-shared/evergreen";var La=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new xi;this.firstBytesManifest$=new xi;this.firstBytesRequested$=new xi;this.firstBytesReceived$=new xi;this.lastConnectionType$=new zr(void 0);this.lastConnectionReused$=new zr(void 0);this.lastRequestFirstBytes$=new zr(void 0);this.lastConnectionMetrics$=new zr(void 0);this.lastDownloadMetrics$=new zr(void 0);this.recoverableError$=new xi;this.error$=new xi;this.abortAllController=new AbortController;this.subscription=new Hm;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=Qr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sa(i)),this.trackRequestStart(i,performance.now());let r=Kt();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Aa);if(s){let a=Kt();t.log("success",ki({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let n=s.headers.get("content-length"),o=0;n&&(o=parseInt(n,10));let c=await s.text();if((!n||isNaN(o)||o<=0)&&(o=new TextEncoder().encode(c).length),o>0){let d=a-r,p=o/(d/1e3)*8/1024,h={bytes:o,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",ki({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=Qr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1,ignoreNetworkErrors: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,qr().location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:sl(t)}this.requestQuic&&(l=vt(l));let m=this.abortAllController.signal,f;if(a){let y=new AbortController;if(f=Um(al(this.abortAllController.signal,"abort"),al(a,"abort")).subscribe(()=>{try{y.abort()}catch(V){Aa(V)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(V){Aa(V)}m=y.signal}let b=0,g=Kt();h.log("startRequest",ki({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let S=yield this.doFetch(l,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),T=Kt();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(T-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=Kt(),V={requestStartedAt:g,requestEndedAt:y,duration:y-g};return h.log("endRequest",ki(V)),h.end(),S.arrayBuffer()}let v=S.body;if(n){let y;[v,y]=S.body.tee(),this.throughputEstimator?.trackStream(y,o)}let x=v.getReader(),$,L=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(L)&&($=L),!$&&i&&($=i.to-i.from+1);let k=$?new Uint8Array($):new Uint8Array(0),R=!1,E=y=>{this.unsubscribeAbortSubscription(f),R=!0,Aa(y)},F=Qr(m,async function*({done:y,value:V}){if(b===0&&(this.lastRequestFirstBytes$.next(Kt()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!y&&V){if(c&&$)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(F,E)}}.bind(this));yield x?.read().then(F,E),this.unsubscribeAbortSubscription(f);let C=Kt(),I={failed:R,requestStartedAt:g,requestEndedAt:C,duration:C-g};if(R)return h.error("endRequest",ki(I)),h.end(),null;if(b>0){let y=C-g,M=b/(y/1e3)*8/1024,_={bytes:b,speed:M,url:e};this.lastDownloadMetrics$.next(_)}return h.log("endRequest",ki(I)),h.end(),k.buffer}.bind(this));this.fetchByteRangeRepresentation=Qr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(d,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:n},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,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(o)f=new DataView(l,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:b}}.bind(this));this.fetchTemplateRepresentation=Qr(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,qr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=ra(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(qr()).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 qr().navigator))return"unknown";let e=qr().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){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:sl(r)}}destroy(){this.abortAllController.abort(),this.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:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}};import{isNullable as jm,ValueSubject as Qm}from"@vkontakte/videoplayer-shared/evergreen";var Wr=class u{constructor(e,t){this.currentRepresentation$=new Qm(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(!jm(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Me(t.segmentReference))}};var Km=["timeupdate","progress","play","seeked","stalled","waiting"],Xm=["timeupdate","progress","loadeddata","playing","seeked"];var Da=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new ol;this.subscriptionRemovable=new Wm;this.representationSubscription=new ol;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=ho(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ve.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ho(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ve.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ca(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=ia(e)??{id:"ManifestParsing",category:Ve.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,d)=>!!(this.element?.canPlayType?.(c)&&Pe()?.isTypeSupported?.(`${c}; codecs="${d}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:d,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((c-o)/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:Ve.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:p,codecs:h})=>i(o,p,h));r[o]=d;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let p=d.map(({codecs:h})=>h);o==="audio"&&(a=fa(p),l=a[0]),o==="video"&&(s=ma(p),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[o]=d.filter(({codecs:h})=>yt(h)===l))}else{let p=new Set(d.map(({codecs:h})=>h));l=ha(p),l&&(r[o]=d.filter(({codecs:h})=>h.startsWith(l)))}if(o==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);A.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&&va(r,f)}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Yr(n)),n}.bind(this));this.initRepresentations=ho(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Yr({initialVideo:e,initialAudio:t,sourceHls:i})),Mi(this.manifest),Mi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(nt(l,"error").pipe(Ra(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ve.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=xs();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ai())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new jr("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Kr(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new jr("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}if(Wr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Wr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xt(...Xm.map(l=>nt(this.element,l))).pipe(Ai(l=>this.element?Et(this.element.buffered,this.element.currentTime*1e3):0),Gr(),Gm(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Xt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Gr()).subscribe(p=>this.liveStreamEndTimestamp=fo())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=mo(p).subscribe(h=>{let m=mt(this.manifestUrlString,2);this.manifestUrlString=ee(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($i({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ai(({isActiveLive:p,isLowLatency:h})=>p&&h),Gr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ei(this.element,1)})),this.representationSubscription.add($i({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ra(({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($i({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ra(({isLive:p})=>p),Gr((p,h)=>h.bufferLength<p.bufferLength),Ai(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=mt(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($i({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 T=1;Math.abs(S)>b&&(T=1+Math.sign(S)*g),Ei(this.element,T)})),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 l=0;this.representationSubscription.add($i({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Ym(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=mt(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,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(p)?p:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let L="none";if(x?L="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),L="active_low_latency"):f!==0&&v<g?L="live_forward_buffering":v<g+T&&(L="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),L==="live_forward_buffering"||L==="live_with_target_offset"){let k=l-(g+S),R=this.normalizeLiveOffset(Math.trunc(f+k/m)),E=Math.abs(R-f),F=0;!p||E<=this.tuning.dashCmafLive.offsetCalculationError?F=f:R>0&&E>this.tuning.dashCmafLive.offsetCalculationError&&(F=R),this.manifestUrlString=ee(this.manifestUrlString,F,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ve.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let o=Xt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Ai(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=Xt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Ai(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=$i({allBuffersFull:o,someBufferEnded:c}).pipe(Gr(),Ai(({allBuffersFull:l,someBufferEnded:p})=>l&&p),Ra(l=>l));if(this.representationSubscription.add(Xt(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:Ve.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Xt(...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:Ve.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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),Me(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Kr(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=mo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ve.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new La({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=st.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Mi(this.element),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"?fo()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){Mi(this.element),this.state$.setState("running"),this.subscription.add(Xt(...Km.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ve.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&&Pt(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 d=this.currentStallDuration$.getValue();d+=a,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=fo(),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,T=this.audioBufferManager&&g<h&&p-f>r;if((!t||c)&&((S||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(n&&d%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:Ve.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",Yr(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=mo(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ve.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Mi(this.element),Mi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Pt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(nl(this.element)||nl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Yr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Kr(this.element)&&Kr(this.source)&&Kr(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=qm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(r&&c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a.push(1/0):a.push(c.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Yr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Jm,map as Zm,observeElementSize as ef,Subscription as tf,ValueSubject as bo,noop as rf}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.subscription=new tf;this.pipSize$=new bo(void 0);this.videoSize$=new bo(void 0);this.elementSize$=new bo(void 0);this.pictureInPictureWindowRemoveEventListener=rf}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ef(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(Jm({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Zm(({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 Jt=class{constructor(e){this.subscription=new df;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new hi;this.stallsManager=new Js;this.elementSizeManager=new Ca;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new gt;this.audioTrackSwitchHistory=new gt;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 af(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(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 Da({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;lf(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:ul.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(go(l=>!!l.length),ll()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Jr(l=>l.to.state!=="none"),Xr());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(go(cl),ll()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Jr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),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(nf(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 T=Rr(S);g.push(T),this.audioTracksMap.set(T,{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(Gn(f));let b=[];for(let g of f.representations){let S=It({...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=$c(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Zr(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$,cf(this.video,"progress")).pipe(go(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(pf(o))),this.subscription.add(n.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,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);cl(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(of({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Zr(Ba([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Jr(l=>l.to)))}).pipe(Jr(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),Xr()).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(Xr()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.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(Gn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Xr()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.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(Wn(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(Jr(({to:l})=>l==="ready"),Xr());this.subscription.add(Zr(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ba(["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(Zr(c,this.player.state$.stateChangeEnded$,Ba(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Zr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ba(["init"])).pipe(uf(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Yi:Gi,t=this.params.tuning.useNewAutoSelectVideoTrack?Qs:js,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:Hs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:k})=>k===n),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.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=Et(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,T=0;if(S){if(o&&!a){let k=e(o,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,k?.bitrate??-1/0)}if(c){let k=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,k?.bitrate??-1/0)}}let v=o;(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:T,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}),$=this.videoTracksMap.get(v)?.representation,L=x&&this.audioTracksMap.get(x)?.representation;if($&&L)return[$,L];if($&&!L&&this.audioTracksMap.size===0)return[$,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:ul.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var es=class extends Jt{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 So,merge as dl,filter as pl,filterChanged as hl,isNullable as vo,map as ml,ValueSubject as yo,isNonNullable as hf}from"@vkontakte/videoplayer-shared/evergreen";var ts=class extends Jt{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 yo(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(hl()).subscribe(o=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!o&&!c&&l?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(ml(o=>o.to)).subscribe(this.player.isLowLatency$)).add(So({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ml(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(So({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:dl(r.playbackRateState$,new yo(1))}).pipe(pl(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,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||vo(d)||(t=o-d)})).add(So({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:dl(r.playbackRateState$,new yo(1))}).pipe(hl((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||vo(o)||vo(c))return;let h=-1*(c-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=Ac(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(pl(o=>hf(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var fl="X-Playback-Duration",To=async u=>{let e=await fetch(u),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(fl)?parseInt(e.headers.get(fl),10):void 0};import{assertNever as wf,combine as xf,debounce as kf,ErrorCategory as Na,filter as Pf,filterChanged as Mf,isNonNullable as Sl,isNullable as Fa,map as vl,merge as $f,observableFrom as Af,Subscription as Lf,ValueSubject as Eo,VideoQuality as Rf}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as mf,getExponentialDelay as ff}from"@vkontakte/videoplayer-shared/evergreen";var bf=u=>{let e=null;if(u.QUALITY&&(e=bt(u.QUALITY)),!e&&u.RESOLUTION){let[t,i]=u.RESOLUTION.split("x").map(r=>parseInt(r,10));e=mf({width:t,height:i})}return e??null},gf=(u,e)=>{let t=u.split(`
|
|
178
|
-
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],n=a.match(/^#EXT-X-STREAM-INF:(.+)/),o=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!n&&!o)){if(n){let c=Object.fromEntries(n[1].split(",").map(b=>b.split("="))),d=c.QUALITY??`stream-${c.BANDWIDTH}`,l=
|
|
179
|
-
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let o=r[++a],c=new URL(o,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=o;let c=new Date(o);c.setMilliseconds(0),s=c.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(vf(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:Ef.WTF,thrown:t,message:e})}};var is=class{constructor(e){this.subscription=new Lf;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Eo([]);this.liveOffset=new Nt;this.manifestStartTime$=new Eo(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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 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 wf(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Rf.INVARIANT,url:this.params.source.url};let t=(i,r)=>Va(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 Oa(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Na.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:Na.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(he(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Eo(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Na.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),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(Mf(),vl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&Sl(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(he(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(xf({startTime:this.manifestStartTime$.pipe(Pf(Sl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:o})=>this.params.output.liveTime$.next(n+o*1e3),i)),this.subscription.add(this.manifests$.pipe(vl(n=>n.map(({id:o,quality:c,size:d,bandwidth:l,fps:p})=>({id:o,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let a=$f(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Af(["init"])).pipe(kf(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(Fa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:o}=t?.to??i??{};for(let[c,d]of[[n,"mq"],[o,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),To(a).then(n=>{if(!Fa(n))this.maxSeekBackTime$.next(n);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Fa(o)||!isFinite(o))&&fetch(a).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,a).toString();To(l).then(p=>{Fa(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:Na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Df,debounce as Cf,ErrorCategory as wo,fromEvent as xo,isNonNullable as Bf,isNullable as Vf,map as yl,merge as Tl,observableFrom as Il,Subscription as Of,ValueSubject as El,VideoQuality as Nf}from"@vkontakte/videoplayer-shared/evergreen";var rs=class{constructor(e){this.subscription=new Of;this.videoState=new O("stopped");this.manifests$=new El([]);this.unmuteAfterBrowserResetsHappened=new El(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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 Df(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality: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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Va(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.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:wo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:wo.WTF,message:"HlsProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(yl(n=>n.to)),this.params.output.playbackState$),this.subscription.add(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)),St({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(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&Bf(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(he(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),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n.state==="requested"&&this.seek(n.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(yl(n=>n.map(({id:o,quality:c,size:d,bandwidth:l,fps:p})=>({id:o,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!A.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Tl(xo(n,"addtrack"),xo(n,"removetrack"),xo(n,"change"),Il(["init"])).subscribe(()=>{for(let o=0;o<n.length;o++)n[o].mode="hidden"},i))}let a=Tl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Il(["init"])).pipe(Cf(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(Vf(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[n,o]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));o&&n&&r.searchParams.set(o,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){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:wo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Ff,assertNonNullable as wl,debounce as _f,ErrorCategory as xl,isHigherOrEqual as Uf,isLowerOrEqual as Hf,isNonNullable as jf,merge as Qf,observableFrom as zf,Subscription as qf,map as Wf}from"@vkontakte/videoplayer-shared/evergreen";var ss=class{constructor(e){this.subscription=new qf;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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:o}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?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 Ff(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:xl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Wf(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),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&&jf(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let o=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(o!==c){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(o),d.playbackRate=o)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Qf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zf(["init"])).pipe(_f(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=vt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(he(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:xl.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=Ge(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(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||ci(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?Hf(r,e.max):!0,o=e.min?Uf(r,e.min):!0;n&&o||i(e)}};import{assertNever as Pl,debounce as Xf,merge as Ml,observableFrom as Jf,Subscription as Zf,map as $l,ValueSubject as eb,ErrorCategory as Po,VideoQuality as tb}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Gf}from"@vkontakte/videoplayer-shared/evergreen";var kl=["stun:videostun.mycdn.me:80"],Yf=1e3,Kf=3,ko=()=>null,_a=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=ko;this.externalStopCallback=ko;this.externalErrorCallback=ko;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:kl}]};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:Gf.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),Yf)}normalizeOptions(e={}){let t={stunServerList:kl,maxRetryNumber:Kf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var as=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new eb(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 Pl(e)}};this.subscription=new Zf,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new _a(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:Po.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Ml(this.videoState.stateChangeStarted$.pipe($l(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe($l(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=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(Be(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Pl(a.to)}},i)).add(Ml(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Jf(["init"])).pipe(Xf(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(he(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:tb.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:Po.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:Po.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Li=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 ns,assertNonNullable as ut,ErrorCategory as Ua,filter as Bl,isNonNullable as Vl,isNullable as ub,map as cb,merge as lb,once as db,Subject as J,Subscription as Ol,ValueSubject as B,flattenObject as Mo,devNull as pb,getWindow as hb}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as ib,map as Al,Subscription as rb,Subject as sb}from"@vkontakte/videoplayer-shared/evergreen";var Ll=u=>new ib(e=>{let t=new rb,i=u.desiredPlaybackState$.stateChangeStarted$.pipe(Al(({from:c,to:d})=>`${c}-${d}`)),r=u.desiredPlaybackState$.stateChangeEnded$,s=u.providerChanged$.pipe(Al(({type:c})=>c!==void 0)),a=new sb,n=0,o="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),o=c,n=window.setTimeout(()=>a.next(c),u.maxTransitionInterval),D({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{D({m:"hangup.cl",id:n}),window.clearTimeout(n),o="unknown",n=0})),t.add(s.subscribe(c=>{n&&(D({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(o),u.maxTransitionInterval),D({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as ab,Subscription as nb,combine as ob,filter as Dl,once as Cl}from"@vkontakte/videoplayer-shared/evergreen";function Rl(){return new(window.AudioContext||window.webkitAudioContext)}var Ri=class u{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new nb;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Dl(s=>!!s.type),Cl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){A.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ob({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Dl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Cl()).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=Rl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:u.errorId,category:ab.VIDEO_PIPELINE,message:e?.message??`${u.errorId} exception`,thrown:e})}};var mb={chunkDuration:5e3,maxParallelRequests:5},os=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 Ol;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=on([...Tc(this.params.tuning),...yc(this.params.tuning)]).filter(c=>Vl(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Mo(s)),this.screenFormatsIterator=new Li(s);let a=[...zn(!0),...zn(!1)];this.chromecastFormatsIterator=new Li(a.filter(c=>Vl(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&n!==1&&Ri.isSupported()&&(this.volumeMultiplierManager=new Ri(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}init(){D.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 Li(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(ub(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Ua.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 ns(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);ut(o);let{useDashProviderVirtual:d,useDashProviderVirtualMobile:l}=this.params.tuning,{isMobile:p}=A.device;return!p&&d||p&&l?new _r({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new es({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ut(o),this.params.tuning.useDashProviderVirtual&&!A.device.isMobile?new wi({...n,source:o}):this.params.tuning.useDashProviderVirtualMobile&&A.device.isMobile?new wi({...n,source:o}):new ts({...n,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ut(o),new rs({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ut(o),new is({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ut(o),new ss({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ut(o),new ec({...n,source:o,config:{...mb,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ut(o),new as({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ns(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 Je){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return ut(c),new Fi({...n,chromecastConnector:c})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ut(o),new ji({...n,connection:o})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ns(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ns(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 ns(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Ol,t=!1,i=0;e.add(lb(this.providerOutput.error$.pipe(Bl(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Ll({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(cb(s=>({id:`ProviderHangup:${s}`,category:Ua.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(Bl(({to:a})=>a==="playing"),db()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=D.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&hb().console.log(`===== DASH_LIVE DEBUG START ====
|
|
177
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var vc=u=>{if(!u?.startsWith("P"))return;let e=(a,n)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(u),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(u,e)=>{let t=u;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,o)=>Sc(s)?n:Sc(o)?s:s.padStart(parseInt(o,10),"0"))}return t},ca=(u,e)=>{let i=new DOMParser().parseFromString(u,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(R=>R.textContent?.trim()??""),n=a.at(0)??"",o=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.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,b;o&&(b={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 g,S=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],v=I.reduce((R,E)=>({...R,[E.id]:E.children}),{}),k=I.reduce((R,E)=>({...R,[E.id]:E.getAttribute("duration")}),{});S?g=vc(S):Object.values(k).filter(R=>R).length&&!o?g=Object.values(k).reduce((R,E)=>R+(vc(E)??0),0):f&&(g=parseInt(f,10));let $=0,L=s.getAttribute("profiles")?.split(",")??[];for(let R of I.map(E=>E.id))for(let E of v[R]){let F=E.getAttribute("id")??"id"+($++).toString(10),C=E.getAttribute("mimeType")??"",T=E.getAttribute("codecs")??"",y=E.getAttribute("contentType")??C?.split("/")[0],V=E.getAttribute("profiles")?.split(",")??[],M=gc(E.getAttribute("lang")??"")??{},_=E.querySelector("Label")?.textContent?.trim()??void 0,W=E.querySelectorAll("Representation"),Z=E.querySelector("SegmentTemplate"),ie=E.querySelector("Role")?.getAttribute("value")??void 0,le=y,de={id:F,language:M.language,isDefault:ie==="main",label:_,codecs:T,hdr:le==="video"&&Qn(T),mime:C,representations:[]};for(let U of W){let N=U.getAttribute("lang")??void 0,pe=_??E.getAttribute("label")??U.getAttribute("label")??void 0,me=U.querySelector("BaseURL")?.textContent?.trim()??"",ae=new URL(me||n,e).toString(),Ae=U.getAttribute("mimeType")??C,lt=U.getAttribute("codecs")??T??"",Oe;if(y==="text"){let xe=U.getAttribute("id")||"",dt=M.privateuse?.includes("x-auto")||xe.includes("_auto"),Le=U.querySelector("SegmentTemplate");if(Le){let Di={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},us=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,cs=parseInt(Le.getAttribute("startNumber")??"",10)??1,Zt=parseInt(Le.getAttribute("timescale")??"",10),Ya=Le.querySelectorAll("SegmentTimeline S")??[],ei=Le.getAttribute("media");if(!ei)continue;let ls=[],ds=0,ps="",ti=0,Ci=cs,fe=0;for(let Ne of Ya){let Rt=parseInt(Ne.getAttribute("d")??"",10),Re=parseInt(Ne.getAttribute("r")??"",10)||0,pt=parseInt(Ne.getAttribute("t")??"",10);fe=Number.isFinite(pt)?pt:fe;let Dt=Rt/Zt*1e3,ii=fe/Zt*1e3;for(let He=0;He<Re+1;He++){let ht=_e(ei,{...Di,segmentNumber:Ci.toString(10),segmentTime:(fe+He*Rt).toString(10)}),ri=(ii??0)+He*Dt,Vi=ri+Dt;Ci++,ls.push({time:{from:ri,to:Vi},url:ht})}fe+=(Re+1)*Rt,ds+=(Re+1)*Dt}ti=fe/Zt*1e3,ps=_e(ei,{...Di,segmentNumber:Ci.toString(10),segmentTime:fe.toString(10)});let Bi={time:{from:ti,to:1/0},url:ps},Ke={type:"template",baseUrl:ae,segmentTemplateUrl:ei,initUrl:"",totalSegmentsDurationMs:ds,segments:ls,nextSegmentBeyondManifest:Bi,timescale:Zt};Oe={id:xe,kind:"text",segmentReference:Ke,profiles:[],duration:g,bitrate:us,mime:"",codecs:"",width:0,height:0,isAuto:dt}}else Oe={id:xe,isAuto:dt,kind:"text",url:ae}}else{let xe=U.getAttribute("contentType")??Ae?.split("/")[0]??y,dt=E.getAttribute("profiles")?.split(",")??[],Le=parseInt(U.getAttribute("width")??"",10),Di=parseInt(U.getAttribute("height")??"",10),us=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,cs=U.getAttribute("frameRate")??"",Zt=U.getAttribute("quality")??void 0,Ya=cs?bc(cs):void 0,ei=U.getAttribute("id")??"id"+($++).toString(10),ls=xe==="video"?`${Di}p`:xe==="audio"?`${us}Kbps`:lt,ds=`${ei}@${ls}`,ps=[...L,...V,...dt],ti,Ci=U.querySelector("SegmentBase"),fe=U.querySelector("SegmentTemplate")??Z;if(Ci){let Ke=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Rt]=Ke.split("-").map(ht=>parseInt(ht,10)),Re={from:Ne,to:Rt},pt=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Dt,ii]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],He=pt?{from:Dt,to:ii}:void 0;ti={type:"byteRange",url:ae,initRange:Re,indexRange:He}}else if(fe){let Ke={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Ne=parseInt(fe.getAttribute("timescale")??"",10),Rt=fe.getAttribute("initialization")??"",Re=fe.getAttribute("media"),pt=parseInt(fe.getAttribute("startNumber")??"",10)??1,Dt=_e(Rt,Ke);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let ii=fe.querySelectorAll("SegmentTimeline S")??[],He=[],ht=0,ri="",Vi=0;if(ii.length){let hs=pt,Fe=0;for(let si of ii){let je=parseInt(si.getAttribute("d")??"",10),Ct=parseInt(si.getAttribute("r")??"",10)||0,ms=parseInt(si.getAttribute("t")??"",10);Fe=Number.isFinite(ms)?ms:Fe;let Ka=je/Ne*1e3,sd=Fe/Ne*1e3;for(let fs=0;fs<Ct+1;fs++){let ad=_e(Re,{...Ke,segmentNumber:hs.toString(10),segmentTime:(Fe+fs*je).toString(10)}),Fo=(sd??0)+fs*Ka,nd=Fo+Ka;hs++,He.push({time:{from:Fo,to:nd},url:ad})}Fe+=(Ct+1)*je,ht+=(Ct+1)*Ka}Vi=Fe/Ne*1e3,ri=_e(Re,{...Ke,segmentNumber:hs.toString(10),segmentTime:Fe.toString(10)})}else if(wh(g)){let Fe=parseInt(fe.getAttribute("duration")??"",10)/Ne*1e3,si=Math.ceil(g/Fe),je=0;for(let Ct=1;Ct<si;Ct++){let ms=_e(Re,{...Ke,segmentNumber:Ct.toString(10),segmentTime:je.toString(10)});He.push({time:{from:je,to:je+Fe},url:ms}),je+=Fe}Vi=je,ri=_e(Re,{...Ke,segmentNumber:si.toString(10),segmentTime:je.toString(10)})}let rd={time:{from:Vi,to:1/0},url:ri};ti={type:"template",baseUrl:ae,segmentTemplateUrl:Re,initUrl:Dt,totalSegmentsDurationMs:ht,segments:He,nextSegmentBeyondManifest:rd,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!xe||!Ae)continue;let Bi={video:"video",audio:"audio",text:"text"}[xe];if(!Bi)continue;le||=Bi,Oe={id:ds,kind:Bi,segmentReference:ti,profiles:ps,duration:g,bitrate:us,mime:Ae,codecs:lt,width:Le,height:Di,fps:Ya,quality:Zt}}de.language||=N,de.label||=pe,de.mime||=Ae,de.codecs||=lt,de.hdr||=le==="video"&&Qn(lt),de.representations.push(Oe)}if(le){let U=r[le].find(N=>N.id===de.id);if(U&&de.representations.every(N=>N.segmentReference.type==="template"))for(let N of U.representations){let pe=de.representations.find(Ae=>Ae.id===N.id);if(!pe)continue;let me=pe.segmentReference,ae=N.segmentReference;ae.segments.push(...me.segments),ae.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[le].push(de)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as pa}from"@vkontakte/videoplayer-shared/evergreen";var la=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(la||{});var da=u=>{let{webmDecodingInfo:e}=A.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(u){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:pa(u)}},yc=({webmCodec:u,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...da(u),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(A.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",...da(u),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...da(u),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...da(u),...s,"HLS","HLS_ONDEMAND"];default:pa(e)}if(A.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:pa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tc=({androidPreferredFormat:u,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,o=A.device.isMac&&A.browser.isSafari;if(A.device.isAndroid)switch(u){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:pa(u)}else A.video.nativeHlsSupported&&!o&&!A.browser.isChromiumBased?n=a:o?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},zn=u=>u?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ha=u=>{if(u.size===0)return;if(u.size===1)return u.values().next().value.split(".").at(0);for(let t of u){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return u.values().next().value.split(".").at(0)},ma=u=>{let e=u.map(i=>yt(i)),{codecs:t}=A.video;return Ph().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})},fa=u=>{let e=u.map(i=>yt(i)),{codecs:t}=A.video;return Mh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},yt=u=>u.split(".")[0].replace("0",""),Ph=()=>["av1","vp9","hev1","avc1"],Mh=()=>["opus","mp4a"];import{abortable as Kn,assertNonNullable as Ye,ErrorCategory as Yh,fromEvent as Kh,getExponentialDelay as Xh,getWindow as Lc,isHigher as Jh,isNonNullable as te,isNullable as ue,once as Zh,Subject as em,Subscription as tm,ValueSubject as Dr}from"@vkontakte/videoplayer-shared/evergreen";var ba=u=>u.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 Si=class extends j{};import{assertNever as $h}from"@vkontakte/videoplayer-shared/evergreen";var ur=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:$h(e)}}};var cr=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 lr=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 dr=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 pr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var jt=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 o=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var br=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 gr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Sr=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 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.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 Tr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Er=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var wr=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.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 xr=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 Pr=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 Mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $r=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 Ar=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 Lh={ftyp:cr,moov:lr,mvhd:dr,moof:pr,mdat:hr,sidx:jt,trak:mr,mdia:vr,mfhd:Er,tkhd:yr,traf:wr,tfhd:kr,tfdt:xr,trun:Pr,minf:Tr,sv3d:fr,st3d:br,prhd:gr,proj:Ir,equi:Sr,uuid:ur,stbl:Mr,stsd:$r,avc1:Ar,unknown:Si},tt=class u{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!ba(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=Lh[e];return i?new i(t,new u):new Si(t,new u)}};var Tt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ba(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 Dh=new TextDecoder("ascii"),Ch=u=>Dh.decode(new DataView(u.buffer,u.byteOffset+4,4))==="ftyp",Bh=u=>{let e=new jt(u,new tt),t=e.earliestPresentationTime/e.timescale*1e3,i=u.byteOffset+u.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},Vh=(u,e)=>{let i=new tt().parse(u),r=new Tt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],o=a[a.length-1],c=n.source.byteOffset,l=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(u.buffer,c,l)},Oh=u=>{let t=new tt().parse(u),i=new Tt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Nh=u=>{let t=new tt().parse(u);return new Tt(t).find("sidx")?.timescale},Fh=(u,e)=>{let i=new tt().parse(u),s=new Tt(i).findAll("traf"),a=s[s.length-1].children.find(l=>l.type==="tfhd"),n=s[s.length-1].children.find(l=>l.type==="tfdt"),o=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return o.sampleDuration.length?c=o.sampleDuration.reduce((l,p)=>l+p,0):c=a.defaultSampleDuration*o.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},_h=u=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new tt().parse(u),r=new Tt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Ic={validateData:Ch,parseInit:_h,getIndexRange:()=>{},parseSegments:Bh,parseFeedableSegmentChunk:Vh,getChunkEndTime:Fh,getServerLatencyTimestamps:Oh,getTimescaleFromIndex:Nh};import{assertNonNullable as qn,isNonNullable as xc,isNullable as Hh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Uh}from"@vkontakte/videoplayer-shared/evergreen";var Ec={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"}},wc=u=>{let e=u.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Lr(u,t),r=i in Ec,s=r?Ec[i].type:"binary",a=u.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let o=new DataView(u.buffer,u.byteOffset+t+1,n-1),c=a&255>>n,d=Lr(o),l=c*2**((n-1)*8)+d,p=t+n,h;return p+l>u.byteLength?h=new DataView(u.buffer,u.byteOffset+p):h=new DataView(u.buffer,u.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Lr=(u,e=u.byteLength)=>{switch(e){case 1:return u.getUint8(0);case 2:return u.getUint16(0);case 3:return u.getUint8(0)*2**16+u.getUint16(1);case 4:return u.getUint32(0);case 5:return u.getUint8(0)*2**32+u.getUint32(1);case 6:return u.getUint16(0)*2**32+u.getUint32(2);case 7:{let t=u.getUint8(0)*281474976710656+u.getUint16(1)*4294967296+u.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(u,e)=>{switch(e){case"int":return u.getInt8(0);case"uint":return Lr(u);case"float":return u.byteLength===4?u.getFloat32(0):u.getFloat64(0);case"string":return new TextDecoder("ascii").decode(u);case"utf8":return new TextDecoder("utf-8").decode(u);case"date":return new Date(Date.UTC(2001,0)+u.getInt8(0)).getTime();case"master":return u;case"binary":return u;default:Uh(e)}},Qt=(u,e)=>{let t=0;for(;t<u.byteLength;){let i=new DataView(u.buffer,u.byteOffset+t),r=wc(i);if(!e(r))return;r.type==="master"&&Qt(r.value,e),t=r.value.byteOffset-u.byteOffset+r.valueSize}},kc=u=>{if(u.getUint32(0)!==440786851)return!1;let e,t,i,r=wc(u);return Qt(r.value,({tag:s,type:a,value:n})=>(s===17143?e=Ue(n,a):s===17026?t=Ue(n,a):s===17029&&(i=Ue(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Pc=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jh=[231,22612,22743,167,171,163,160,175],Qh=u=>{let e,t,i,r,s=!1,a=!1,n=!1,o,c,d=!1,l=0;return Qt(u,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=Ue(m,h);c=Lr(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=Ue(m,h):p===17545?r=Ue(m,h):p===21420&&c===475249515?o=Ue(m,h):p===374648427?Qt(m,({tag:b,type:g,value:S})=>b===30321?(d=Ue(S,g)===1,!1):!0):s&&a&&Pc.includes(p)&&(n=!0),!n}),qn(e,"Failed to parse webm Segment start"),qn(t,"Failed to parse webm Segment end"),qn(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zh=u=>{if(Hh(u.cuesSeekPosition))return;let e=u.segmentStart+u.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qh=(u,e)=>{let t=!1,i=!1,r=n=>xc(n.time)&&xc(n.position),s=[],a;return Qt(u,({tag:n,type:o,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Ue(c,o));break;case 183:break;case 241:a&&(a.position=Ue(c,o));break;default:t&&Pc.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,o)=>{let{time:c,position:d}=n,l=s[o+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}}})},Wh=u=>{let e=0,t=!1;try{Qt(u,i=>i.tag===524531317?i.tagSize<=u.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):jh.includes(i.tag)?(e+i.tagSize<=u.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=u.byteLength&&t?new DataView(u.buffer,u.byteOffset,e):null},Mc={validateData:kc,parseInit:Qh,getIndexRange:zh,parseSegments:qh,parseFeedableSegmentChunk:Wh};var zt=u=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(u);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Mc;case"mp4":return Ic}}throw new ReferenceError(`Unsupported mime type ${u}`)};import{videoSizeToQuality as Gh}from"@vkontakte/videoplayer-shared/evergreen";var It=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a,tvDisabled:n})=>{let o=(s?bt(s):void 0)??Gh({width:e,height:t});return o&&{id:u,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a,tvDisabled:n}},Rr=({id:u,bitrate:e})=>({id:u,bitrate:e}),$c=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Ac=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Wn=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Gn=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Yn=u=>"url"in u,Me=u=>u.type==="template";var vi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,getCurrentStallDuration:n,manifest:o}){this.error$=new em;this.playingRepresentation$=new Dr(void 0);this.playingRepresentationInit$=new Dr(void 0);this.currentSegmentLength$=new Dr(0);this.onLastSegment$=new Dr(!1);this.fullyBuffered$=new Dr(!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 tm;this.startWith=Kn(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.containerParser=zt(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);Ye(i,"No init buffer for starting representation"),Ye(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Kn(this.destroyAbortController.signal,async function*(e,t=!0){if(ue(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);Ye(r,`No such representation ${e}`),Ye(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),a=this.segments.get(r.id);Ye(s,"No init buffer for switching representation"),Ye(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,o=l=>l.segment.bufferStatus!=="fed",c=l=>{let p=this.representations.get(l.representationId);return Ye(p,"No itemRepresentation for previous track before switch"),l.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(p,r)},d=l=>t?o(l)&&c(l):o(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(n),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Kn(this.downloadAbortController.signal,async function*(){let e=Xh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=Lc();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(Kh(i,"online").pipe(Zh()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=a,this.getCurrentStallDuration=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(c=>[c.id,c]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ue(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(s=>s.segment.networkStatus==="downloaded"),i=t[t.length-1],r=te(e)&&te(i)?i.segment.time.to-e:0;return Math.max(r,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 ue(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(e){let t=this.segments.get(e);return(t?t.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=Lc();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=It(e),s=It(t);i=te(r)&&te(s)&&Jh(s.quality,r.quality)}else if(this.kind==="audio"){let r=Rr(e),s=Rr(t);i=te(r?.bitrate)&&te(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():te(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:a,initDataView:n,segments:o}=await s??{};if(this.initDataPromises.delete(e.id),ue(n)||ue(o))return;a&&this.parsedInitData.set(e.id,a);let c=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,o),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:Yh.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition(),t=this.segments.get(this.downloadingRepresentationId??""),i=t?.[t?.length-1];if(ue(e)||ue(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(h=>this.withinInterval(e,h.segment.time)),s=this.bufferPlaybackQueue.find(h=>h.segment.bufferStatus!=="fed"),a=this.initData.get(s?.representationId??""),n=this.bufferPlaybackQueue[0],o=this.downloadAbortController.signal,d=(this.getCurrentStallDuration()??0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&(d&&=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=d?this.getForwardPlaybackBufferDuration()>=l:!0;te(a)&&te(s)&&te(r)&&this.playingRepresentationId!==s.representationId&&this.withinAppendInterval(e,s.segment.time)&&(s===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(a,this.downloadAbortController.signal),this.playingRepresentationId=s.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),te(s)&&this.withinAppendInterval(e,s.segment.time)&&p&&(s.segment.loadedBytes===s.segment.size&&s.segment.bufferStatus==="none"?await this.appendSegmentFully(s,o):await this.appendSegmentPartially(s,o)),te(n)&&this.withinRemoveInterval(e,n.segment.time)&&await this.removeSegment(n,o),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Ye(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ue(t)||ue(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);te(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(ue(t)||t.length===0)return;let i=t[t?.length-1];ue(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){Ye(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;te(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(n=>this.withinInterval(e,n.time))),r=r===-1?0:r;let a=[];for(;r<t.length&&s>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:n,to:o}=t[r].time;s-=o-n,r++}return a}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return te(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return te(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 te(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ue(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(ue(e.segment.data)||ue(e.segment.loadedBytes)||ue(e.segment.feedingBytes)||ue(e.segment.fedBytes)||ue(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||te(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)te(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())te(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(o=>o.segment===n)&&!this.downloadingBufferItems.find(o=>o.segment===n)&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as im,isNonNullable as rm,isNullable as Rc,now as Dc,isAbortError as sm}from"@vkontakte/videoplayer-shared/evergreen";var ga=class extends vi{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=Dc(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),sm(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(oe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(n,o)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Dc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:im.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||Rc(n)||Rc(r)||a.aborted))for(let o of e){let{segment:c}=o,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<s,m=l<=s;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(o),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(o)):rm(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(o))))}}updateRepresentationBaseUrl(e,t){if(oe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as am,isAbortError as nm,isNullable as Xn,now as Cc}from"@vkontakte/videoplayer-shared/evergreen";var yi=class extends vi{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=Cc(),Xn(n))return;let o=e[0],c=new DataView(n);o.segment.size=c.byteLength,o.segment.loadedBytes=c.byteLength,o.segment.data=c,this.onItemFullyDownloaded(o),await this.onDownloadItem(o),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),nm(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=Cc(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,signal:r,representationId:t.id})}catch(o){this.error$.next({id:"SegmentFeeding",category:am.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:o})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!oe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let a=e[0],{segment:n}=a,o=this.representations.get(i);!this.downloadingBufferItems.length||Xn(o)||Xn(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(!oe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as om,ErrorCategory as um,isNullable as it,ValueSubject as Bc}from"@vkontakte/videoplayer-shared/evergreen";var Sa=class extends yi{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Bc(0);this.currentLowLatencySegmentLength$=new Bc(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(it(r)||!oe(r.segmentReference))return;let s=r.segmentReference.segments.map(d=>({...d,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],o=n.at(-1)?.time.to??0,c=s?.findIndex(d=>o>=d.time.from+a&&o<=d.time.to+a);if(c===-1){let d=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,d)}else{let d=s.slice(c+1);this.segments.set(r.id,[...n,...d])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;om(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(it(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(it(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return it(t)||!oe(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),it(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(it(t.segment.data)||it(r)||!oe(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(!oe(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),d=_e(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: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 s=this.tuning.dash.useFetchPriorityHints?i:"auto",a=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,a);let{initMetadata:n,initDataView:o,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),it(o)||it(c))return;n&&this.parsedInitData.set(t.id,n);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(t.id,l),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:um.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 Cr=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new Sa(e,t,i,r):oe(i[0].segmentReference)?new yi(e,t,i,r):new ga(e,t,i,r)}};import{ErrorCategory as dm,fromEvent as pm,isNullable as Ti,Subject as hm,Subscription as mm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as cm,ErrorCategory as Vc,Subject as Oc}from"@vkontakte/videoplayer-shared/evergreen";var lm=18,Nc=!1;try{Nc=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=lm}catch(u){console.error(u)}var Jn=class{constructor(e,t=!1){this.bufferFull$=new Oc;this.error$=new Oc;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 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)};Nc&&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: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:cm(t)}}},Fc=Jn;var Et=(u,e)=>{let t=0;for(let i=0;i<u.length;i++){let r=u.start(i)*1e3,s=u.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Br=class{constructor(e){this.error$=new hm;this.subscription=new mm;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Fc(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(pm(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:dm.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(Ti(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(){!Ti(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Ti(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 Ti(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ti(e)?0:Et(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Ti(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 va=(u,e)=>{u.video.forEach(t=>{t.representations.forEach(i=>{let{height:r,codecs:s,fps:a}=i,n=e.find(([c,d,l])=>c===`${r}p`&&yt(s)===l)?.[1],o=_c(n)&&_c(a)&&a>n;i.tvDisabled=o})})};function _c(u){return typeof u=="number"&&Number.isInteger(u)}var vm=["timeupdate","progress","play","seeked","stalled","waiting"],Qc=["timeupdate","progress","loadeddata","playing","seeked"],Ii=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new jc;this.subscriptionRemovable=new Sm;this.representationSubscription=new jc;this.forceEnded$=new kt;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 kt;this.manifestRequested=new kt;this.manifestReceived=new kt;this.firstBytesRequested=new kt;this.firstBytesReceived=new kt;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 kt;this.fetcherError$=new kt;this.initRepresentations=Uc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ya({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,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),rt(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=Uc(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Or(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qt.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 na({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:qt.PARSER,message:"No playable video representations"})}initBuffer(){rt(this.element),this.state$.setState("running"),this.subscription.add(Nr(...vm.map(t=>Wt(this.element,t)),Wt(Vr(),"online"),Hc(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:qt.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Nr(...e.map(t=>Wt(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Wt(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Hc(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:qt.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){rt(this.element),rt(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,A.browser.isSafari?(await this.audioBufferManager?.seek(i),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i)),this.tracer.log("seek",ya({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){wt(this.element)&&wt(this.source)&&wt(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(e){return Math.max(this.videoBufferManager?.calculateDurationFromSegments(e)||0,this.audioBufferManager?.calculateDurationFromSegments(e)||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&&Vr().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),wt(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(Or(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(){rt(this.element),rt(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)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",ya(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=gm(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,d=wt(this.videoBufferManager)&&o<s&&r-a>i,l=wt(this.audioBufferManager)&&c<s&&r-n>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Or(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",ya(i)),i}parseManifest(e){try{return ca(e??"",this.manifestUrlString)}catch(t){let i=ia(e)??{id:"ManifestParsing",category:qt.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&Pe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:l,codecs:p})=>i(n,l,p));t[n]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);n==="audio"&&(s=fa(l),d=s[0]),n==="video"&&(r=ma(l),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[n]=c.filter(({codecs:p})=>yt(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=ha(l),d&&(t[n]=c.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let l=this.tuning.preferHDR,p=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);A.display.isHDR&&l&&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&&va(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){rt(this.manifest),rt(this.element);let s=c=>{this.representationSubscription.add(Wt(c,"error").pipe(Zn(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=ks();let a=Vr().document,n=a.createElement("source");if(s(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ai())if(r){let c=a.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Br(this.source),this.videoBufferManager=Cr.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],wt(i)){this.audioNativeBufferManager=new Br(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=Cr.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=Vr().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:qt.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&&Vr().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(Nr(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),rt(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(Nr(...Qc.map(e=>Wt(this.element,e))).pipe(eo(e=>this.videoBufferManager?.getPlaybackBufferState()),Zn(wt),eo(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Nr(...Qc.map(e=>Wt(this.element,e))).pipe(eo(e=>Math.min(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),fm()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Zn(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=bm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Or(this.element)||Or(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 Ta,combine as ym,ErrorCategory as Tm,filter as to,filterChanged as Im,fromEvent as Em,isNonNullable as wm,map as io,merge as Fr}from"@vkontakte/videoplayer-shared/evergreen";var Ia=class extends Ii{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){Ta(this.manifest),Ta(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),oe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){Ta(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Ta(this.element);let e=Fr(Em(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(to(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Fr(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Fr(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(io(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=Fr(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(io(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=ym({allBuffersFull:e,someBufferEnded:t}).pipe(Im(),io(({allBuffersFull:s,someBufferEnded:a})=>s&&a),to(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:Tm.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(Fr(this.forceEnded$,i).pipe(to(s=>wm(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var _r=class extends _t{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(xm(),km(s=>Pm(s))).subscribe(s=>{let a=this.player.calculateDurationFromSegments(s);a&&this.params.output.duration$.next(a/1e3)},r))}getPlayer(){return new Ia({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{combine as ao,merge as Kc,filter as Xc,filterChanged as Jc,isNullable as no,map as Zc,ValueSubject as oo,isNonNullable as Bm}from"@vkontakte/videoplayer-shared/evergreen";import{isNullable as Mm,ValueSubject as zc}from"@vkontakte/videoplayer-shared/evergreen";var xt=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 zc(e.initial),this.debounced$=new zc(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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)&&(Mm(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 Ea=class extends xt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=et(this.slow,e,this.params.emaAlphaSlow),this.fast=et(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wa=class extends xt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=et(this.emaSmoothed,e,this.params.emaAlpha);let i=oc(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ka=class extends xt{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?et(this.smoothed,t,this.params.emaAlpha):t}};var st=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ea({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new wa({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 ka({initial:e,label:"liveEdgeDelay",...t})}};import{assertNonNullable as Gt,combine as Hr,ErrorCategory as xa,filter as Pa,filterChanged as ro,fromEvent as qc,interval as Rm,isNonNullable as Dm,isNullable as Wc,map as so,now as Gc,throttle as Cm}from"@vkontakte/videoplayer-shared/evergreen";var Ei=(u,e)=>{u&&u.playbackRate!==e&&(u.playbackRate=e)};import{isNullable as $m,ValueSubject as Am}from"@vkontakte/videoplayer-shared/evergreen";var Ur=class u{constructor(e,t){this.currentRepresentation$=new Am(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(!$m(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&oe(t.segmentReference))}};var Ma=class extends Ii{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=st.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){Gt(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){let i=this.videoBufferManager?.getRepresentationInitialTime()??0;await super.seek(i,!1)}async tick(){await super.tick();let t=(this.element?.currentTime??0)*1e3;this.liveTextManager?.maintain(t)}setSourceDuration(){Gt(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,s=this.liveStreamStatus$.getValue()==="active";return(!i||s)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,s=this.currentStallDuration$.getValue(),n=this.liveStreamStatus$.getValue()==="active";if(s%i===0){let o=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=o,!n&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(o),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(o).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:xa.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){let t=await super.updateManifest();if(Wc(t))return null;if(Wc(t.live))return this.error$.next({id:"ManifestParsing",category:xa.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:s,streamIsAlive:a}=t.live,n=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*n),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let o="active";if(a||(o=s?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(o),this.bufferManagers.forEach(d=>d.updateManifest(t)),this.liveTextManager?.updateLive(t),a&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let d=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(d).catch(l=>{this.error$.next({id:"updateManifest",category:xa.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:l})})}return t}prepareManifestUrlString(t,i){return ee(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?Gc()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=ee(this.manifestUrlString,r,2)}createBuffers(t,i,r,s){Gt(this.manifest),super.createBuffers(t,i,r,s),Ur.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ur(this.manifest.streams.text,t))}initRepresentationSubscriptions(){Gt(this.element),Gt(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),Dm(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){Gt(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>Rm(t).subscribe(async r=>{let s=mt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,s+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add(qc(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add(qc(this.element,"play").subscribe(r=>this.livePauseWatchdogSubscription?.unsubscribe()))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe(ro()).subscribe(i=>this.liveStreamEndTimestamp=Gc())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add(Hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(so(({isActiveLive:t,isLowLatency:i})=>t&&i),ro(),Pa(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Ei(this.element,1))),this.representationSubscription.add(Hr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Pa(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let s=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,a=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,n=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=t-s,c=1;Math.abs(o)>a&&(c=1+Math.sign(o)*n),Ei(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add(Hr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Pa(({bufferLength:r,isActiveLive:s,isLowLatency:a})=>s&&a&&!!r),so(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{let s=0;if(r){let a=(this.element?.currentTime??0)*1e3;s=Math.min(...i.map(o=>o.getLiveSegmentsToLoadState(this.manifest)?.to??a))-a}this.liveLoadBufferLength$.getValue()!==s&&this.liveLoadBufferLength$.next(s)})),this.representationSubscription.add(Hr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe(Pa(({isLive:r})=>r),ro((r,s)=>s.bufferLength<r.bufferLength),so(({rtt:r,bufferLength:s,segmentServerLatency:a})=>{let n=mt(this.manifestUrlString,2);return(r/2+s+a+n)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add(Hr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Cm(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:s})=>{Gt(this.element);let a=this.element.playbackRate,n=mt(this.manifestUrlString,2),o=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(o,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*a),d=this.tuning.dashCmafLive.normalizedActualBufferOffset*a,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*a,p=isFinite(r)?r:s,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=o<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let f="none";if(h?f="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(b=>b.proceedLowLatencyLive()),f="active_low_latency"):n!==0&&p<c?f="live_forward_buffering":p<c+l&&(f="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),f==="live_forward_buffering"||f==="live_with_target_offset"){let b=i-(c+d),g=this.normalizeLiveOffset(Math.trunc(n+b/a)),S=Math.abs(g-n),I=0;!r||S<=this.tuning.dashCmafLive.offsetCalculationError?I=n:g>0&&S>this.tuning.dashCmafLive.offsetCalculationError&&(I=g),this.manifestUrlString=ee(this.manifestUrlString,I,2)}(f==="live_with_target_offset"||f==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:xa.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var wi=class extends _t{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Ma({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let n=new oo(1);a(r.playbackRateState$,n),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Jc()).subscribe(o=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!o&&!c&&l?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Zc(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ao({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Zc(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o+c:void 0)).subscribe(i.liveTime$)).add(ao({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Kc(r.playbackRateState$,new oo(1))}).pipe(Xc(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,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||no(d)||(t=o-d)})).add(ao({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Kc(r.playbackRateState$,new oo(1))}).pipe(Jc((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||no(o)||no(c))return;let h=-1*(c-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=sc(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Xc(o=>Bm(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as nf,assertNonNullable as of,combine as uf,debounce as cf,ErrorCategory as cl,filter as go,filterChanged as Xr,fromEvent as lf,isNonNullable as ll,isNullable as df,map as Jr,merge as Zr,observableFrom as Ba,once as dl,Subscription as pf,throttle as hf}from"@vkontakte/videoplayer-shared/evergreen";var Pt=(u,e,t=0)=>{for(let i=0;i<u.length;i++)if(u.start(i)*1e3-t<=e&&u.end(i)*1e3+t>e)return!0;return!1};import{abortable as ho,assertNonNullable as Mi,combine as $i,ErrorCategory as Ve,filter as Ra,filterChanged as Gr,flattenObject as Yr,fromEvent as nt,getTraceSubscriptionMethod as Wm,interval as mo,isNonNullable as Kr,isNullable as ol,map as Ai,merge as Xt,now as fo,Subject as ot,Subscription as ul,SubscriptionRemovable as Gm,tap as Ym,throttle as Km,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Vm,ErrorCategory as el,Subject as tl}from"@vkontakte/videoplayer-shared/evergreen";var Om=18,il=!1;try{il=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=Om}catch(u){console.error(u)}var uo=class{constructor(e,t=!1){this.bufferFull$=new tl;this.error$=new tl;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:el.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)};il&&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:el.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:Vm(t)}}},rl=uo;var co=u=>{let e=0;for(let t=0;t<u.length;t++)e+=u.end(t)-u.start(t);return e*1e3};import{abortable as Mt,assertNonNullable as ye,ErrorCategory as at,fromEvent as lo,getExponentialDelay as po,isHigher as Nm,isNonNullable as $t,isNullable as re,now as $a,once as Fm,Subject as _m,Subscription as Um,ValueSubject as Yt,isAbortError as sl}from"@vkontakte/videoplayer-shared/evergreen";var jr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new Yt(0);this.currentLowLatencySegmentLength$=new Yt(0);this.currentSegmentLength$=new Yt(0);this.onLastSegment$=new Yt(!1);this.fullyBuffered$=new Yt(!1);this.playingRepresentation$=new Yt(void 0);this.playingRepresentationInit$=new Yt(void 0);this.error$=new _m;this.gaps=[];this.subscription=new Um;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=Mt(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 rl(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(lo(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,o=this.mediaSource.readyState;o!=="open"&&(n={id:`SegmentEjection_source_${o}`,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(lo(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 o=Math.min(this.bufferLimit,co(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=this.getForwardBufferDuration(n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ye(i,"No init buffer for starting representation"),ye(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Mt(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(re(s)||re(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();$t(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=Mt(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(re(s)||re(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();$t(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=Mt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(p=>p.id===o);c&&this.representations.set(o,c);let d=this.representations.get(o);if(!d||!Me(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 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=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(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){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Mt(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(re(n)||re(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 o=this.getCurrentPosition();$t(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!re(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(re(e)||re(this.downloadingRepresentationId)||re(this.playingRepresentationId)||re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||$t(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}`),re(r)||re(s))return;let a=r.find(p=>e>=p.time.from&&e<p.time.to);$t(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),h=It(i),m=It(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&$t(h)&&$t(m)&&Nm(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+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([I,v])=>{let k=v.find($=>e>=$.time.from&&e<$.time.to);return{representationId:I,status:k?.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)&&co(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,n),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(d.includes(a))p="high";else{let h=d.at(0);h&&h.time.from-a.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.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)<o),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;$t(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,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;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(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status: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)&&!(Pt(this.sourceBuffer.buffered,h)&&Pt(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<a.length&&(n<=d||o<=l);p++){let h=a[p];if(n+=h.byte.to+1-h.byte.from,o+=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:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Mt(n,async function*(){let d=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=$a(),!d)return;let l=new DataView(d),p=zt(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,n);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]),sl(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())Me(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Mt(a,async function*(){let o=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),lo(window,"online").pipe(Fm()).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=$a(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),sl(o)||(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,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$a(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category: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=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$a();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=zt(a.mime).parseFeedableSegmentChunk(c,this.isLive);d?.byteLength&&(o.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.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 o of this.activeSegments){let{segment:c}=o;if(o.representationId!==t)continue;if(s.aborted){await a();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=zt(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(p,r-d),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===p?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===p&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&A.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Pt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Pt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:at.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Yn(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,n=(!i&&this.failedDownloads>0?Mt(this.destroyAbortController.signal,async function*(){let o=po(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,zt(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:c,dataView:d,segments:l}=o,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;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,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||re(e))return!1;let r=[],s=0,a=o=>{o.sort((d,l)=>d.from-l.from);let c=[o[0]];for(let d=1;d<o.length;d++){let{from:l,to:p}=o[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(o[d])}return c},n=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let c=Yn(o)?o.size??0:o.byte.to-o.byte.from;s+=c};for(let o of this.segments.values())for(let c of o){let 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"&&n(c)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let c=this.sourceBuffer.buffered.start(o)*1e3,d=this.sourceBuffer.buffered.end(o)*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"};n(p)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+o&&d.status==="fed"&&n(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||!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||re(e)?0:Et(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,o=s.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!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 o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:at.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(re(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||re(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=e.some(d=>d.from-t<=a&&d.to+t>=n),c=e.filter(d=>a>=d.from&&a<d.to-t||n>d.from+t&&n<=d.to);o||(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:at.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Qr,assertNever as al,fromEvent as nl,merge as Hm,now as Kt,Subject as ki,ValueSubject as zr,flattenObject as xi,ErrorCategory as Pi,SubscriptionRemovable as jm,getWindow as qr,suppressAbort as Aa}from"@vkontakte/videoplayer-shared/evergreen";var La=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new ki;this.firstBytesManifest$=new ki;this.firstBytesRequested$=new ki;this.firstBytesReceived$=new ki;this.lastConnectionType$=new zr(void 0);this.lastConnectionReused$=new zr(void 0);this.lastRequestFirstBytes$=new zr(void 0);this.lastConnectionMetrics$=new zr(void 0);this.lastDownloadMetrics$=new zr(void 0);this.recoverableError$=new ki;this.error$=new ki;this.abortAllController=new AbortController;this.subscription=new jm;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=Qr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sa(i)),this.trackRequestStart(i,performance.now());let r=Kt();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Aa);if(s){let a=Kt();t.log("success",xi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let n=s.headers.get("content-length"),o=0;n&&(o=parseInt(n,10));let c=await s.text();if((!n||isNaN(o)||o<=0)&&(o=new TextEncoder().encode(c).length),o>0){let d=a-r,p=o/(d/1e3)*8/1024,h={bytes:o,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",xi({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=Qr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1,ignoreNetworkErrors: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,qr().location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:al(t)}this.requestQuic&&(l=vt(l));let m=this.abortAllController.signal,f;if(a){let y=new AbortController;if(f=Hm(nl(this.abortAllController.signal,"abort"),nl(a,"abort")).subscribe(()=>{try{y.abort()}catch(V){Aa(V)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(V){Aa(V)}m=y.signal}let b=0,g=Kt();h.log("startRequest",xi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let S=yield this.doFetch(l,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),I=Kt();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=Kt(),V={requestStartedAt:g,requestEndedAt:y,duration:y-g};return h.log("endRequest",xi(V)),h.end(),S.arrayBuffer()}let v=S.body;if(n){let y;[v,y]=S.body.tee(),this.throughputEstimator?.trackStream(y,o)}let k=v.getReader(),$,L=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(L)&&($=L),!$&&i&&($=i.to-i.from+1);let x=$?new Uint8Array($):new Uint8Array(0),R=!1,E=y=>{this.unsubscribeAbortSubscription(f),R=!0,Aa(y)},F=Qr(m,async function*({done:y,value:V}){if(b===0&&(this.lastRequestFirstBytes$.next(Kt()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!y&&V){if(c&&$)x.set(V,b),b+=V.byteLength;else{let M=new Uint8Array(x.length+V.length);M.set(x),M.set(V,x.length),x=M,b+=V.byteLength}r?.(new DataView(x.buffer),b),yield k?.read().then(F,E)}}.bind(this));yield k?.read().then(F,E),this.unsubscribeAbortSubscription(f);let C=Kt(),T={failed:R,requestStartedAt:g,requestEndedAt:C,duration:C-g};if(R)return h.error("endRequest",xi(T)),h.end(),null;if(b>0){let y=C-g,M=b/(y/1e3)*8/1024,_={bytes:b,speed:M,url:e};this.lastDownloadMetrics$.next(_)}return h.log("endRequest",xi(T)),h.end(),x.buffer}.bind(this));this.fetchByteRangeRepresentation=Qr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(d,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:n},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,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(o)f=new DataView(l,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:b}}.bind(this));this.fetchTemplateRepresentation=Qr(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,qr().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=ra(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(qr()).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 qr().navigator))return"unknown";let e=qr().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){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:al(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:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Pi.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}};import{isNullable as Qm,ValueSubject as zm}from"@vkontakte/videoplayer-shared/evergreen";var Wr=class u{constructor(e,t){this.currentRepresentation$=new zm(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(!Qm(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Me(t.segmentReference))}};var Xm=["timeupdate","progress","play","seeked","stalled","waiting"],Jm=["timeupdate","progress","loadeddata","playing","seeked"];var Da=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new ul;this.subscriptionRemovable=new Gm;this.representationSubscription=new ul;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=ho(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ve.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ho(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ve.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ca(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=ia(e)??{id:"ManifestParsing",category:Ve.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,d)=>!!(this.element?.canPlayType?.(c)&&Pe()?.isTypeSupported?.(`${c}; codecs="${d}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:d,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((c-o)/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:Ve.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:p,codecs:h})=>i(o,p,h));r[o]=d;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let p=d.map(({codecs:h})=>h);o==="audio"&&(a=fa(p),l=a[0]),o==="video"&&(s=ma(p),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[o]=d.filter(({codecs:h})=>yt(h)===l))}else{let p=new Set(d.map(({codecs:h})=>h));l=ha(p),l&&(r[o]=d.filter(({codecs:h})=>h.startsWith(l)))}if(o==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);A.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&&va(r,f)}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Yr(n)),n}.bind(this));this.initRepresentations=ho(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Yr({initialVideo:e,initialAudio:t,sourceHls:i})),Mi(this.manifest),Mi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(nt(l,"error").pipe(Ra(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ve.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ks();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ai())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new jr("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Kr(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new jr("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}if(Wr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Wr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xt(...Jm.map(l=>nt(this.element,l))).pipe(Ai(l=>this.element?Et(this.element.buffered,this.element.currentTime*1e3):0),Gr(),Ym(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Xt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Gr()).subscribe(p=>this.liveStreamEndTimestamp=fo())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=mo(p).subscribe(h=>{let m=mt(this.manifestUrlString,2);this.manifestUrlString=ee(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($i({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ai(({isActiveLive:p,isLowLatency:h})=>p&&h),Gr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ei(this.element,1)})),this.representationSubscription.add($i({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ra(({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($i({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ra(({isLive:p})=>p),Gr((p,h)=>h.bufferLength<p.bufferLength),Ai(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=mt(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($i({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),Ei(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 l=0;this.representationSubscription.add($i({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Km(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=mt(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,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let L="none";if(k?L="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(x=>x.proceedLowLatencyLive()),L="active_low_latency"):f!==0&&v<g?L="live_forward_buffering":v<g+I&&(L="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),L==="live_forward_buffering"||L==="live_with_target_offset"){let x=l-(g+S),R=this.normalizeLiveOffset(Math.trunc(f+x/m)),E=Math.abs(R-f),F=0;!p||E<=this.tuning.dashCmafLive.offsetCalculationError?F=f:R>0&&E>this.tuning.dashCmafLive.offsetCalculationError&&(F=R),this.manifestUrlString=ee(this.manifestUrlString,F,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ve.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let o=Xt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Ai(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=Xt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Ai(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=$i({allBuffersFull:o,someBufferEnded:c}).pipe(Gr(),Ai(({allBuffersFull:l,someBufferEnded:p})=>l&&p),Ra(l=>l));if(this.representationSubscription.add(Xt(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:Ve.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Xt(...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:Ve.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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),Me(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Kr(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=mo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ve.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new La({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=st.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Mi(this.element),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"?fo()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){Mi(this.element),this.state$.setState("running"),this.subscription.add(Xt(...Xm.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ve.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&&Pt(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 d=this.currentStallDuration$.getValue();d+=a,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=fo(),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)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(n&&d%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(k=>{this.error$.next({id:"stallIntervalCallback",category:Ve.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),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",Yr(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=mo(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ve.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Mi(this.element),Mi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Pt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ol(this.element)||ol(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Yr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Kr(this.element)&&Kr(this.source)&&Kr(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=Wm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(r&&c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a.push(1/0):a.push(c.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Yr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Zm,map as ef,observeElementSize as tf,Subscription as rf,ValueSubject as bo,noop as sf}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.subscription=new rf;this.pipSize$=new bo(void 0);this.videoSize$=new bo(void 0);this.elementSize$=new bo(void 0);this.pictureInPictureWindowRemoveEventListener=sf}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(tf(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(Zm({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ef(({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 Jt=class{constructor(e){this.subscription=new pf;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new hi;this.stallsManager=new Js;this.elementSizeManager=new Ca;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new gt;this.audioTrackSwitchHistory=new gt;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 nf(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(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 Da({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;df(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:cl.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(go(l=>!!l.length),dl()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Jr(l=>l.to.state!=="none"),Xr());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(go(ll),dl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Jr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),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(of(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=Rr(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(Gn(f));let b=[];for(let g of f.representations){let S=It({...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=$c(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Zr(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$,lf(this.video,"progress")).pipe(go(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(hf(o))),this.subscription.add(n.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,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);ll(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(uf({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Zr(Ba([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Jr(l=>l.to)))}).pipe(Jr(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),Xr()).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(Xr()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.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(Gn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Xr()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.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(Wn(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(Jr(({to:l})=>l==="ready"),Xr());this.subscription.add(Zr(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ba(["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(Zr(c,this.player.state$.stateChangeEnded$,Ba(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Zr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ba(["init"])).pipe(cf(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Yi:Gi,t=this.params.tuning.useNewAutoSelectVideoTrack?Qs:js,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:Hs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:x})=>x===n),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:x})=>x===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Et(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:x})=>x===g?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(o&&!a){let x=e(o,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,x?.bitrate??-1/0)}if(c){let x=e(c,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,x?.bitrate??-1/0)}}let v=o;(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 k=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}),$=this.videoTracksMap.get(v)?.representation,L=k&&this.audioTracksMap.get(k)?.representation;if($&&L)return[$,L];if($&&!L&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cl.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.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML),this.tracer.end()}};var es=class extends Jt{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 So,merge as pl,filter as hl,filterChanged as ml,isNullable as vo,map as fl,ValueSubject as yo,isNonNullable as mf}from"@vkontakte/videoplayer-shared/evergreen";var ts=class extends Jt{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 yo(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(ml()).subscribe(o=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!o&&!c&&l?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(fl(o=>o.to)).subscribe(this.player.isLowLatency$)).add(So({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fl(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(So({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:pl(r.playbackRateState$,new yo(1))}).pipe(hl(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,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||vo(d)||(t=o-d)})).add(So({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:pl(r.playbackRateState$,new yo(1))}).pipe(ml((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||vo(o)||vo(c))return;let h=-1*(c-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=Ac(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(hl(o=>mf(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var bl="X-Playback-Duration",To=async u=>{let e=await fetch(u),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(bl)?parseInt(e.headers.get(bl),10):void 0};import{assertNever as kf,combine as xf,debounce as Pf,ErrorCategory as Na,filter as Mf,filterChanged as $f,isNonNullable as vl,isNullable as Fa,map as yl,merge as Af,observableFrom as Lf,Subscription as Rf,ValueSubject as Eo,VideoQuality as Df}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as ff,getExponentialDelay as bf}from"@vkontakte/videoplayer-shared/evergreen";var gf=u=>{let e=null;if(u.QUALITY&&(e=bt(u.QUALITY)),!e&&u.RESOLUTION){let[t,i]=u.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ff({width:t,height:i})}return e??null},Sf=(u,e)=>{let t=u.split(`
|
|
178
|
+
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],n=a.match(/^#EXT-X-STREAM-INF:(.+)/),o=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!n&&!o)){if(n){let c=Object.fromEntries(n[1].split(",").map(b=>b.split("="))),d=c.QUALITY??`stream-${c.BANDWIDTH}`,l=gf(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();l&&i.push({id:d,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(o){let c=Object.fromEntries(o[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=c.URI?.replace(/playlist$/,"subtitles.vtt"),l=c.LANGUAGE,p=c.NAME;d&&l&&r.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},vf=u=>new Promise(e=>{setTimeout(()=>{e()},u)}),Io=0,gl=async(u,e=u,t,i)=>{let s=await(await fetch(u,i)).text();Io+=1;try{let{qualityManifests:a,textTracks:n}=Sf(s,e);return{qualityManifests:a,textTracks:n}}catch{if(Io<=t.manifestRetryMaxCount)return await vf(bf(Io-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gl(u,e,t)}return{qualityManifests:[],textTracks:[]}},Va=gl;import{isNonNullable as yf,Subscription as Tf,throttle as If,ValueSubject as Sl,Subject as Ef,ErrorCategory as wf}from"@vkontakte/videoplayer-shared/evergreen";var Oa=class{constructor(e,t,i,r,s){this.subscription=new Tf;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Sl(null);this.getCurrentTime$=new Sl(null);this.error$=new Ef;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(If(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 o=r[++a],c=new URL(o,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=o;let c=new Date(o);c.setMilliseconds(0),s=c.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(yf(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:wf.WTF,thrown:t,message:e})}};var is=class{constructor(e){this.subscription=new Rf;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Eo([]);this.liveOffset=new Nt;this.manifestStartTime$=new Eo(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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 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 kf(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Df.INVARIANT,url:this.params.source.url};let t=(i,r)=>Va(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 Oa(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Na.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:Na.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(he(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Eo(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Na.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),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($f(),yl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&vl(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(he(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(xf({startTime:this.manifestStartTime$.pipe(Mf(vl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:o})=>this.params.output.liveTime$.next(n+o*1e3),i)),this.subscription.add(this.manifests$.pipe(yl(n=>n.map(({id:o,quality:c,size:d,bandwidth:l,fps:p})=>({id:o,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Af(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Lf(["init"])).pipe(Pf(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,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){let e=this.selectManifest();if(Fa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:o}=t?.to??i??{};for(let[c,d]of[[n,"mq"],[o,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),To(a).then(n=>{if(!Fa(n))this.maxSeekBackTime$.next(n);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Fa(o)||!isFinite(o))&&fetch(a).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,a).toString();To(l).then(p=>{Fa(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Cf,debounce as Bf,ErrorCategory as wo,fromEvent as ko,isNonNullable as Vf,isNullable as Of,map as Tl,merge as Il,observableFrom as El,Subscription as Nf,ValueSubject as wl,VideoQuality as Ff}from"@vkontakte/videoplayer-shared/evergreen";var rs=class{constructor(e){this.subscription=new Nf;this.videoState=new O("stopped");this.manifests$=new wl([]);this.unmuteAfterBrowserResetsHappened=new wl(!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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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 Cf(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ff.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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Va(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.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:wo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let n=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:wo.WTF,message:"HlsProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Tl(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)),St({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(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&Vf(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(he(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),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n.state==="requested"&&this.seek(n.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Tl(n=>n.map(({id:o,quality:c,size:d,bandwidth:l,fps:p})=>({id:o,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!A.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Il(ko(n,"addtrack"),ko(n,"removetrack"),ko(n,"change"),El(["init"])).subscribe(()=>{for(let o=0;o<n.length;o++)n[o].mode="hidden"},i))}let a=Il(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,El(["init"])).pipe(Bf(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,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){let e=this.selectManifest();if(Of(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[n,o]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));o&&n&&r.searchParams.set(o,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as _f,assertNonNullable as kl,debounce as Uf,ErrorCategory as xl,isHigherOrEqual as Hf,isLowerOrEqual as jf,isNonNullable as Qf,merge as zf,observableFrom as qf,Subscription as Wf,map as Gf}from"@vkontakte/videoplayer-shared/evergreen";var ss=class{constructor(e){this.subscription=new Wf;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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:o}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?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 _f(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:xl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=we(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Gf(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),St({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),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&&Qf(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let o=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(o!==c){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(o),d.playbackRate=o)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=zf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qf(["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,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;kl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];kl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=vt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(he(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.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=Ge(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(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||ci(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?jf(r,e.max):!0,o=e.min?Hf(r,e.min):!0;n&&o||i(e)}};import{assertNever as Ml,debounce as Jf,merge as $l,observableFrom as Zf,Subscription as eb,map as Al,ValueSubject as tb,ErrorCategory as Po,VideoQuality as ib}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Yf}from"@vkontakte/videoplayer-shared/evergreen";var Pl=["stun:videostun.mycdn.me:80"],Kf=1e3,Xf=3,xo=()=>null,_a=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=xo;this.externalStopCallback=xo;this.externalErrorCallback=xo;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:Pl}]};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:Yf.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),Kf)}normalizeOptions(e={}){let t={stunServerList:Pl,maxRetryNumber:Xf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var as=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new tb(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 Ml(e)}};this.subscription=new eb,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new _a(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,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Po.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add($l(this.videoState.stateChangeStarted$.pipe(Al(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Al(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(Be(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Ml(a.to)}},i)).add($l(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Zf(["init"])).pipe(Jf(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(he(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:ib.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:Po.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Po.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Li=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 ns,assertNonNullable as ut,ErrorCategory as Ua,filter as Vl,isNonNullable as Ol,isNullable as cb,map as lb,merge as db,once as pb,Subject as J,Subscription as Nl,ValueSubject as B,flattenObject as Mo,devNull as hb,getWindow as mb}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as rb,map as Ll,Subscription as sb,Subject as ab}from"@vkontakte/videoplayer-shared/evergreen";var Rl=u=>new rb(e=>{let t=new sb,i=u.desiredPlaybackState$.stateChangeStarted$.pipe(Ll(({from:c,to:d})=>`${c}-${d}`)),r=u.desiredPlaybackState$.stateChangeEnded$,s=u.providerChanged$.pipe(Ll(({type:c})=>c!==void 0)),a=new ab,n=0,o="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),o=c,n=window.setTimeout(()=>a.next(c),u.maxTransitionInterval),D({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{D({m:"hangup.cl",id:n}),window.clearTimeout(n),o="unknown",n=0})),t.add(s.subscribe(c=>{n&&(D({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(o),u.maxTransitionInterval),D({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as nb,Subscription as ob,combine as ub,filter as Cl,once as Bl}from"@vkontakte/videoplayer-shared/evergreen";function Dl(){return new(window.AudioContext||window.webkitAudioContext)}var Ri=class u{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new ob;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Cl(s=>!!s.type),Bl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){A.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ub({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Cl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Bl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Dl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:u.errorId,category:nb.VIDEO_PIPELINE,message:e?.message??`${u.errorId} exception`,thrown:e})}};var fb={chunkDuration:5e3,maxParallelRequests:5},os=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 Nl;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=on([...Tc(this.params.tuning),...yc(this.params.tuning)]).filter(c=>Ol(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",Mo(s)),this.screenFormatsIterator=new Li(s);let a=[...zn(!0),...zn(!1)];this.chromecastFormatsIterator=new Li(a.filter(c=>Ol(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&n!==1&&Ri.isSupported()&&(this.volumeMultiplierManager=new Ri(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}init(){D.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 Li(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(cb(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Ua.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 ns(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);ut(o);let{useDashProviderVirtual:d,useDashProviderVirtualMobile:l}=this.params.tuning,{isMobile:p}=A.device;return!p&&d||p&&l?new _r({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new es({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ut(o),this.params.tuning.useDashProviderVirtual&&!A.device.isMobile?new wi({...n,source:o}):this.params.tuning.useDashProviderVirtualMobile&&A.device.isMobile?new wi({...n,source:o}):new ts({...n,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ut(o),new rs({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ut(o),new is({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ut(o),new ss({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ut(o),new ec({...n,source:o,config:{...fb,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ut(o),new as({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ns(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 Je){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return ut(c),new Fi({...n,chromecastConnector:c})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ut(o),new ji({...n,connection:o})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ns(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ns(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 ns(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 Nl,t=!1,i=0;e.add(db(this.providerOutput.error$.pipe(Vl(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Rl({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(lb(s=>({id:`ProviderHangup:${s}`,category:Ua.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(Vl(({to:a})=>a==="playing"),pb()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=D.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&mb().console.log(`===== DASH_LIVE DEBUG START ====
|
|
180
180
|
`,s.map(({time:o,data:c,stack:d})=>`${o}: ${JSON.stringify(c)}${d?`
|
|
181
181
|
`+d:""}`).join(`
|
|
182
182
|
`),`
|
|
183
|
-
===== DASH_LIVE DEBUG END ====`),n){let o=s.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},"");pb.push("core",{key:"vp_dash_live_debug",strings:[o]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(D({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{D({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let a=this.current$.getValue().destination,n={error:s,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=s.category===Ua.NETWORK,c=s.category===Ua.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&&(o&&t||!l);n={...n,isNetworkError:o,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(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",Mo(n)):this.tracer.error("providerError",Mo(n))})),e}};import{fromEvent as Ha,once as fb,combine as bb,Subscription as Nl,ValueSubject as $o,map as Fl,filter as gb,isNonNullable as ja,now as $e,safeStorage as Ao,getWindow as Sb}from"@vkontakte/videoplayer-shared/evergreen";var vb=5e3,_l="one_video_throughput",Ul="one_video_rtt",Ro=()=>{let{navigator:u}=Sb();if(u)return u.connection},Hl=()=>{let u=Ro()?.downlink;if(ja(u)&&u!==10)return u*1e3},jl=()=>{let u=Ro()?.rtt;if(ja(u)&&u!==3e3)return u},Ql=(u,e,t)=>{let i=t*8,r=i/u;return i/(r+e)},Lo=class u{constructor(e){this.subscription=new Nl;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=u.load(_l)||(e.useBrowserEstimation?Hl():void 0)||vb,i=u.load(Ul)??(e.useBrowserEstimation?jl():void 0)??0;if(this.throughput$=new $o(t),this.rtt$=new $o(i),this.rttAdjustedThroughput$=new $o(Ql(t,i,e.rttPenaltyRequestSize)),this.throughput=st.getSmoothedValue(t,-1,e),this.rtt=st.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=Hl();n&&this.throughput.next(n);let o=jl();ja(o)&&this.rtt.next(o)},s=Ro();s&&"onchange"in s&&this.subscription.add(Ha(s,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Ao.set(_l,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Ao.set(Ul,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Fl(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(bb({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Fl(({throughput:r,rtt:s})=>Ql(r,s,e.rttPenaltyRequestSize)),gb(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=$e(),r=new Nl;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ha(e,"progress").pipe(fb()).subscribe(s=>{t=s.loaded,i=$e()}));break;case 1:case 0:r.add(Ha(e,"loadstart").subscribe(()=>{t=0,i=$e()}));break}r.add(Ha(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=$e(),o=a-t,c=n-i;this.addRawSpeed(o,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=$e(),a=0,n=$e(),o=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()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=$e();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=l.byteLength,s=$e()}else a+=l.byteLength;n=$e()}else r+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&$e()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,$e()-n,this.concurrentDownloads.size),a=0,n=$e());await i?.read().then(c,o)}};this.concurrentDownloads.add(e),i?.read().then(c,o)}addRawSpeed(e,t,i=1,r=!1){if(u.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Ao.get(e);if(ja(t))return parseInt(t,10)??void 0}},zl=Lo;import{fillWithDefault as yb,VideoQuality as Qa}from"@vkontakte/videoplayer-shared/evergreen";var Tb={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:Qa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qa.Q_720P,trafficSavingLimit:Qa.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:Qa.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,tickMaintainInterval:1e3,minSafeBufferToPlay:1e4,useBufferHoldingOnlyOnStall:!0,useNewStallExitPolicy:!1,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},ql=u=>yb(u,Tb);import{assertNonNullable as Bo,combine as ct,ErrorCategory as za,filter as se,filterChanged as Q,fromEvent as Vo,isNonNullable as Xl,isNullable as Rb,Logger as Db,map as z,mapTo as Jl,merge as At,now as qa,once as ce,Subject as H,Subscription as Zl,tap as Oo,ValueSubject as P,isHigher as Cb,isInvariantQuality as ed,flattenObject as Lt,throttle as No,getTraceSubscriptionMethod as td,TracerFactory as Bb,InternalsExposure as Vb,getPlayerId as Ob,devNull as Wa}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Ib,map as Eb,filter as Wl,isNonNullable as wb}from"@vkontakte/videoplayer-shared/evergreen";var Do=({seekState:u,position$:e})=>Ib(u.stateChangeEnded$.pipe(Eb(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Wl(wb)),e.pipe(Wl(()=>u.getState().state==="none")));import{assertNonNullable as xb}from"@vkontakte/videoplayer-shared/evergreen";var Gl=u=>{let e=typeof u.container=="string"?document.getElementById(u.container):u.container;return xb(e,`Wrong container or containerId {${u.container}}`),e};import{filter as kb,once as Pb}from"@vkontakte/videoplayer-shared/evergreen";var Yl=(u,e,t,i)=>{u!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(kb(r=>r.length>0),Pb()).subscribe(r=>{r.find(i)&&e.startTransitionTo(u)}):(u===void 0||t?.getValue().find(i))&&e.startTransitionTo(u)};import{devNull as Mb,getWindow as Co}from"@vkontakte/videoplayer-shared/evergreen";var Kl=()=>{let u="mediaCapabilities"in Co().navigator?$b:Ab,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Lb).map(async([r,s])=>({codec:r,supported:await u(s)}))),i=[A.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Mb.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},$b=async u=>{if(!u)return Promise.resolve({supported:!1});let e={["channels"in u?"audio":"video"]:u};return await Co().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Ab=u=>{if(!u)return Promise.resolve({supported:!1});let e=Co().document,t="channels"in u?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(u?.contentType??"")==="probably"})},Lb={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 Ga=class{constructor(e={},t=Bb.createRootTracer(!1),i){this.subscription=new Zl;this.logger=new Db;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:$u,getCurrentTime$:new P(null)};this.initLogs(),this.tuning=ql(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(s=>s.setSuppressErrors(!0)),Object.values(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Je(r):new Ss(r),this.throughputEstimator=new zl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Vb("core",Ob(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Wa.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let o=Reflect.get(s,a,n);return typeof o!="function"?o:(...c)=>{try{return o.apply(s,c)}catch(d){let l=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),p=`Player.${String(a)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:za.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:s,...a}=e;this.tracer.log("initVideo",Lt(a)),this.domContainer=Gl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new os({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?(Wa.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Kl())):Wa.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?A.isInited$.pipe(se(s=>!!s),ce()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Vo(document,"visibilitychange").pipe(ce()).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(),Wa.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(se(t=>!!t),ce()).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 Je)?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 Je)?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(()=>{Bo(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(se(i=>i.length>0),ce()).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",Lt(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",Lt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Yl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Rb(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Lu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e==="stopped"),ce()).subscribe(()=>{this.initedAt=qa(),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",Lt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:za.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ce()).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",Lt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(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(z(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(o=>n?n.id===o.streamId:!0).map(({quality:o})=>o).sort((o,c)=>ed(o)?1:ed(c)?-1:Cb(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let o of a)o.fps&&(n[o.quality]=o.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(se(a=>Xl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Q((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Q((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.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(z(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(z(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(Oo(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$.pipe(Q()).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(z(a=>a.to),Q(),z(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:Do({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:a,position:n,isLowLatency:o})=>{let c=this.getActiveLiveDelay(o);return a&&Math.abs(n)<c/1e3}),Q(),Oo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({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(z(({isLive:a,position:n,duration:o})=>a&&(Math.abs(o)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),Q(),Oo(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(a=>a.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(a=>a.volume),Q()).subscribe(this.info.volume$)).add(Do({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(Jl(!0)),e.providerOutput.seekedEvent$.pipe(Jl(!1))).pipe(Q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(z(a=>({id:a?`No${a}`:"NoProviders",category:za.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(ce()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ce()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ce()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ce()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ce()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ce(),z(a=>a??qa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ce(),z(()=>qa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ce(),z(()=>qa()-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(se(({to:a})=>a==="playing"),ce()).subscribe(()=>i.next(!1)));let r=0,s=At(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{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(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let 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(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":o?c?a?l="pip":n?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(z(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zl;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),ce()).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=Ge(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(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(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;Bo(this.providerContainer),Bo(e),Mu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Pu(t)),this.providerContainer.current$.subscribe(({type:t})=>Wi("provider",t)),e.duration$.subscribe(t=>Wi("duration",t)),e.availableVideoTracks$.pipe(se(t=>!!t.length),ce()).subscribe(t=>Wi("tracks",t)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(z(t=>t?.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(t=>this.subscription.add(t)),Wi("codecs",A.video.supportedCodecs)}initTracerSubscription(){let e=td(this.tracer.log.bind(this.tracer)),t=td(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(se(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(se(i=>i>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(se(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(se(i=>i.end>0),Q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Q())}).pipe(No(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(se(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),No(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),se(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),se(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(),se(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(se(({throughputEstimation:i,rtt:r})=>!!i&&!!r),No(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),se(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:za.DOM,message:String(r)})})};this.subscription.add(At(Vo(document,"visibilitychange"),Vo(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",Lt({quality:t,availableTracks:Lt(e),track:Lt(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&&!er()}};import{Subscription as VV,Observable as OV,Subject as NV,ValueSubject as FV,VideoQuality as _V}from"@vkontakte/videoplayer-shared/evergreen";var UV=`@vkontakte/videoplayer-core@${_o}`;export{Oi as ChromecastState,Ja as HttpConnectionType,OV as Observable,be as PlaybackState,Ga as Player,bs as PredefinedQualityLimits,UV as SDK_VERSION,NV as Subject,VV as Subscription,Za as Surface,_o as VERSION,FV as ValueSubject,Xa as VideoCodec,Xe as VideoFormat,_V as VideoQuality,la as WebmCodecStrategy,Ad as areValidLiveRecordSources,A as clientChecker,Vt as isMobile};
|
|
183
|
+
===== DASH_LIVE DEBUG END ====`),n){let o=s.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},"");hb.push("core",{key:"vp_dash_live_debug",strings:[o]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(D({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{D({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let a=this.current$.getValue().destination,n={error:s,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=s.category===Ua.NETWORK,c=s.category===Ua.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&&(o&&t||!l);n={...n,isNetworkError:o,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(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",Mo(n)):this.tracer.error("providerError",Mo(n))})),e}};import{fromEvent as Ha,once as bb,combine as gb,Subscription as Fl,ValueSubject as $o,map as _l,filter as Sb,isNonNullable as ja,now as $e,safeStorage as Ao,getWindow as vb}from"@vkontakte/videoplayer-shared/evergreen";var yb=5e3,Ul="one_video_throughput",Hl="one_video_rtt",Ro=()=>{let{navigator:u}=vb();if(u)return u.connection},jl=()=>{let u=Ro()?.downlink;if(ja(u)&&u!==10)return u*1e3},Ql=()=>{let u=Ro()?.rtt;if(ja(u)&&u!==3e3)return u},zl=(u,e,t)=>{let i=t*8,r=i/u;return i/(r+e)},Lo=class u{constructor(e){this.subscription=new Fl;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=u.load(Ul)||(e.useBrowserEstimation?jl():void 0)||yb,i=u.load(Hl)??(e.useBrowserEstimation?Ql():void 0)??0;if(this.throughput$=new $o(t),this.rtt$=new $o(i),this.rttAdjustedThroughput$=new $o(zl(t,i,e.rttPenaltyRequestSize)),this.throughput=st.getSmoothedValue(t,-1,e),this.rtt=st.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=jl();n&&this.throughput.next(n);let o=Ql();ja(o)&&this.rtt.next(o)},s=Ro();s&&"onchange"in s&&this.subscription.add(Ha(s,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Ao.set(Ul,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Ao.set(Hl,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(_l(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(gb({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_l(({throughput:r,rtt:s})=>zl(r,s,e.rttPenaltyRequestSize)),Sb(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=$e(),r=new Fl;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ha(e,"progress").pipe(bb()).subscribe(s=>{t=s.loaded,i=$e()}));break;case 1:case 0:r.add(Ha(e,"loadstart").subscribe(()=>{t=0,i=$e()}));break}r.add(Ha(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=$e(),o=a-t,c=n-i;this.addRawSpeed(o,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=$e(),a=0,n=$e(),o=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()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=$e();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=l.byteLength,s=$e()}else a+=l.byteLength;n=$e()}else r+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&$e()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,$e()-n,this.concurrentDownloads.size),a=0,n=$e());await i?.read().then(c,o)}};this.concurrentDownloads.add(e),i?.read().then(c,o)}addRawSpeed(e,t,i=1,r=!1){if(u.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Ao.get(e);if(ja(t))return parseInt(t,10)??void 0}},ql=Lo;import{fillWithDefault as Tb,VideoQuality as Qa}from"@vkontakte/videoplayer-shared/evergreen";var Ib={keepVideoElement:!1,clearVideoElementInnerHTML:!1,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:Qa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qa.Q_720P,trafficSavingLimit:Qa.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:Qa.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,tickMaintainInterval:1e3,minSafeBufferToPlay:1e4,useBufferHoldingOnlyOnStall:!0,useNewStallExitPolicy:!1,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},Wl=u=>Tb(u,Ib);import{assertNonNullable as Bo,combine as ct,ErrorCategory as za,filter as se,filterChanged as Q,fromEvent as Vo,isNonNullable as Jl,isNullable as Db,Logger as Cb,map as z,mapTo as Zl,merge as At,now as qa,once as ce,Subject as H,Subscription as ed,tap as Oo,ValueSubject as P,isHigher as Bb,isInvariantQuality as td,flattenObject as Lt,throttle as No,getTraceSubscriptionMethod as id,TracerFactory as Vb,InternalsExposure as Ob,getPlayerId as Nb,devNull as Wa}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Eb,map as wb,filter as Gl,isNonNullable as kb}from"@vkontakte/videoplayer-shared/evergreen";var Do=({seekState:u,position$:e})=>Eb(u.stateChangeEnded$.pipe(wb(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Gl(kb)),e.pipe(Gl(()=>u.getState().state==="none")));import{assertNonNullable as xb}from"@vkontakte/videoplayer-shared/evergreen";var Yl=u=>{let e=typeof u.container=="string"?document.getElementById(u.container):u.container;return xb(e,`Wrong container or containerId {${u.container}}`),e};import{filter as Pb,once as Mb}from"@vkontakte/videoplayer-shared/evergreen";var Kl=(u,e,t,i)=>{u!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Pb(r=>r.length>0),Mb()).subscribe(r=>{r.find(i)&&e.startTransitionTo(u)}):(u===void 0||t?.getValue().find(i))&&e.startTransitionTo(u)};import{devNull as $b,getWindow as Co}from"@vkontakte/videoplayer-shared/evergreen";var Xl=()=>{let u="mediaCapabilities"in Co().navigator?Ab:Lb,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Rb).map(async([r,s])=>({codec:r,supported:await u(s)}))),i=[A.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return $b.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},Ab=async u=>{if(!u)return Promise.resolve({supported:!1});let e={["channels"in u?"audio":"video"]:u};return await Co().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Lb=u=>{if(!u)return Promise.resolve({supported:!1});let e=Co().document,t="channels"in u?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(u?.contentType??"")==="probably"})},Rb={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 Ga=class{constructor(e={},t=Vb.createRootTracer(!1),i){this.subscription=new ed;this.logger=new Cb;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),availableVideoTracks$:new P([]),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:$u,getCurrentTime$:new P(null)};this.initLogs(),this.tuning=Wl(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 Je(r):new Ss(r),this.throughputEstimator=new ql(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Ob("core",Nb(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Wa.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let o=Reflect.get(s,a,n);return typeof o!="function"?o:(...c)=>{try{return o.apply(s,c)}catch(d){let l=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),p=`Player.${String(a)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:za.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:s,...a}=e;this.tracer.log("initVideo",Lt(a)),this.domContainer=Yl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new os({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?(Wa.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Xl())):Wa.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?A.isInited$.pipe(se(s=>!!s),ce()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Vo(document,"visibilitychange").pipe(ce()).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(),Wa.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(se(t=>!!t),ce()).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 Je)?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 Je)?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(()=>{Bo(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(se(i=>i.length>0),ce()).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",Lt(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",Lt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Kl(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(Db(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Jl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Lu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e==="stopped"),ce()).subscribe(()=>{this.initedAt=qa(),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",Lt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:za.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ce()).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",Lt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(a=>a.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.subscribe(this.info.availableVideoTracks$)).add(ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(o=>n?n.id===o.streamId:!0).map(({quality:o})=>o).sort((o,c)=>td(o)?1:td(c)?-1:Bb(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let o of a)o.fps&&(n[o.quality]=o.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(se(a=>Jl(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(z(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(z(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(Oo(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$.pipe(Q()).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(z(a=>a.to),Q(),z(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:Do({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:a,position:n,isLowLatency:o})=>{let c=this.getActiveLiveDelay(o);return a&&Math.abs(n)<c/1e3}),Q(),Oo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({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(z(({isLive:a,position:n,duration:o})=>a&&(Math.abs(o)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),Q(),Oo(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(a=>a.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(a=>a.volume),Q()).subscribe(this.info.volume$)).add(Do({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(At(e.providerOutput.endedEvent$.pipe(Zl(!0)),e.providerOutput.seekedEvent$.pipe(Zl(!1))).pipe(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(z(a=>({id:a?`No${a}`:"NoProviders",category:za.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(ce()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ce()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ce()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ce()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ce()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ce(),z(a=>a??qa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ce(),z(()=>qa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ce(),z(()=>qa()-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(se(({to:a})=>a==="playing"),ce()).subscribe(()=>i.next(!1)));let r=0,s=At(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{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(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let 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(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":o?c?a?l="pip":n?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(z(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new ed;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),ce()).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=Ge(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(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(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;Bo(this.providerContainer),Bo(e),Mu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Pu(t)),this.providerContainer.current$.subscribe(({type:t})=>Wi("provider",t)),e.duration$.subscribe(t=>Wi("duration",t)),e.availableVideoTracks$.pipe(se(t=>!!t.length),ce()).subscribe(t=>Wi("tracks",t)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(z(t=>t?.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(t=>this.subscription.add(t)),Wi("codecs",A.video.supportedCodecs)}initTracerSubscription(){let e=id(this.tracer.log.bind(this.tracer)),t=id(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(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(se(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(se(i=>i>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(se(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(se(i=>i.end>0),Q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Q())}).pipe(No(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(se(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),No(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),se(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),se(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(),se(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(se(({throughputEstimation:i,rtt:r})=>!!i&&!!r),No(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),se(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:za.DOM,message:String(r)})})};this.subscription.add(At(Vo(document,"visibilitychange"),Vo(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",Lt({quality:t,availableTracks:Lt(e),track:Lt(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&&!er()}};import{Subscription as OV,Observable as NV,Subject as FV,ValueSubject as _V,VideoQuality as UV}from"@vkontakte/videoplayer-shared/evergreen";var HV=`@vkontakte/videoplayer-core@${_o}`;export{Oi as ChromecastState,Ja as HttpConnectionType,NV as Observable,be as PlaybackState,Ga as Player,bs as PredefinedQualityLimits,HV as SDK_VERSION,FV as Subject,OV as Subscription,Za as Surface,_o as VERSION,_V as ValueSubject,Xa as VideoCodec,Xe as VideoFormat,UV as VideoQuality,la as WebmCodecStrategy,Ld as areValidLiveRecordSources,A as clientChecker,Vt as isMobile};
|