@vkontakte/videoplayer-core 2.0.149-dev.a444d83a.0 → 2.0.149
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +29 -29
- package/es2015.esm.js +22 -22
- package/es2018.cjs.js +27 -27
- package/es2018.esm.js +22 -22
- package/es2024.cjs.js +4 -4
- package/es2024.esm.js +6 -6
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +14 -14
- package/package.json +2 -2
- package/types/providers/DashProviderVirtual/lib/buffer/nativeBufferManager.d.ts +1 -1
- package/types/providers/DashProviderVirtual/lib/buffer/sourceBufferTaskQueue.d.ts +2 -1
- package/types/utils/ClientChecker/services/DeviceChecker.d.ts +4 -2
package/evergreen.esm.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.149
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.149
|
|
3
|
+
* Tue, 16 Dec 2025 09:23:45 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-149/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Eu="2.0.149-dev.a444d83a.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),dt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(dt||{});var pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(pr||{}),An=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(An||{});var $n=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))($n||{}),ta=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ta||{});import{assertNever as $u,assertNonNullable as Jl,isNonNullable as ia,ValueSubject as Mn,Subject as Zl,Subscription as eh,merge as th,observableFrom as ih,fromEvent as ku,map as xu,tap as Pu,filterChanged as rh,isNullable as Rn,ErrorCategory as Au}from"@vkontakte/videoplayer-shared/evergreen";var wu=u=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",u),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ra=class{constructor(e){this.connection$=new Mn(void 0);this.castState$=new Mn("NOT_AVAILABLE");this.errorEvent$=new Zl;this.realCastState$=new Mn("NOT_AVAILABLE");this.subscription=new eh;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=ia(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||wu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Au.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Rn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Rn(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(ku(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 $u(r.sessionState)}})).add(th(ku(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Pu(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),xu(r=>r.castState)),ih([i.getCastState()])).pipe(rh(),xu(sh),Pu(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=ia(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();Jl(n);let o=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(Rn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?ia(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Au.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},sh=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 $u(u)}};import{assertNonNullable as Bn,combine as Cn,debounce as Vn,ErrorCategory as Sh,filter as Ei,filterChanged as Fu,isNonNullable as On,isNullable as _u,map as vh,Subscription as yh,ValueSubject as Nn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as ah,assertNonNullable as Xt,ErrorCategory as nh,getHighestQuality as oh,isNonNullable as Ru}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Mu}from"@vkontakte/videoplayer-shared/evergreen";var te=(u,e=0,t=0)=>{switch(t){case 0:return u.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return u;let i=new URL(u);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(u);return!i.searchParams.get("offset_p")&&e===0?u:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Mu(t)}return u},$t=(u,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(u);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(u);return Number(t.searchParams.get("offset_p")??0)}default:Mu(e)}};var aa=u=>{let{source:e,format:t,meta:i,output:r}=u,s,a,n;switch(t){case"MPEG":{let d=e[t];Xt(d);let l=oh(Object.keys(d));Xt(l);let p=d[l];Xt(p),s=p,a="video/mp4",n=sa();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=e[t];Xt(d),s=d.url,a="application/x-mpegurl",n=sa();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=sa();break}case"DASH_LIVE_CMAF":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=Lu();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=e[t];Xt(d),s=te(d.url),a="application/x-mpegurl",n=Lu();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:nh.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return ah(t)}let o=uh(i.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=ch();let{title:c,subtitle:h}=i;return Ru(c)&&(o.metadata.title=c),Ru(h)&&(o.metadata.subtitle=h),o};function sa(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Lu(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function uh(u,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(u,e):{contentId:u,contentType:e,metadata:{title:"",subtitle:""},streamType:sa()}}function ch(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var x=(u,e,t=!1)=>{let i=u.getTransition();(t||!i||i.to===e)&&u.setState(e)};var na=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Nu}from"@vkontakte/videoplayer-shared/evergreen";var oa=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,n=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||c||r||s||n||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Jt=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var ua=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Jt()}catch(t){console.error(t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.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(t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]*( se)?)/i,["Windows Mobile",2]],[/(windows)[/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i,[1,2]],[/windows nt ?([\d.)]*)(?!.+xbox)/i,[2]],[/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d.;]*)/i,[1]],[/(mac os x) ?([\w. ]*)/i,["macOS",2]],[/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i,["macOS"]],[/(?:ios;fbsv|ios(?=.+ip(?:ad|hone))|ip(?:ad|hone)(?: |.+i(?:pad)?)os)[/ ]([\w.]+)/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(android|harmonyos)[/ ]?([\d.]*)/i,[1,2]],[/(linux|ubuntu|debian|fedora|red hat|centos)[-/ ]?([\w.]*)/i,[1,2]],[/(cros) \w+(?:\)| ([\w.]+)\b)/i,["Chrome OS",2]]];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]:a,c=typeof n=="number"?s[n]:n;o.toLowerCase().includes("mac")?o="macOS":o.toLowerCase().includes("windows")?o="Windows":o.toLowerCase().includes("android")?o="Android":(o.toLowerCase().includes("ios")||o.toLowerCase().includes("iphone")||o.toLowerCase().includes("ipad"))&&(o="iOS"),c&&(c=c.replace(/_/g,".")),this._os={name:o,version:c||"Unknown",full:c?`${o} ${c}`:o};break}}this._os.name==="Unknown"&&(e.includes("Mac")?this._os={name:"macOS",version:"Unknown",full:"macOS"}:e.includes("Win")?this._os={name:"Windows",version:"Unknown",full:"Windows"}:e.includes("Linux")&&(this._os={name:"Linux",version:"Unknown",full:"Linux"}))}catch(t){console.error("OS detection error:",t)}}detectDeviceDetails(e){try{let t=[[/(ip(hone|od|ad))/i,["Apple",1]],[/(macintosh)/i,["Apple","Macintosh"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\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]],[/(?:huawei) ?([-\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]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note|max|cc)?[_ ]?(?:\d{0,2}\w?)[_ ]?(?:plus|se|lite|pro)?( 5g|lte)?)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,["Xiaomi",1]],[/\b(?:xiao)?((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i,["Xiaomi",1]],[/(?:one)?(?:plus)? (a\d0\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]],[/; (\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]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/\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",1]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",1]],[/\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",1]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/(sonyericsson)[-_ ]?([-\w]*)/i,["Sony Ericsson",2]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",1]],[/(pixel (c|tablet))\b/i,["Google",1]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i,["Google",1]],[/(google) (pixelbook( go)?)/i,["Google",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]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i,["ASUS",1]],[/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]],[/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,["Amazon",1]],[/(kf[a-z]+)( bui|\)).+silk\//i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i,["Amazon",1]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(alcatel|geeksphone|nexian|panasonic)[-_ ]?([-\w]*)/i,[1,2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(dell) (streak)/i,["Dell",2]],[/(hp) ([\w ]+\w)/i,["HP",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",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]],[/(spice)[-_ ]?([-\w]*)/i,["Spice",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(shield \w+ tv)/i,["Nvidia",1]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*[)/]((?:dvp-)?[\d.]*)/i,["Roku",1]],[/(apple) ?tv/i,["Apple","TV"]],[/(amazon) ?tv/i,["Amazon","Fire TV"]]];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]:a,c=typeof n=="number"?s[n]:n;this._details.vendor=o,this._details.model=c||"Unknown";break}}}catch(t){console.error("Device details detection error:",t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}normalizeOSName(e){let t=e.toLowerCase();return t.includes("mac")?"macOS":t.includes("win")?"Windows":t.includes("linux")?"Linux":t.includes("android")?"Android":t.includes("ios")||t.includes("iphone")?"iOS":e}normalizeOSVersion(e){return e.replace(/_/g,".")}};var ca=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var xe=()=>window.ManagedMediaSource||window.MediaSource,Mt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Du=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ii=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dh=document.createElement("video"),lh='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hh='video/mp4; codecs="hev1.1.6.L93.B0"',Bu='video/webm; codecs="vp09.00.10.08"',Cu='video/webm; codecs="av01.0.00M.08"',ph='audio/mp4; codecs="mp4a.40.2"',mh='audio/webm; codecs="opus"',Vu,fh=async()=>{if(!window.navigator.mediaCapabilities)return;let u={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...u,video:{...u.video,contentType:Cu}}),window.navigator.mediaCapabilities.decodingInfo({...u,video:{...u.video,contentType:Bu}})]);Vu={DASH_WEBM_AV1:e,DASH_WEBM:t}};fh().catch(u=>{console.log(dh),console.error(u)});var da=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Vu}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Mt(),mse:Du(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!xe()?.isTypeSupported?.(lh),t=!!xe()?.isTypeSupported?.(hh),i=!!xe()?.isTypeSupported?.(ph);this._codecs={h264:e,h265:t,vp9:!!xe()?.isTypeSupported?.(Bu),av1:!!xe()?.isTypeSupported?.(Cu),aac:i,opus:!!xe()?.isTypeSupported?.(mh),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Ou="audio/mpeg",la=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Ou)},this._codecs={mp3:!!xe()?.isTypeSupported?.(Ou)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as bh}from"@vkontakte/videoplayer-shared/evergreen";var Ln=class{constructor(){this.isInited$=new bh(!1);this._displayChecker=new ca,this._deviceChecker=new ua(this._displayChecker),this._browserChecker=new oa,this._videoChecker=new da(this._deviceChecker,this._browserChecker),this._audioChecker=new la,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},$=new Ln;var Dn=u=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return u.filter(n=>{switch(n){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Nu(n)}})},mr=u=>{switch(u){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Nu(u)}},gh=u=>{let t=Object.keys(u).filter(i=>!mr(i));return Dn(t).length>0};var fr=class{constructor(e){this.subscription=new yh;this.sessionId$=new Nn(null);this.mediaSessionId$=new Nn(null);this.contentId$=new Nn(null);this.isMobile=Jt();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(_u(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;On(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(On(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let a=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!a?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new na(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:Sh.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Ei(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Ei(On),Fu(),Vn(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Fu(),vh(Boolean));this.subscription.add(Cn({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Ei(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Cn({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Ei(({mediaLoaded:r})=>r),Vn(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Ei(({mediaLoaded:r,playbackState:{from:s,to:a}})=>!r&&s==="stopped"&&a==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Cn({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Vn(30)),mediaLoaded:t}).pipe(Ei(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:a}=r.to;this.setVolume(a,s)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=aa(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),a=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:a,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Bn(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Bn(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Bn(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":x(this.params.desiredState.playbackState,"paused");break;case"PLAYING":x(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),x(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):x(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(_u(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 Th,ErrorCategory as Fn,filter as Ih,Subject as Eh,Subscription as _n,tap as wh,ValueSubject as wi,fromEvent as br}from"@vkontakte/videoplayer-shared/evergreen";var Uu=u=>({castDevice:{friendlyName:u},remotePlayer:{},remotePlayerController:{},session:{}}),Hu=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var gr=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new wi(null);this.sessionId$=new wi(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new _n;this.subscriptionEvents=new _n;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new wi(!1);this.presentationConnection$=new wi(null);this.message$=new wi(null);this.friendlyName$=new wi(null);this.errorEvent$=new Eh;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(br(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();Th(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:Fn.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(br(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(wh(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Ih(e=>!!e)).subscribe(e=>{let t=br(e,"message").subscribe(s=>{let a=JSON.parse(s.data);a.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(a),this.message$.next(a))}),i=br(e,"connect").subscribe(()=>{this.send("client_connect")}),r=br(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:Fn.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:Fn.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]||Hu()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new _n}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 ju,Subject as kh,map as xh,Subscription as Ph,combine as Ah,filterChanged as Qu,assertNonNullable as $h}from"@vkontakte/videoplayer-shared/evergreen";var lt=class u{constructor(e){this.subscription=new Ph;this.connection$=new ju(void 0);this.castState$=new ju("NOT_AVAILABLE");this.errorEvent$=new kh;let t=u.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new gr({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){$h(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Ah({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Qu())});this.subscription.add(e.pipe(xh(({connection:t,friendlyName:i})=>!!(t&&i)),Qu()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Uu(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 Mh,Subject as ha,merge as zu}from"@vkontakte/videoplayer-shared/evergreen";var V=class{constructor(e){this.transitionStarted$=new ha;this.transitionEnded$=new ha;this.transitionUpdated$=new ha;this.forceChanged$=new ha;this.stateChangeStarted$=zu(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=zu(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||Mh(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as Sr,debounce as qu,ErrorCategory as Rh,fromEvent as Zt,map as Wu,merge as Gu,observableFrom as Lh,Subject as Dh,Subscription as Un,timeout as Bh}from"@vkontakte/videoplayer-shared/evergreen";var Ch=5,Vh=5,Oh=500,Yu=7e3,vr=class{constructor(e){this.subscription=new Un;this.loadMediaTimeoutSubscription=new Un;this.videoState=new V("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}default:Sr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Un;this.subscription.add(e),this.subscription.add(Gu(this.videoState.stateChangeStarted$.pipe(Wu(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Wu(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 Dh;e.add(r.pipe(qu(Oh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let n=a.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-s)>Ch)&&r.next(n),s=n})),e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Vh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Sr(a)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Gu(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Lh(["init"])).pipe(qu(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=aa(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(Bh(Yu).subscribe(()=>s(`timeout(${Yu})`)))});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:Rh.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Xu}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Nh}from"@vkontakte/videoplayer-shared/evergreen";var Ku=u=>{try{u.pause(),u.playbackRate=0,Nh(u),u.remove()}catch(e){console.error(e)}};import{fromEvent as Fh,Subscription as _h}from"@vkontakte/videoplayer-shared/evergreen";var Hn=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)}},jn=window.WeakMap?new WeakMap:new Hn,Qn=window.WeakMap?new WeakMap:new Map,Uh=(u,e=20)=>{let t=0;return Fh(u,"ratechange").subscribe(i=>{t++,t>=e&&(u.currentTime=u.currentTime,t=0)})},ge=(u,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=u.querySelector("video"),r=!!i;i?Xu(i):(i=document.createElement("video"),u.appendChild(i)),jn.set(i,r);let s=new _h;return s.add(Uh(i,e)),Qn.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Se=u=>{Qn.get(u)?.unsubscribe(),Qn.delete(u);let t=jn.get(u);jn.delete(u),t?Xu(u):Ku(u)};import{assertNonNullable as Tr,isNonNullable as st,isNullable as Qh,fromEvent as ki,merge as Ju,observableFrom as Zu,filterChanged as ec,map as Ir,Subject as tc,Subscription as zh,ValueSubject as qh,ErrorCategory as Wh}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as zn,isNullable as Hh,Subscription as jh}from"@vkontakte/videoplayer-shared/evergreen";var pa=(u,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=u.getState(),n=e(),o=Hh(r),c=new jh;return r&&c.add(r.subscribe(h=>{let d=u.getState();i(h,d)&&u.setState(h)},s)),i(n,a)||(t(a),o&&u.setState(a)),c.add(u.stateChangeStarted$.subscribe(h=>{t(h.to),o&&u.setState(h.to)},s)),c},je=(u,e,t)=>pa(e,()=>u.loop,i=>{zn(i)&&(u.loop=i)},{onError:t}),ve=(u,e,t,i)=>pa(e,()=>({muted:u.muted,volume:u.volume}),r=>{zn(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)=>pa(e,()=>u.playbackRate,r=>{zn(r)&&(u.playbackRate=r)},{changed$:t,onError:i}),yr=pa;var Gh=u=>["__",u.language,u.label].join("|"),Yh=(u,e)=>{if(u.id===e)return!0;let[t,i,r]=e.split("|");return u.language===i&&u.label===r},qn=class u{constructor(e){this.available$=new tc;this.current$=new qh(void 0);this.error$=new tc;this.subscription=new zh;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:Wh.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(yr(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(yr(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(yr(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(yr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Tr(this.video);let{textTracks:e}=this.video;this.subscription.add(ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ju(ki(e,"addtrack"),ki(e,"removetrack"),Zu(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ec((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Ju(ki(e,"change"),Zu(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ir(i=>i&&this.htmlTextTrackToITextTrack(i).id),ec()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ki(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ki(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;st(t.align)&&(r.align=t.align),st(t.position)&&(r.position=t.position),st(t.size)&&(r.size=t.size),st(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Tr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(u.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Gh(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Tr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Qh(e)||!Yh(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Tr(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Tr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=qn;var ei=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ic=u=>{let e=u;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Wn=u=>{let e=ic(u);return!!(e&&e.fullscreenElement&&e.fullscreenElement===u)},rc=u=>{let e=ic(u);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===u)};import{fromEvent as Pe,map as at,merge as ma,filterChanged as ac,isNonNullable as nc,Subject as Xh,filter as Gn,mapTo as Yn,combine as Jh,once as Zh,shareReplay as Ae,throttle as ep,ErrorCategory as tp,ValueSubject as oc,Subscription as ip}from"@vkontakte/videoplayer-shared/evergreen";var Kh=3,sc=(u,e,t=Kh)=>{let i=0,r=0;for(let s=0;s<u.length;s++){let a=u.start(s),n=u.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)u.end(o)+t>=i&&(i=u.start(o));for(let o=s+1;o<u.length;o++)u.start(o)-t<=r&&(r=u.end(o))}}return{from:i,to:r}};var ye=u=>{let e=k=>Pe(u,k).pipe(Yn(void 0),Ae(1)),t=new ip,i=()=>t.unsubscribe(),r=ma(Pe(u,"progress"),Pe(u,"timeupdate")).pipe(at(()=>sc(u.buffered,u.currentTime)),Ae(1)),s=$.browser.isSafari?Jh({play:e("play").pipe(Zh()),playing:e("playing")}).pipe(Yn(void 0),Ae(1)):e("playing"),a=Pe(u,"volumechange").pipe(at(()=>({muted:u.muted,volume:u.volume})),Ae(1)),n=Pe(u,"ratechange").pipe(at(()=>u.playbackRate),Ae(1)),o=Pe(u,"error").pipe(Gn(()=>!!(u.error||u.played.length)),at(()=>{let k=u.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:tp.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:u.error??void 0}}),Ae(1)),c=Pe(u,"timeupdate").pipe(at(()=>u.currentTime),Ae(1)),h=["waiting","seeking","seeked","timeupdate"],d=new Xh,l=.3,p;t.add(ma(...h.map(k=>Pe(u,k))).subscribe(k=>{let N=u.currentTime;u.loop&&nc(p)&&nc(N)&&p>=u.duration-l&&N<=l&&d.next(p),p=N}));let m=e("pause").pipe(Gn(()=>!u.error&&p!==u.duration),Ae(1)),f=Pe(u,"enterpictureinpicture").pipe(Ae(1)),b=Pe(u,"leavepictureinpicture").pipe(Ae(1)),g=new oc(rc(u));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new oc(Wn(u)),y=Pe(u,"fullscreenchange").pipe(Ae(1));t.add(y.pipe(at(()=>Wn(u))).subscribe(S));let v=.1,w=1e3,P=Pe(u,"timeupdate").pipe(at(k=>u.duration-u.currentTime<v),ac(),Ae(1)),A=ma(P.pipe(Gn(k=>!u.loop&&k)),Pe(u,"ended")).pipe(ep(w),Yn(void 0),Ae(1)),L=ma(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Pe(u,k)),P.pipe(at(k=>({type:k?"ended":"unknown"})))).pipe(at(k=>$.browser.isFirefox&&k.type==="ended"?u.readyState<2:u.readyState<3),ac(),Ae(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:A,looped$:d,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Pe(u,"durationchange").pipe(at(()=>u.duration),Ae(1)),isBuffering$:L,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Rt}from"@vkontakte/videoplayer-shared/evergreen";var nt=u=>{switch(u){case"mobile":return Rt.Q_144P;case"lowest":return Rt.Q_240P;case"low":return Rt.Q_360P;case"sd":case"medium":return Rt.Q_480P;case"hd":case"high":return Rt.Q_720P;case"fullhd":case"full":return Rt.Q_1080P;case"quadhd":case"quad":return Rt.Q_1440P;case"ultrahd":case"ultra":return Rt.Q_2160P}};import{isNonNullable as W,isNullable as Sa,now as Sc,isHigher as va,isHigherOrEqual as ti,isInvariantQuality as ya,isLowerOrEqual as Pi,videoSizeToQuality as vc,assertNotEmptyArray as Ta,assertNonNullable as yc}from"@vkontakte/videoplayer-shared/evergreen";var Kn=!1,ht={},uc=u=>{Kn=u},cc=()=>{ht={}},dc=u=>{u(ht)},Er=(u,e)=>{Kn&&(ht.meta=ht.meta??{},ht.meta[u]=e)},$e=class{constructor(e){this.name=e}next(e){if(!Kn)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as rp,isHigherOrEqual as jy,isLower as lc,isLowerOrEqual as Qy,isNonNullable as fa,isNullable as sp,videoHeightToQuality as ba}from"@vkontakte/videoplayer-shared/evergreen";function hc(u,e,t){return!u.max&&u.min===e?"high_quality":!u.min&&u.max===t?"traffic_saving":"unknown"}function xi(u,e,t){return sp(u)||fa(u.min)&&fa(u.max)&&lc(u.max,u.min)||fa(u.min)&&e&&rp(u.min,e)||fa(u.max)&&t&&lc(u.max,t)}function pc({limits:u,highestAvailableHeight:e,lowestAvailableHeight:t}){return xi({max:u?.max?ba(u.max):void 0,min:u?.min?ba(u.min):void 0},e?ba(e):void 0,t?ba(t):void 0)}var Tc=new $e("best_bitrate"),Ia=(u,e,t)=>(e-t)*Math.pow(2,-10*u)+t;var Ai=u=>(e,t)=>u*(Number(e.bitrate)-Number(t.bitrate)),Je=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Sc()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ea='Assertion "ABR Tracks is empty array" failed',ga=new WeakMap,mc=new WeakMap,fc=new WeakMap,ii=(u,e,t,i)=>{let r=[...e].sort(Ai(1)),s=[...t].sort(Ai(1)),a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},ri=(u,e,t,i)=>{let r=ga.get(e);r||(r=[...e].sort(Ai(1)),ga.set(e,r));let s=ga.get(t);s||(s=[...t].sort(Ai(1)),ga.set(t,s));let a=fc.get(u);a||(a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),fc.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)},bc=u=>"quality"in u,wa=(u,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?u.trackCooldownIncreaseQuality:u.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Sc()-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=bc(a)?"video":"audio",o=bc(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var wu="2.0.149";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),dt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(dt||{});var pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(pr||{}),An=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(An||{});var $n=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))($n||{}),ta=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ta||{});import{assertNever as $u,assertNonNullable as Jl,isNonNullable as ia,ValueSubject as Mn,Subject as Zl,Subscription as eh,merge as th,observableFrom as ih,fromEvent as ku,map as xu,tap as Pu,filterChanged as rh,isNullable as Rn,ErrorCategory as Au}from"@vkontakte/videoplayer-shared/evergreen";var Eu=u=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",u),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ra=class{constructor(e){this.connection$=new Mn(void 0);this.castState$=new Mn("NOT_AVAILABLE");this.errorEvent$=new Zl;this.realCastState$=new Mn("NOT_AVAILABLE");this.subscription=new eh;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=ia(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Eu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Au.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Rn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Rn(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(ku(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 $u(r.sessionState)}})).add(th(ku(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Pu(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),xu(r=>r.castState)),ih([i.getCastState()])).pipe(rh(),xu(sh),Pu(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=ia(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();Jl(n);let o=n.getCastDevice(),c=n.getMediaSession()?.media?.contentId;(Rn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?ia(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Au.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},sh=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 $u(u)}};import{assertNonNullable as Bn,combine as Cn,debounce as Vn,ErrorCategory as Sh,filter as wi,filterChanged as Fu,isNonNullable as On,isNullable as _u,map as vh,Subscription as yh,ValueSubject as Nn}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as ah,assertNonNullable as Xt,ErrorCategory as nh,getHighestQuality as oh,isNonNullable as Ru}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Mu}from"@vkontakte/videoplayer-shared/evergreen";var te=(u,e=0,t=0)=>{switch(t){case 0:return u.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return u;let i=new URL(u);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(u);return!i.searchParams.get("offset_p")&&e===0?u:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Mu(t)}return u},$t=(u,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(u);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(u);return Number(t.searchParams.get("offset_p")??0)}default:Mu(e)}};var aa=u=>{let{source:e,format:t,meta:i,output:r}=u,s,a,n;switch(t){case"MPEG":{let d=e[t];Xt(d);let l=oh(Object.keys(d));Xt(l);let p=d[l];Xt(p),s=p,a="video/mp4",n=sa();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=e[t];Xt(d),s=d.url,a="application/x-mpegurl",n=sa();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=sa();break}case"DASH_LIVE_CMAF":{let d=e[t];Xt(d),s=d.url,a="application/dash+xml",n=Lu();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=e[t];Xt(d),s=te(d.url),a="application/x-mpegurl",n=Lu();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:nh.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return ah(t)}let o=uh(i.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=ch();let{title:c,subtitle:h}=i;return Ru(c)&&(o.metadata.title=c),Ru(h)&&(o.metadata.subtitle=h),o};function sa(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Lu(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function uh(u,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(u,e):{contentId:u,contentType:e,metadata:{title:"",subtitle:""},streamType:sa()}}function ch(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var x=(u,e,t=!1)=>{let i=u.getTransition();(t||!i||i.to===e)&&u.setState(e)};var na=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Nu}from"@vkontakte/videoplayer-shared/evergreen";var oa=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,n=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||c||r||s||n||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Jt=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var ua=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Jt()}catch(t){console.error("DeviceChecker: calling isMobile error - ",t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||a||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r.length>0,n=r.length>1,o="Unknown",c="Unknown";if(a){let h=r[0];typeof h=="number"?h<s.length&&s[h]!==void 0&&(o=s[h]):o=h}if(n){let h=r[1];typeof h=="number"?h<s.length&&s[h]!==void 0&&(c=s[h]):h!==void 0&&(c=h)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&a&&typeof r[0]=="string"&&(c=s[1]);o=this.normalizeOSName(o),c=this.normalizeOSVersion(c,o),o==="iOS"&&/ipad/i.test(e)?o="iPadOS":o==="iPadOS"&&/ip(hone|od)/i.test(e)&&(o="iOS"),this._os={name:o,version:c||"Unknown",full:c&&c!=="Unknown"?`${o} ${c}`:o};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let a=r[0],n=r[1],o=typeof a=="number"?s[a]!==void 0?this.normalizeVendorName(s[a]):"Unknown":this.normalizeVendorName(a),c="Unknown";typeof n=="number"?c=s[n]!==void 0?s[n]:"Unknown":n!==void 0?c=n:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,o),this.details.vendor=o,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let t=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(t);return}if(this._os.version!=="Unknown"){let t=this._os.version.split("."),i=t.length>=2?`${t[0]}.${t[1]}`:t[0];this._iosVersion=parseFloat(i);return}let e=navigator.userAgent.match(/OS (\d+(_\d+)?)/i);e?.[1]&&(this._iosVersion=parseFloat(e[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var ca=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var xe=()=>window.ManagedMediaSource||window.MediaSource,Mt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Du=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ii=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dh=document.createElement("video"),lh='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hh='video/mp4; codecs="hev1.1.6.L93.B0"',Bu='video/webm; codecs="vp09.00.10.08"',Cu='video/webm; codecs="av01.0.00M.08"',ph='audio/mp4; codecs="mp4a.40.2"',mh='audio/webm; codecs="opus"',Vu,fh=async()=>{if(!window.navigator.mediaCapabilities)return;let u={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...u,video:{...u.video,contentType:Cu}}),window.navigator.mediaCapabilities.decodingInfo({...u,video:{...u.video,contentType:Bu}})]);Vu={DASH_WEBM_AV1:e,DASH_WEBM:t}};fh().catch(u=>{console.log(dh),console.error(u)});var da=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Vu}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Mt(),mse:Du(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!xe()?.isTypeSupported?.(lh),t=!!xe()?.isTypeSupported?.(hh),i=!!xe()?.isTypeSupported?.(ph);this._codecs={h264:e,h265:t,vp9:!!xe()?.isTypeSupported?.(Bu),av1:!!xe()?.isTypeSupported?.(Cu),aac:i,opus:!!xe()?.isTypeSupported?.(mh),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Ou="audio/mpeg",la=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Ou)},this._codecs={mp3:!!xe()?.isTypeSupported?.(Ou)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as bh}from"@vkontakte/videoplayer-shared/evergreen";var Ln=class{constructor(){this.isInited$=new bh(!1);this._displayChecker=new ca,this._deviceChecker=new ua(this._displayChecker),this._browserChecker=new oa,this._videoChecker=new da(this._deviceChecker,this._browserChecker),this._audioChecker=new la,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},$=new Ln;var Dn=u=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return u.filter(n=>{switch(n){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Nu(n)}})},mr=u=>{switch(u){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Nu(u)}},gh=u=>{let t=Object.keys(u).filter(i=>!mr(i));return Dn(t).length>0};var fr=class{constructor(e){this.subscription=new yh;this.sessionId$=new Nn(null);this.mediaSessionId$=new Nn(null);this.contentId$=new Nn(null);this.isMobile=Jt();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(_u(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;On(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(On(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let a=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!a?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new na(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:Sh.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(wi(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(wi(On),Fu(),Vn(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Fu(),vh(Boolean));this.subscription.add(Cn({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(wi(({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(wi(({mediaLoaded:r})=>r),Vn(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(wi(({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(Vn(30)),mediaLoaded:t}).pipe(wi(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:a}=r.to;this.setVolume(a,s)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=aa(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),a=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:a,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Bn(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Bn(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Bn(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":x(this.params.desiredState.playbackState,"paused");break;case"PLAYING":x(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),x(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):x(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(_u(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 Th,ErrorCategory as Fn,filter as Ih,Subject as wh,Subscription as _n,tap as Eh,ValueSubject as Ei,fromEvent as br}from"@vkontakte/videoplayer-shared/evergreen";var Uu=u=>({castDevice:{friendlyName:u},remotePlayer:{},remotePlayerController:{},session:{}}),Hu=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var gr=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new Ei(null);this.sessionId$=new Ei(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new _n;this.subscriptionEvents=new _n;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new Ei(!1);this.presentationConnection$=new Ei(null);this.message$=new Ei(null);this.friendlyName$=new Ei(null);this.errorEvent$=new wh;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(br(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();Th(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:Fn.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(br(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(Eh(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Ih(e=>!!e)).subscribe(e=>{let t=br(e,"message").subscribe(s=>{let a=JSON.parse(s.data);a.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(a),this.message$.next(a))}),i=br(e,"connect").subscribe(()=>{this.send("client_connect")}),r=br(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:Fn.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:Fn.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]||Hu()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new _n}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 ju,Subject as kh,map as xh,Subscription as Ph,combine as Ah,filterChanged as zu,assertNonNullable as $h}from"@vkontakte/videoplayer-shared/evergreen";var lt=class u{constructor(e){this.subscription=new Ph;this.connection$=new ju(void 0);this.castState$=new ju("NOT_AVAILABLE");this.errorEvent$=new kh;let t=u.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new gr({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){$h(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=Ah({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(zu())});this.subscription.add(e.pipe(xh(({connection:t,friendlyName:i})=>!!(t&&i)),zu()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Uu(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 Mh,Subject as ha,merge as Qu}from"@vkontakte/videoplayer-shared/evergreen";var V=class{constructor(e){this.transitionStarted$=new ha;this.transitionEnded$=new ha;this.transitionUpdated$=new ha;this.forceChanged$=new ha;this.stateChangeStarted$=Qu(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qu(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||Mh(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as Sr,debounce as qu,ErrorCategory as Rh,fromEvent as Zt,map as Wu,merge as Gu,observableFrom as Lh,Subject as Dh,Subscription as Un,timeout as Bh}from"@vkontakte/videoplayer-shared/evergreen";var Ch=5,Vh=5,Oh=500,Yu=7e3,vr=class{constructor(e){this.subscription=new Un;this.loadMediaTimeoutSubscription=new Un;this.videoState=new V("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}default:Sr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mr(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Un;this.subscription.add(e),this.subscription.add(Gu(this.videoState.stateChangeStarted$.pipe(Wu(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Wu(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 Dh;e.add(r.pipe(qu(Oh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let n=a.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-s)>Ch)&&r.next(n),s=n})),e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Vh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Sr(a)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Gu(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Lh(["init"])).pipe(qu(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=aa(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(Bh(Yu).subscribe(()=>s(`timeout(${Yu})`)))});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:Rh.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Xu}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Nh}from"@vkontakte/videoplayer-shared/evergreen";var Ku=u=>{try{u.pause(),u.playbackRate=0,Nh(u),u.remove()}catch(e){console.error(e)}};import{fromEvent as Fh,Subscription as _h}from"@vkontakte/videoplayer-shared/evergreen";var Hn=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)}},jn=window.WeakMap?new WeakMap:new Hn,zn=window.WeakMap?new WeakMap:new Map,Uh=(u,e=20)=>{let t=0;return Fh(u,"ratechange").subscribe(i=>{t++,t>=e&&(u.currentTime=u.currentTime,t=0)})},ge=(u,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=u.querySelector("video"),r=!!i;i?Xu(i):(i=document.createElement("video"),u.appendChild(i)),jn.set(i,r);let s=new _h;return s.add(Uh(i,e)),zn.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Se=u=>{zn.get(u)?.unsubscribe(),zn.delete(u);let t=jn.get(u);jn.delete(u),t?Xu(u):Ku(u)};import{assertNonNullable as Tr,isNonNullable as st,isNullable as zh,fromEvent as ki,merge as Ju,observableFrom as Zu,filterChanged as ec,map as Ir,Subject as tc,Subscription as Qh,ValueSubject as qh,ErrorCategory as Wh}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Qn,isNullable as Hh,Subscription as jh}from"@vkontakte/videoplayer-shared/evergreen";var pa=(u,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=u.getState(),n=e(),o=Hh(r),c=new jh;return r&&c.add(r.subscribe(h=>{let d=u.getState();i(h,d)&&u.setState(h)},s)),i(n,a)||(t(a),o&&u.setState(a)),c.add(u.stateChangeStarted$.subscribe(h=>{t(h.to),o&&u.setState(h.to)},s)),c},je=(u,e,t)=>pa(e,()=>u.loop,i=>{Qn(i)&&(u.loop=i)},{onError:t}),ve=(u,e,t,i)=>pa(e,()=>({muted:u.muted,volume:u.volume}),r=>{Qn(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)=>pa(e,()=>u.playbackRate,r=>{Qn(r)&&(u.playbackRate=r)},{changed$:t,onError:i}),yr=pa;var Gh=u=>["__",u.language,u.label].join("|"),Yh=(u,e)=>{if(u.id===e)return!0;let[t,i,r]=e.split("|");return u.language===i&&u.label===r},qn=class u{constructor(e){this.available$=new tc;this.current$=new qh(void 0);this.error$=new tc;this.subscription=new Qh;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:Wh.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(yr(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(yr(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,a)=>st(s)&&st(a)&&s.length===a.length&&s.every(({id:n},o)=>n===a[o].id),changed$:this.available$.pipe(Ir(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(yr(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(yr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Tr(this.video);let{textTracks:e}=this.video;this.subscription.add(ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ju(ki(e,"addtrack"),ki(e,"removetrack"),Zu(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ec((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Ju(ki(e,"change"),Zu(["init"])).pipe(Ir(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ir(i=>i&&this.htmlTextTrackToITextTrack(i).id),ec()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ki(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ki(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;st(t.align)&&(r.align=t.align),st(t.position)&&(r.position=t.position),st(t.size)&&(r.size=t.size),st(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Tr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(u.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Gh(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Tr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zh(e)||!Yh(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Tr(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Tr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=qn;var ei=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ic=u=>{let e=u;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Wn=u=>{let e=ic(u);return!!(e&&e.fullscreenElement&&e.fullscreenElement===u)},rc=u=>{let e=ic(u);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===u)};import{fromEvent as Pe,map as at,merge as ma,filterChanged as ac,isNonNullable as nc,Subject as Xh,filter as Gn,mapTo as Yn,combine as Jh,once as Zh,shareReplay as Ae,throttle as ep,ErrorCategory as tp,ValueSubject as oc,Subscription as ip}from"@vkontakte/videoplayer-shared/evergreen";var Kh=3,sc=(u,e,t=Kh)=>{let i=0,r=0;for(let s=0;s<u.length;s++){let a=u.start(s),n=u.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)u.end(o)+t>=i&&(i=u.start(o));for(let o=s+1;o<u.length;o++)u.start(o)-t<=r&&(r=u.end(o))}}return{from:i,to:r}};var ye=u=>{let e=k=>Pe(u,k).pipe(Yn(void 0),Ae(1)),t=new ip,i=()=>t.unsubscribe(),r=ma(Pe(u,"progress"),Pe(u,"timeupdate")).pipe(at(()=>sc(u.buffered,u.currentTime)),Ae(1)),s=$.browser.isSafari?Jh({play:e("play").pipe(Zh()),playing:e("playing")}).pipe(Yn(void 0),Ae(1)):e("playing"),a=Pe(u,"volumechange").pipe(at(()=>({muted:u.muted,volume:u.volume})),Ae(1)),n=Pe(u,"ratechange").pipe(at(()=>u.playbackRate),Ae(1)),o=Pe(u,"error").pipe(Gn(()=>!!(u.error||u.played.length)),at(()=>{let k=u.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:tp.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:u.error??void 0}}),Ae(1)),c=Pe(u,"timeupdate").pipe(at(()=>u.currentTime),Ae(1)),h=["waiting","seeking","seeked","timeupdate"],d=new Xh,l=.3,p;t.add(ma(...h.map(k=>Pe(u,k))).subscribe(k=>{let N=u.currentTime;u.loop&&nc(p)&&nc(N)&&p>=u.duration-l&&N<=l&&d.next(p),p=N}));let m=e("pause").pipe(Gn(()=>!u.error&&p!==u.duration),Ae(1)),f=Pe(u,"enterpictureinpicture").pipe(Ae(1)),b=Pe(u,"leavepictureinpicture").pipe(Ae(1)),g=new oc(rc(u));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new oc(Wn(u)),y=Pe(u,"fullscreenchange").pipe(Ae(1));t.add(y.pipe(at(()=>Wn(u))).subscribe(S));let v=.1,E=1e3,P=Pe(u,"timeupdate").pipe(at(k=>u.duration-u.currentTime<v),ac(),Ae(1)),A=ma(P.pipe(Gn(k=>!u.loop&&k)),Pe(u,"ended")).pipe(ep(E),Yn(void 0),Ae(1)),L=ma(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Pe(u,k)),P.pipe(at(k=>({type:k?"ended":"unknown"})))).pipe(at(k=>$.browser.isFirefox&&k.type==="ended"?u.readyState<2:u.readyState<3),ac(),Ae(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:A,looped$:d,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Pe(u,"durationchange").pipe(at(()=>u.duration),Ae(1)),isBuffering$:L,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Rt}from"@vkontakte/videoplayer-shared/evergreen";var nt=u=>{switch(u){case"mobile":return Rt.Q_144P;case"lowest":return Rt.Q_240P;case"low":return Rt.Q_360P;case"sd":case"medium":return Rt.Q_480P;case"hd":case"high":return Rt.Q_720P;case"fullhd":case"full":return Rt.Q_1080P;case"quadhd":case"quad":return Rt.Q_1440P;case"ultrahd":case"ultra":return Rt.Q_2160P}};import{isNonNullable as W,isNullable as Sa,now as Sc,isHigher as va,isHigherOrEqual as ti,isInvariantQuality as ya,isLowerOrEqual as Pi,videoSizeToQuality as vc,assertNotEmptyArray as Ta,assertNonNullable as yc}from"@vkontakte/videoplayer-shared/evergreen";var Kn=!1,ht={},uc=u=>{Kn=u},cc=()=>{ht={}},dc=u=>{u(ht)},wr=(u,e)=>{Kn&&(ht.meta=ht.meta??{},ht.meta[u]=e)},$e=class{constructor(e){this.name=e}next(e){if(!Kn)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as rp,isHigherOrEqual as jy,isLower as lc,isLowerOrEqual as zy,isNonNullable as fa,isNullable as sp,videoHeightToQuality as ba}from"@vkontakte/videoplayer-shared/evergreen";function hc(u,e,t){return!u.max&&u.min===e?"high_quality":!u.min&&u.max===t?"traffic_saving":"unknown"}function xi(u,e,t){return sp(u)||fa(u.min)&&fa(u.max)&&lc(u.max,u.min)||fa(u.min)&&e&&rp(u.min,e)||fa(u.max)&&t&&lc(u.max,t)}function pc({limits:u,highestAvailableHeight:e,lowestAvailableHeight:t}){return xi({max:u?.max?ba(u.max):void 0,min:u?.min?ba(u.min):void 0},e?ba(e):void 0,t?ba(t):void 0)}var Tc=new $e("best_bitrate"),Ia=(u,e,t)=>(e-t)*Math.pow(2,-10*u)+t;var Ai=u=>(e,t)=>u*(Number(e.bitrate)-Number(t.bitrate)),Je=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Sc()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wa='Assertion "ABR Tracks is empty array" failed',ga=new WeakMap,mc=new WeakMap,fc=new WeakMap,ii=(u,e,t,i)=>{let r=[...e].sort(Ai(1)),s=[...t].sort(Ai(1)),a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(u)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},ri=(u,e,t,i)=>{let r=ga.get(e);r||(r=[...e].sort(Ai(1)),ga.set(e,r));let s=ga.get(t);s||(s=[...t].sort(Ai(1)),ga.set(t,s));let a=fc.get(u);a||(a=s.filter(o=>W(o.bitrate)&&W(u.bitrate)?u.bitrate/o.bitrate>i:!0),fc.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)},bc=u=>"quality"in u,Ea=(u,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?u.trackCooldownIncreaseQuality:u.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Sc()-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=bc(a)?"video":"audio",o=bc(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),a}return i?.recordSwitch(t),t},ap=(u,e)=>Math.log(e)/Math.log(u),Ic=({tuning:u,container:e,limits:t,panelSize:i})=>{let r=u.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(u.usePixelRatio&&$.display.pixelRatio){let s=$.display.pixelRatio;if(u.pixelRatioMultiplier)r*=u.pixelRatioMultiplier*(s-1)+1;else{let a=u.pixelRatioLogBase,[n=0,o=0,c=0]=u.pixelRatioLogCoefficients,h=ap(a,n*s+o)+c;Number.isFinite(h)&&(r*=h)}}return W(t?.min)&&ti(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}},gc=new WeakMap,
|
|
8
|
+
`}),a}return i?.recordSwitch(t),t},ap=(u,e)=>Math.log(e)/Math.log(u),Ic=({tuning:u,container:e,limits:t,panelSize:i})=>{let r=u.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(u.usePixelRatio&&$.display.pixelRatio){let s=$.display.pixelRatio;if(u.pixelRatioMultiplier)r*=u.pixelRatioMultiplier*(s-1)+1;else{let a=u.pixelRatioLogBase,[n=0,o=0,c=0]=u.pixelRatioLogCoefficients,h=ap(a,n*s+o)+c;Number.isFinite(h)&&(r*=h)}}return W(t?.min)&&ti(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}},gc=new WeakMap,ze=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:l,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{Ta(u,wa);let{containerSizeFactor:b,containerSizeLimit:g}=Ic({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&W(n)?n:1,y=gc.get(u);y||(y=u.filter(I=>!ya(I.quality)).sort((I,T)=>va(I.quality,T.quality)?-1:1),gc.set(u,y));let v=y.at(-1)?.quality,E=y.at(0)?.quality,P=xi(r,E,v),A=S*Ia(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},L=null;for(let I of y){let T=!0;if(g)if(I.size)T=I.size.width<=g.width&&I.size.height<=g.height;else{let H=g&&vc(g);T=H?Pi(I.quality,H):!0}if(!T){w[I.quality]="FitsContainer";continue}let O=p||t,R=W(O)&&isFinite(O)&&W(I.bitrate)?O-s>=I.bitrate*A:!0,U=r?.min===I.quality;if(!R&&!U){w[I.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&W(i.minBufferToSwitchUp)&&o&&!ya(o.quality)&&(a??0)<i.minBufferToSwitchUp&&va(I.quality,o.quality)){w[I.quality]="Buffer";continue}if(!!d&&ti(I.quality,d)&&!U){w[I.quality]="DroppedFramesLimit";continue}if(!!l&&ti(I.quality,l)&&!U){w[I.quality]="StallsLimit";continue}let pe=P||(Sa(r?.max)||Pi(I.quality,r.max))&&(Sa(r?.min)||ti(I.quality,r.min)),me=W(h)&&!h?Pi(I.quality,i.backgroundVideoQualityLimit):!0;if(!pe||!me){w[I.quality]="FitsQualityLimits";continue}L||(L=I)}L&&L.bitrate&&Tc.next(L.bitrate);let k=L??y.at(-1)??u[0],N=c?.last,D=Ea(i,m,k,c);return W(c)&&D.quality!==N?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${u.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${I.size?.width}:${I.size?.height} }`).join(`
|
|
@@ -33,12 +33,12 @@ var Eu="2.0.149-dev.a444d83a.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(w).map(([I,T])=>`${I}: ${T}`).join(`
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
39
|
[best video track] ${L?.quality}
|
|
40
40
|
[selected video track] ${D?.quality}
|
|
41
|
-
`}),D},$i=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:l,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{Ta(u,
|
|
41
|
+
`}),D},$i=(u,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:o,history:c,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:l,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{Ta(u,wa);let{containerSizeFactor:b,containerSizeLimit:g}=Ic({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&W(n)?n:1,y=u.filter(T=>!ya(T.quality)).sort((T,O)=>va(T.quality,O.quality)?-1:1),v=y.at(-1)?.quality,E=y.at(0)?.quality,P=xi(r,E,v),A=S*Ia(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},k=y.filter(T=>{let O=!0;if(g)if(T.size)O=T.size.width<=g.width&&T.size.height<=g.height;else{let _=g&&vc(g);O=_?Pi(T.quality,_):!0}if(!O)return w[T.quality]="FitsContainer",!1;let R=p||t,U=W(R)&&isFinite(R)&&W(T.bitrate)?R-s>=T.bitrate*A:!0,G=r?.min===T.quality;if(!U&&!G)return w[T.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&W(i.minBufferToSwitchUp)&&o&&!ya(o.quality)&&(a??0)<i.minBufferToSwitchUp&&va(T.quality,o.quality))return w[T.quality]="Buffer",!1;if(!!d&&ti(T.quality,d)&&!G)return w[T.quality]="DroppedFramesLimit",!1;if(!!l&&ti(T.quality,l)&&!G)return w[T.quality]="StallsLimit",!1;let me=P||(Sa(r?.max)||Pi(T.quality,r.max))&&(Sa(r?.min)||ti(T.quality,r.min)),H=W(h)&&!h?Pi(T.quality,i.backgroundVideoQualityLimit):!0;return!me||!H?(w[T.quality]="FitsQualityLimits",!1):!0})[0];k&&k.bitrate&&Tc.next(k.bitrate);let N=k??y.at(-1)??u[0],D=c?.last,I=Ea(i,m,N,c);return W(c)&&I.quality!==D?.quality&&m({message:`
|
|
42
42
|
[VIDEO TRACKS ABR]
|
|
43
43
|
[available video tracks]
|
|
44
44
|
${u.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
|
|
@@ -66,12 +66,12 @@ var Eu="2.0.149-dev.a444d83a.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(w).map(([T,O])=>`${T}: ${O}`).join(`
|
|
70
70
|
`)||"All tracks are available"}
|
|
71
71
|
|
|
72
72
|
[best video track] ${k?.quality}
|
|
73
73
|
[selected video track] ${I?.quality}
|
|
74
|
-
`}),I},Mi=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ta(t,
|
|
74
|
+
`}),I},Mi=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ta(t,wa);let h=r.considerPlaybackRate&&W(s)?s:1,d=[...t].sort(Ai(-1)),l=u.bitrate;yc(l);let p=h*Ia(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=ii(u,e,t,r.minVideoAudioRatio),b=c||i;W(b)&&isFinite(b)&&(m=d.find(y=>W(y.bitrate)&&W(f?.bitrate)?b-l>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Ea(r,o,m,n);return W(n)&&S?.bitrate!==g?.bitrate&&o({message:`
|
|
75
75
|
[AUDIO TRACKS ABR]
|
|
76
76
|
[available audio tracks]
|
|
77
77
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
@@ -92,7 +92,7 @@ var Eu="2.0.149-dev.a444d83a.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},Ri=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ta(t,
|
|
95
|
+
`}),S},Ri=(u,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:o,stallsPredictedThroughput:c})=>{Ta(t,wa);let h=r.considerPlaybackRate&&W(s)?s:1,d=mc.get(t);d||(d=[...t].sort(Ai(-1)),mc.set(t,d));let l=u.bitrate;yc(l);let p=h*Ia(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=ri(u,e,t,r.minVideoAudioRatio),b=c||i;W(b)&&isFinite(b)&&(m=d.find(y=>W(y.bitrate)&&W(f?.bitrate)?b-l>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,S=m&&Ea(r,o,m,n);return W(n)&&S?.bitrate!==g?.bitrate&&o({message:`
|
|
96
96
|
[AUDIO TRACKS ABR]
|
|
97
97
|
[available audio tracks]
|
|
98
98
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
@@ -113,7 +113,7 @@ var Eu="2.0.149-dev.a444d83a.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 se=u=>new URL(u).hostname;import{assertNever as $c,assertNonNullable as Mc,combine as Ap,debounce as $p,ErrorCategory as Rc,filter as Lc,filterChanged as Mp,isNonNullable as io,map as Aa,merge as Dc,observableFrom as Rp,once as Lp,Subscription as Dp,ValueSubject as ro,videoQualityToHeight as Bc,videoSizeToQuality as Bp}from"@vkontakte/videoplayer-shared/evergreen";var Ec=u=>{if(u instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(u.message))throw u;return!(u instanceof DOMException&&(u.code===20||u.name==="AbortError"))},Te=async(u,e)=>{let t=u.muted;try{await u.play()}catch(i){if(!Ec(i))return!1;if(e&&e(),t)return console.warn(i),!1;u.muted=!0;try{await u.play()}catch(r){return Ec(r)&&(u.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as xa,isNullable as dp,assertNonNullable as xr}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as wc,assertNonNullable as ka,now as np}from"@vkontakte/videoplayer-shared/evergreen";function de(){return np()}function Xn(u){return de()-u}function Jn(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 kc(u,e,t){let i=(...r)=>{t.apply(null,r),u.removeEventListener(e,i)};u.addEventListener(e,i)}function Li(u,e,t,i){let r=window.XMLHttpRequest,s,a,n,o=!1,c=0,h,d,l=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;ka(h);let D=Xn(h),I;if(D<f){I=f-D,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,P()},g=D=>(s=D,N),S=D=>(d=D,N),y=()=>(p="json",N),v=()=>{if(!o){if(--c>=0){b(),i&&i();return}o=!0,d&&d(),t&&t()}},w=D=>(l=D,N),P=()=>{h=de(),a=new r,a.open("get",u);let D=0,I,T=0,O=()=>(ka(h),Math.max(h,Math.max(I||0,T||0)));if(s&&a.addEventListener("progress",R=>{let U=de();s.updateChunk&&R.loaded>D&&(s.updateChunk(O(),R.loaded-D),D=R.loaded,I=U)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;ka(a);let R=a.status;if(R>=200&&R<300){let{response:U,responseType:G}=a,ee=U?.byteLength;if(typeof ee=="number"&&s){let re=ee-D;re&&s.updateChunk&&s.updateChunk(O(),re)}G==="json"&&(!U||!Object.values(U).length)?v():(d&&d(),e(U))}else v()}),a.addEventListener("error",()=>{v()}),l){let R=()=>{ka(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=de(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),N},N={withBitrateReporting:g,withParallel:w,withJSONResponse:y,withRetryCount:D=>(c=D,N),withRetryInterval:(D,I)=>(wc(D)&&(f=D),wc(I)&&(m=I),N),withTimeout:D=>(n=D,N),withFinally:S,send:P,abort:()=>{a&&(a.abort(),a=void 0),o=!0,d&&d()}};return N}var wr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,n=s.end-s.start;i+=a;let o=s.bytes*a/n;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var kr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=de(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=de()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Li(t,s,()=>r("error"),n),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as lp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as xc}from"@vkontakte/videoplayer-shared/evergreen";var B=(u,e)=>xc(u)&&xc(e)&&u.readyState==="open"&&op(u,e);function op(u,e){for(let t=0;t<u.activeSourceBuffers.length;++t)if(u.activeSourceBuffers[t]===e)return!0;return!1}var Zn=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]}}},up=(u,e="warn")=>{let t=[];function i(r,s=!1){let a=window.performance?.timing?.navigationStart??0,n=new Zn(u,Math.round((Date.now()-a)/1e3),r,s?new Error().stack:void 0);t.push(n),e&&window.console[e](n.toString())}return i.reset=()=>{t=[]},i.drain=()=>{let r=t;return t=[],r},i},C=up("vp_dash_live_debug",!1);var Pa=1e4,eo=3;var hp=6e4,pp=10,mp=1,fp=500,Pr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new lp,this.chunkRateEstimator=new wr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(C({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",C({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(C({m:"ldp.play.1"}),this._playVideoElement()):(C({m:"ldp.play.2"}),this._notifyBuffering(!0))):(C({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,C({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jn(e),C({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;C({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(C({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),C({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:o,min:c}=this.autoQualityLimits||{};!pc({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||xa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(C({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",n=>{C({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{C({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{kc(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new kr(eo,Pa,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,n=null,o=null,c=null,h=!1,d=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},l=(v,w,P)=>{o&&o.abort(),o=Li(this.urlResolver.resolve(v,!1),w,P,()=>this._retryCallback()).withTimeout(Pa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eo).withFinally(()=>{o=null}).send()},p=(v,w,P)=>{xr(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),w,P,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let w=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${w}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let P=de()-1e4,A=0;for(let L=0;L<this.bufferStates.length;L++){let k=this.bufferStates[L];v=Math.min(v,k.buf),k.ts<P&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${v} drop=${A} jitter=${this.sourceJitter}`);let E=v-mp;this.sourceJitter>=0?E-=this.sourceJitter/2:this.sourceJitter-=1,E>3?m(1.15):E>1?m(1.1):E>.3?m(1.05):m(1)}},g=v=>{let w,P=()=>w&&w.start?w.start.length:0,A=R=>w.start[R]/1e3,E=R=>w.dur[R]/1e3,L=R=>w.fragIndex+R,k=(R,U)=>({chunkIdx:L(R),startTS:A(R),dur:E(R),discontinuity:U}),N=()=>{let R=0;if(w&&w.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=U;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let re=w.dur.length-1;for(;re>=0&&(ee-=w.dur[re],!(ee<=0));--re);R=Math.min(re,w.dur.length-1-G),R=Math.max(R,0)}return k(R,!0)},D=R=>{let U=P();if(!(U<=0)){if(xa(R)){for(let G=0;G<U;G++)if(A(G)>R)return k(G)}return N()}},I=R=>{let U=P(),G=R?R.chunkIdx+1:0,ee=G-w.fragIndex;if(!(U<=0)){if(!R||ee<0||ee-U>pp)return t(`Resync: offset=${ee} bChunks=${U} chunk=`+JSON.stringify(R)),N();if(!(ee>=U))return k(G-w.fragIndex,!1)}},T=(R,U,G)=>{c&&c.abort(),c=Li(this.urlResolver.resolve(R,!0,this.lowLatency),U,G,()=>this._retryCallback()).withTimeout(Pa).withRetryCount(eo).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(R,U)=>{T(v,G=>{if(!d())return;w=G;let ee=!!w.lowLatency;ee!==this.lowLatency&&f(ee);let re=0;for(let pe=0;pe<w.dur.length;++pe)re+=w.dur[pe];re>0&&(xr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(D(U))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,n&&n.abort(),o&&o.abort(),c&&c.abort(),xr(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:w,logger:P}=this.params,A=g(e.jidxUrl),E,L,k,N,D=0,I,T,O,R=()=>{I&&(clearTimeout(I),I=void 0);let _=Math.max(fp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),fe=D+_,we=de(),ce=Math.min(1e4,fe-we);D=we;let Ue=()=>{c||d()&&A.seek(()=>{d()&&(D=de(),U(),R())})};ce>0?I=window.setTimeout(()=>{this.paused?R():Ue()},ce):Ue()},U=()=>{let _;for(;_=A.nextChunk(N);)N=_,me(_);let fe=A.nextChunk(k);if(fe){if(k&&fe.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?R():(S(),C({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}pe(fe)}else R()},G=(_,fe)=>{if(!d()||!this.sourceBuffer){C({m:"ab.0",c:[!d(),!this.sourceBuffer]});return}let we,ce,Ue,kt=We=>{C({m:"ldp.postpone",t:We}),window.setTimeout(()=>{d()&&G(_,fe)},We)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),C({m:"ldp.ab.1"}),kt(100);else{let We=de(),Ve=w.currentTime;!this.paused&&w.buffered.length>1&&T===Ve&&We-O>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),T!==Ve&&(T=Ve,O=We);let xt=this._getBufferSizeSec();if(xt>30)C({m:"ldp.ab.3"}),P(`Buffered ${xt} seconds; delaying appendBuffer`),kt(2e3);else try{if(this.params.config.useInvalidBufferFix&&B(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(C({m:"ldp.ab.5"}),this.bufferStates.push({ts:We,buf:xt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(C({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),fe&&fe()}catch(Ge){if(C({m:"ldp.ab.err",e:Ge.name}),Ge.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Ue=this.sourceBuffer.buffered.length,Ue!==0&&(we=this.sourceBuffer.buffered.start(0),ce=Ve,ce-we>4&&this.sourceBuffer.remove(we,ce-3)),kt(1e3);else throw Ge}}},ee=()=>{L&&E&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(k)]),G(L,function(){L=null,U()}))},re=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),pe=_=>{d()&&p(re(_),(fe,we)=>{if(d()){if(we/=1e3,L=fe,k=_,a=_.startTS,we){let ce=Math.min(10,_.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}ee()}},()=>this._handleNetworkError())},me=_=>{d()&&(xr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(_),!1)))},H=_=>{d()&&(e.cachedHeader=_,G(_,()=>{E=!0,ee()}))};s=!0,A.seek(_=>{if(d()){if(D=de(),!_){R();return}N=_,!dp(v)||_.startTS>v?pe(_):(k=_,U())}},v),e.cachedHeader?H(e.cachedHeader):l(e.headerUrl,H,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},h}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),xa(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,xr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let l,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}l=this._selectQuality(d),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(l,p)=>{let m=de();if(this.chunkRateEstimator.addInterval(l,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-l,speed:b}),!0}},get:()=>{let l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}},a=-1/0,n,o=!0,c=()=>{let d=s.get();if(d&&n&&this.autoQuality){if(o&&d>n&&Xn(a)<3e4)return;i(d)}o=this.autoQuality};return{updateChunk:(d,l)=>{let p=s.updateChunk(d,l);return p&&c(),p},notifySwitch:d=>{let l=de();d<n&&(a=l),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=Li(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Pa).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Te(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{C({m:"ldp.pve.1"}),t||(C({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let n=[];return a?.length?(a.forEach((o,c)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=c,n.push(o))}),n.sort(function(o,c){return o.video&&c.video?c.video.height-o.video.height:c.bitrate-o.bitrate}),n):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},hp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as bp,filter as Pc,fromEvent as gp,interval as Sp,isHigher as vp,isInvariantQuality as yp,isLower as Tp,merge as Ip,Subject as Ac,Subscription as Ep}from"@vkontakte/videoplayer-shared/evergreen";var to=class{constructor(){this.onDroopedVideoFramesLimit$=new Ac;this.subscription=new Ep;this.playing=!1;this.tracks=[];this.forceChecker$=new Ac;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&&!yp(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&&vp(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(gp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Sp(this.droppedFramesChecker.checkTime).pipe(Pc(()=>this.playing),Pc(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(bp(this.droppedFramesChecker.checkTime)),i=Ip(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])=>Tp(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Lt=to;import{map as wp,Observable as kp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as xp}from"@vkontakte/videoplayer-shared/evergreen";var Ar=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Pp=(u,e)=>new kp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(o=>t.next(o.isIntersecting||Ar()))},{...i,...e});r.observe(u);let s=xp(document,"visibilitychange").pipe(wp(a=>!document.hidden||Ar())).subscribe(a=>t.next(a));return()=>{r.unobserve(u),s.unsubscribe()}}),Ce=Pp;var Cp=["paused","playing","ready"],Vp=["paused","playing","ready"],$r=class{constructor(e){this.subscription=new Dp;this.videoState=new V("stopped");this.representations$=new ro([]);this.droppedFramesManager=new Lt;this.maxSeekBackTime$=new ro(1/0);this.zeroTime$=new ro(void 0);this.liveOffset=new ei;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Rc.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=nt(r.name)??Bp(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),io(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(Vp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Cp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){C({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&(C({m:"dlp.sync.2"}),this.dash.catchUp()),C({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(te(this.params.source.url,o))}return;default:return $c(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Rc.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Dc(this.videoState.stateChangeStarted$.pipe(Aa(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Aa(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{C({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ye(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Aa(r=>r.map(({track:s})=>s)),Lc(r=>!!r.length),Lp()).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(Mp(),Aa(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ap({zeroTime:this.zeroTime$.pipe(Lc(io)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(je(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Bc(r),min:s&&Bc(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),C({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(C({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":C({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":C({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return $c(r.to)}},t)).add(Dc(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rp(["init"])).pipe($p(0)).subscribe(this.syncPlayback,t))}destroy(){C({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Se(this.video)}createLiveDashPlayer(){let e=new Pr({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&io(t)?t:Qe(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==n){let c=e.find(({track:h})=>h.id===s)?.representation;Mc(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Mc(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),C({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(te(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Cc=$r;import{filterChanged as df}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Jp,assertNonNullable as Zp,debounce as em,ErrorCategory as zc,filter as ho,filterChanged as po,fromEvent as tm,isNonNullable as qc,isNullable as im,map as mo,merge as Ba,observableFrom as fo,once as Wc,Subscription as rm,throttle as sm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Op}from"@vkontakte/videoplayer-shared/evergreen";var Vc=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Op({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Oc=({id:u,bitrate:e})=>({id:u,bitrate:e}),Nc=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e});var so=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),$a=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var Me=u=>u.type==="template";var Ma=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ra=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 Fc=`attribute vec2 a_vertex;
|
|
116
|
+
`}),S};var se=u=>new URL(u).hostname;import{assertNever as $c,assertNonNullable as Mc,combine as Ap,debounce as $p,ErrorCategory as Rc,filter as Lc,filterChanged as Mp,isNonNullable as io,map as Aa,merge as Dc,observableFrom as Rp,once as Lp,Subscription as Dp,ValueSubject as ro,videoQualityToHeight as Bc,videoSizeToQuality as Bp}from"@vkontakte/videoplayer-shared/evergreen";var wc=u=>{if(u instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(u.message))throw u;return!(u instanceof DOMException&&(u.code===20||u.name==="AbortError"))},Te=async(u,e)=>{let t=u.muted;try{await u.play()}catch(i){if(!wc(i))return!1;if(e&&e(),t)return console.warn(i),!1;u.muted=!0;try{await u.play()}catch(r){return wc(r)&&(u.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as xa,isNullable as dp,assertNonNullable as xr}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Ec,assertNonNullable as ka,now as np}from"@vkontakte/videoplayer-shared/evergreen";function de(){return np()}function Xn(u){return de()-u}function Jn(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 kc(u,e,t){let i=(...r)=>{t.apply(null,r),u.removeEventListener(e,i)};u.addEventListener(e,i)}function Li(u,e,t,i){let r=window.XMLHttpRequest,s,a,n,o=!1,c=0,h,d,l=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;ka(h);let D=Xn(h),I;if(D<f){I=f-D,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,P()},g=D=>(s=D,N),S=D=>(d=D,N),y=()=>(p="json",N),v=()=>{if(!o){if(--c>=0){b(),i&&i();return}o=!0,d&&d(),t&&t()}},E=D=>(l=D,N),P=()=>{h=de(),a=new r,a.open("get",u);let D=0,I,T=0,O=()=>(ka(h),Math.max(h,Math.max(I||0,T||0)));if(s&&a.addEventListener("progress",R=>{let U=de();s.updateChunk&&R.loaded>D&&(s.updateChunk(O(),R.loaded-D),D=R.loaded,I=U)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;ka(a);let R=a.status;if(R>=200&&R<300){let{response:U,responseType:G}=a,ee=U?.byteLength;if(typeof ee=="number"&&s){let re=ee-D;re&&s.updateChunk&&s.updateChunk(O(),re)}G==="json"&&(!U||!Object.values(U).length)?v():(d&&d(),e(U))}else v()}),a.addEventListener("error",()=>{v()}),l){let R=()=>{ka(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=de(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),N},N={withBitrateReporting:g,withParallel:E,withJSONResponse:y,withRetryCount:D=>(c=D,N),withRetryInterval:(D,I)=>(Ec(D)&&(f=D),Ec(I)&&(m=I),N),withTimeout:D=>(n=D,N),withFinally:S,send:P,abort:()=>{a&&(a.abort(),a=void 0),o=!0,d&&d()}};return N}var Er=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,n=s.end-s.start;i+=a;let o=s.bytes*a/n;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var kr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=de(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=de()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Li(t,s,()=>r("error"),n),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as lp}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as xc}from"@vkontakte/videoplayer-shared/evergreen";var B=(u,e)=>xc(u)&&xc(e)&&u.readyState==="open"&&op(u,e);function op(u,e){for(let t=0;t<u.activeSourceBuffers.length;++t)if(u.activeSourceBuffers[t]===e)return!0;return!1}var Zn=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]}}},up=(u,e="warn")=>{let t=[];function i(r,s=!1){let a=window.performance?.timing?.navigationStart??0,n=new Zn(u,Math.round((Date.now()-a)/1e3),r,s?new Error().stack:void 0);t.push(n),e&&window.console[e](n.toString())}return i.reset=()=>{t=[]},i.drain=()=>{let r=t;return t=[],r},i},C=up("vp_dash_live_debug",!1);var Pa=1e4,eo=3;var hp=6e4,pp=10,mp=1,fp=500,Pr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new lp,this.chunkRateEstimator=new Er(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(C({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",C({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(C({m:"ldp.play.1"}),this._playVideoElement()):(C({m:"ldp.play.2"}),this._notifyBuffering(!0))):(C({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,C({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jn(e),C({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;C({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(C({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),C({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:o,min:c}=this.autoQualityLimits||{};!pc({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||xa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(C({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",n=>{C({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{C({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{kc(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new kr(eo,Pa,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,n=null,o=null,c=null,h=!1,d=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},l=(v,E,P)=>{o&&o.abort(),o=Li(this.urlResolver.resolve(v,!1),E,P,()=>this._retryCallback()).withTimeout(Pa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eo).withFinally(()=>{o=null}).send()},p=(v,E,P)=>{xr(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),E,P,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let E=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${E}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let P=de()-1e4,A=0;for(let L=0;L<this.bufferStates.length;L++){let k=this.bufferStates[L];v=Math.min(v,k.buf),k.ts<P&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${v} drop=${A} jitter=${this.sourceJitter}`);let w=v-mp;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?m(1.15):w>1?m(1.1):w>.3?m(1.05):m(1)}},g=v=>{let E,P=()=>E&&E.start?E.start.length:0,A=R=>E.start[R]/1e3,w=R=>E.dur[R]/1e3,L=R=>E.fragIndex+R,k=(R,U)=>({chunkIdx:L(R),startTS:A(R),dur:w(R),discontinuity:U}),N=()=>{let R=0;if(E&&E.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=U;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let re=E.dur.length-1;for(;re>=0&&(ee-=E.dur[re],!(ee<=0));--re);R=Math.min(re,E.dur.length-1-G),R=Math.max(R,0)}return k(R,!0)},D=R=>{let U=P();if(!(U<=0)){if(xa(R)){for(let G=0;G<U;G++)if(A(G)>R)return k(G)}return N()}},I=R=>{let U=P(),G=R?R.chunkIdx+1:0,ee=G-E.fragIndex;if(!(U<=0)){if(!R||ee<0||ee-U>pp)return t(`Resync: offset=${ee} bChunks=${U} chunk=`+JSON.stringify(R)),N();if(!(ee>=U))return k(G-E.fragIndex,!1)}},T=(R,U,G)=>{c&&c.abort(),c=Li(this.urlResolver.resolve(R,!0,this.lowLatency),U,G,()=>this._retryCallback()).withTimeout(Pa).withRetryCount(eo).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(R,U)=>{T(v,G=>{if(!d())return;E=G;let ee=!!E.lowLatency;ee!==this.lowLatency&&f(ee);let re=0;for(let pe=0;pe<E.dur.length;++pe)re+=E.dur[pe];re>0&&(xr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,R(D(U))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,n&&n.abort(),o&&o.abort(),c&&c.abort(),xr(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:E,logger:P}=this.params,A=g(e.jidxUrl),w,L,k,N,D=0,I,T,O,R=()=>{I&&(clearTimeout(I),I=void 0);let _=Math.max(fp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),fe=D+_,Ee=de(),ce=Math.min(1e4,fe-Ee);D=Ee;let Ue=()=>{c||d()&&A.seek(()=>{d()&&(D=de(),U(),R())})};ce>0?I=window.setTimeout(()=>{this.paused?R():Ue()},ce):Ue()},U=()=>{let _;for(;_=A.nextChunk(N);)N=_,me(_);let fe=A.nextChunk(k);if(fe){if(k&&fe.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?R():(S(),C({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}pe(fe)}else R()},G=(_,fe)=>{if(!d()||!this.sourceBuffer){C({m:"ab.0",c:[!d(),!this.sourceBuffer]});return}let Ee,ce,Ue,kt=We=>{C({m:"ldp.postpone",t:We}),window.setTimeout(()=>{d()&&G(_,fe)},We)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),C({m:"ldp.ab.1"}),kt(100);else{let We=de(),Ve=E.currentTime;!this.paused&&E.buffered.length>1&&T===Ve&&We-O>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),T!==Ve&&(T=Ve,O=We);let xt=this._getBufferSizeSec();if(xt>30)C({m:"ldp.ab.3"}),P(`Buffered ${xt} seconds; delaying appendBuffer`),kt(2e3);else try{if(this.params.config.useInvalidBufferFix&&B(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(C({m:"ldp.ab.5"}),this.bufferStates.push({ts:We,buf:xt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(C({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),fe&&fe()}catch(Ge){if(C({m:"ldp.ab.err",e:Ge.name}),Ge.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Ue=this.sourceBuffer.buffered.length,Ue!==0&&(Ee=this.sourceBuffer.buffered.start(0),ce=Ve,ce-Ee>4&&this.sourceBuffer.remove(Ee,ce-3)),kt(1e3);else throw Ge}}},ee=()=>{L&&w&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(k)]),G(L,function(){L=null,U()}))},re=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),pe=_=>{d()&&p(re(_),(fe,Ee)=>{if(d()){if(Ee/=1e3,L=fe,k=_,a=_.startTS,Ee){let ce=Math.min(10,_.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}ee()}},()=>this._handleNetworkError())},me=_=>{d()&&(xr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(_),!1)))},H=_=>{d()&&(e.cachedHeader=_,G(_,()=>{w=!0,ee()}))};s=!0,A.seek(_=>{if(d()){if(D=de(),!_){R();return}N=_,!dp(v)||_.startTS>v?pe(_):(k=_,U())}},v),e.cachedHeader?H(e.cachedHeader):l(e.headerUrl,H,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},h}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),xa(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,xr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let l,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}l=this._selectQuality(d),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(l,p)=>{let m=de();if(this.chunkRateEstimator.addInterval(l,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-l,speed:b}),!0}},get:()=>{let l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}},a=-1/0,n,o=!0,c=()=>{let d=s.get();if(d&&n&&this.autoQuality){if(o&&d>n&&Xn(a)<3e4)return;i(d)}o=this.autoQuality};return{updateChunk:(d,l)=>{let p=s.updateChunk(d,l);return p&&c(),p},notifySwitch:d=>{let l=de();d<n&&(a=l),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=Li(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Pa).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Te(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{C({m:"ldp.pve.1"}),t||(C({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let n=[];return a?.length?(a.forEach((o,c)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=c,n.push(o))}),n.sort(function(o,c){return o.video&&c.video?c.video.height-o.video.height:c.bitrate-o.bitrate}),n):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},hp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as bp,filter as Pc,fromEvent as gp,interval as Sp,isHigher as vp,isInvariantQuality as yp,isLower as Tp,merge as Ip,Subject as Ac,Subscription as wp}from"@vkontakte/videoplayer-shared/evergreen";var to=class{constructor(){this.onDroopedVideoFramesLimit$=new Ac;this.subscription=new wp;this.playing=!1;this.tracks=[];this.forceChecker$=new Ac;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&&!yp(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&&vp(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(gp(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Sp(this.droppedFramesChecker.checkTime).pipe(Pc(()=>this.playing),Pc(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(bp(this.droppedFramesChecker.checkTime)),i=Ip(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])=>Tp(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Lt=to;import{map as Ep,Observable as kp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as xp}from"@vkontakte/videoplayer-shared/evergreen";var Ar=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Pp=(u,e)=>new kp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(o=>t.next(o.isIntersecting||Ar()))},{...i,...e});r.observe(u);let s=xp(document,"visibilitychange").pipe(Ep(a=>!document.hidden||Ar())).subscribe(a=>t.next(a));return()=>{r.unobserve(u),s.unsubscribe()}}),Ce=Pp;var Cp=["paused","playing","ready"],Vp=["paused","playing","ready"],$r=class{constructor(e){this.subscription=new Dp;this.videoState=new V("stopped");this.representations$=new ro([]);this.droppedFramesManager=new Lt;this.maxSeekBackTime$=new ro(1/0);this.zeroTime$=new ro(void 0);this.liveOffset=new ei;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Rc.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=nt(r.name)??Bp(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),io(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(Vp.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Cp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){C({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&(C({m:"dlp.sync.2"}),this.dash.catchUp()),C({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(te(this.params.source.url,o))}return;default:return $c(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Rc.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Dc(this.videoState.stateChangeStarted$.pipe(Aa(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Aa(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{C({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ye(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Aa(r=>r.map(({track:s})=>s)),Lc(r=>!!r.length),Lp()).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(Mp(),Aa(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ap({zeroTime:this.zeroTime$.pipe(Lc(io)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(je(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Bc(r),min:s&&Bc(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),C({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(C({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":C({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":C({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return $c(r.to)}},t)).add(Dc(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rp(["init"])).pipe($p(0)).subscribe(this.syncPlayback,t))}destroy(){C({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Se(this.video)}createLiveDashPlayer(){let e=new Pr({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&io(t)?t:ze(e.map(({track:c})=>c),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==n){let c=e.find(({track:h})=>h.id===s)?.representation;Mc(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Mc(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),C({m:"dlp.seek",p:e,no:a,url:this.params.source.url}),this.dash.reinit(te(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Cc=$r;import{filterChanged as df}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Jp,assertNonNullable as Zp,debounce as em,ErrorCategory as Qc,filter as ho,filterChanged as po,fromEvent as tm,isNonNullable as qc,isNullable as im,map as mo,merge as Ba,observableFrom as fo,once as Wc,Subscription as rm,throttle as sm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Op}from"@vkontakte/videoplayer-shared/evergreen";var Vc=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Op({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Oc=({id:u,bitrate:e})=>({id:u,bitrate:e}),Nc=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e});var so=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),$a=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)});var Me=u=>u.type==="template";var Ma=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ra=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 Fc=`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 Bt=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 Ma(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ra(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(Fc,this.gl.VERTEX_SHADER),i=this.createShader(_c,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,n=e+i,o=t-r,c=e+i,h=t+r,d=e-i,l=t+r;return[s,a,n,o,c,h,d,l]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as _p,now as Mr,once as Up,Subscription as Hp,ValueSubject as no,isNonNullable as jp,safeStorage as oo,filterChanged as Qp}from"@vkontakte/videoplayer-shared/evergreen";var pt=(u,e,t)=>t*e+(1-t)*u,ao=(u,e)=>u.reduce((t,i)=>t+i,0)/e,Uc=(u,e,t,i)=>{let r=0,s=t,a=ao(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 La="stalls_manager_metrics",uo="stalls_manager_abr_params",Hc="stalls_manager_default_tuning_abr_params",co=class{constructor(){this.isSeeked$=new no(!1);this.isBuffering$=new no(!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 Hp;this.severeStallOccurred$=new no(!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(uo):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Hc)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(uo),this.setStoredData(Hc,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(La,"[]");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(La,[]),this.setStoredData(uo,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(oo.get(e)??t)}setStoredData(e,t){oo.set(e,JSON.stringify(t))}removeStoredData(e){oo.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(La,"[]"),r=t/e,s=i.length?pt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(La,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(Up()).subscribe(t=>this.providerStartWatchingTimestamp=Mr())),this.subscription.add(this.currentStallDuration$.pipe(Qp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(_p(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),o=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),h=Mr(),d=r&&this.currentStallsCount>=r,l=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&h-c>=i+n&&t>=i;(d||l)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,jp(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Di=co;import{combine as zp,map as qp,observeElementSize as Wp,Subscription as Gp,ValueSubject as lo,noop as Yp}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.subscription=new Gp;this.pipSize$=new lo(void 0);this.videoSize$=new lo(void 0);this.elementSize$=new lo(void 0);this.pictureInPictureWindowRemoveEventListener=Yp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Wp(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(zp({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(qp(({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 jc,map as Kp,once as Qc}from"@vkontakte/videoplayer-shared/evergreen";var Ct=({subscription:u,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,s=!1;u.add(e.volume.stateChangeStarted$.pipe(Kp(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),jc(a=>!!a),Qc()).subscribe(()=>{r=performance.now(),s=!0})),u.add(i.playbackRateState$.pipe(jc(()=>s),Qc()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var Rr=class{constructor(e){this.subscription=new rm;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new Da;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Jp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;im(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:zc.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ho(d=>!!d.length),Wc()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(mo(d=>d.to.state!=="none"),po());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(ho(qc),Wc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(mo(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Zp(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(so(b));let g=[];for(let S of b.representations){let y=Oc(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push($a(f));let b=[];for(let g of f.representations){let S=Vc({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=Nc(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Ba(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$,tm(this.video,"progress")).pipe(ho(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(sm(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition(),p=t.autoVideoTrackSwitching.getState();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,b]=m,g=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===f.id);qc(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready"?await this.player.initRepresentations(f.id,b?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,p),b&&await this.player.switchRepresentation("audio",b.id,p))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(po()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(so(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(mo(({to:d})=>d==="ready"),po());this.subscription.add(Ba(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,fo(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ba(c,this.player.state$.stateChangeEnded$,fo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Ba(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fo(["init"])).pipe(em(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?Qe:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:E})=>E===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:E})=>E===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:E})=>E===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};import{ErrorCategory as Lr}from"@vkontakte/videoplayer-shared/evergreen";var Bi=u=>{if(!u)return{id:"EmptyResponse",category:Lr.PARSER,message:"Empty response"};if(u.length<=2&&u.match(/^\d+$/))return{id:`UVError#${u}`,category:Lr.NETWORK,message:`UV Error ${u}`};let e=u.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Lr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(u,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Lr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Lr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as vd,assertNonNullable as gt,ErrorCategory as ni,filter as Po,filterChanged as Jm,flattenObject as ja,fromEvent as oi,getTraceSubscriptionMethod as Zm,interval as ef,isNonNullable as Ft,isNullable as ds,map as Ao,merge as ls,now as tf,Subject as _t,Subscription as yd,SubscriptionRemovable as rf,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";var Ze=u=>{let e=new URL(u);return e.searchParams.set("quic","1"),e.toString()};var Ci=u=>{let e=u.get("X-Delivery-Type"),t=u.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Dr,assertNever as Gc,ErrorCategory as Br,flattenObject as Oi,fromEvent as Yc,merge as am,now as Cr,Subject as Ni,Subscription as nm,ValueSubject as bo}from"@vkontakte/videoplayer-shared/evergreen";var Ie=u=>u instanceof DOMException&&(u.name==="AbortError"||u.code===20);var Vi=u=>{let e=new URL(u);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Va=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Ni;this.manifestReceived=new Ni;this.firstBytesRequested=new Ni;this.firstBytesReceived=new Ni;this.lastConnectionType$=new bo(void 0);this.lastConnectionReused$=new bo(void 0);this.lastRequestFirstBytes$=new bo(void 0);this.recoverableError$=new Ni;this.error$=new Ni;this.abortAllController=new AbortController;this.subscription=new nm;this.fetchManifest=Dr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ca);return r?(t.log("success",Oi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Oi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Dr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:Gc(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=am(Yc(this.abortAllController.signal,"abort"),Yc(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){Ca(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){Ca(T)}p=I.signal}let f=0,b=Cr();l.log("startRequest",Oi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=Cr();if(!g)return l.error("error",{message:"No response in request"}),l.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){m?.unsubscribe();let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){m?.unsubscribe();let I=Cr(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",Oi(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),w,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(w=P),!w&&i&&(w=i.to-i.from+1);let A=w?new Uint8Array(w):new Uint8Array(0),E=!1,L=I=>{m?.unsubscribe(),E=!0,Ca(I)},k=Dr(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Cr()-b),this.firstBytesReceived.next()),p.aborted){m?.unsubscribe();return}if(!I&&T){if(c&&w)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),m?.unsubscribe();let N=Cr(),D={failed:E,requestStartedAt:b,requestEndedAt:N,duration:N-b};return E?(l.error("endRequest",Oi(D)),l.end(),null):(l.log("endRequest",Oi(D)),l.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=Dr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:p,initDataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Dr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(a=>({...a,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:Gc(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Br.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Br.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Br.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Br.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Br.FATAL})}}},Ca=u=>{if(!Ie(u))throw u};var So=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 um,isNullable as Jc}from"@vkontakte/videoplayer-shared/evergreen";var Kc=u=>{if(u.includes("/")){let e=u.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(u)};var Xc=u=>{try{let e=om(),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 om(){let u="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",h=`^(?:(?<langtag>${`
|
|
170
|
+
`;var Bt=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 Ma(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ra(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(Fc,this.gl.VERTEX_SHADER),i=this.createShader(_c,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,n=e+i,o=t-r,c=e+i,h=t+r,d=e-i,l=t+r;return[s,a,n,o,c,h,d,l]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as _p,now as Mr,once as Up,Subscription as Hp,ValueSubject as no,isNonNullable as jp,safeStorage as oo,filterChanged as zp}from"@vkontakte/videoplayer-shared/evergreen";var pt=(u,e,t)=>t*e+(1-t)*u,ao=(u,e)=>u.reduce((t,i)=>t+i,0)/e,Uc=(u,e,t,i)=>{let r=0,s=t,a=ao(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 La="stalls_manager_metrics",uo="stalls_manager_abr_params",Hc="stalls_manager_default_tuning_abr_params",co=class{constructor(){this.isSeeked$=new no(!1);this.isBuffering$=new no(!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 Hp;this.severeStallOccurred$=new no(!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(uo):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Hc)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(uo),this.setStoredData(Hc,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(La,"[]");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(La,[]),this.setStoredData(uo,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(oo.get(e)??t)}setStoredData(e,t){oo.set(e,JSON.stringify(t))}removeStoredData(e){oo.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(La,"[]"),r=t/e,s=i.length?pt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(La,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(Up()).subscribe(t=>this.providerStartWatchingTimestamp=Mr())),this.subscription.add(this.currentStallDuration$.pipe(zp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(_p(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),o=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),h=Mr(),d=r&&this.currentStallsCount>=r,l=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&h-c>=i+n&&t>=i;(d||l)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,jp(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Di=co;import{combine as Qp,map as qp,observeElementSize as Wp,Subscription as Gp,ValueSubject as lo,noop as Yp}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.subscription=new Gp;this.pipSize$=new lo(void 0);this.videoSize$=new lo(void 0);this.elementSize$=new lo(void 0);this.pictureInPictureWindowRemoveEventListener=Yp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Wp(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(Qp({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(qp(({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 jc,map as Kp,once as zc}from"@vkontakte/videoplayer-shared/evergreen";var Ct=({subscription:u,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,s=!1;u.add(e.volume.stateChangeStarted$.pipe(Kp(()=>{let a=e.volume.getTransition(),n=t.getValue();return!n||!a?!1:!a.to.muted&&n.muted}),jc(a=>!!a),zc()).subscribe(()=>{r=performance.now(),s=!0})),u.add(i.playbackRateState$.pipe(jc(()=>s),zc()).subscribe(()=>{let a=t.getValue(),n=e.playbackRate.getState();a&&n!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=n)}))};var Rr=class{constructor(e){this.subscription=new rm;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new Da;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Jp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;im(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Qc.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(ho(d=>!!d.length),Wc()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(mo(d=>d.to.state!=="none"),po());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(ho(qc),Wc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(mo(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Zp(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(so(b));let g=[];for(let S of b.representations){let y=Oc(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push($a(f));let b=[];for(let g of f.representations){let S=Vc({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=Nc(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Ba(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$,tm(this.video,"progress")).pipe(ho(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(sm(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition(),p=t.autoVideoTrackSwitching.getState();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,b]=m,g=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===f.id);qc(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready"?await this.player.initRepresentations(f.id,b?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,p),b&&await this.player.switchRepresentation("audio",b.id,p))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(po()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(so(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(mo(({to:d})=>d==="ready"),po());this.subscription.add(Ba(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,fo(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ba(c,this.player.state$.stateChangeEnded$,fo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Ba(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fo(["init"])).pipe(em(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:w})=>w===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let w=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}if(c){let w=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=E&&this.audioTracksMap.get(E)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};import{ErrorCategory as Lr}from"@vkontakte/videoplayer-shared/evergreen";var Bi=u=>{if(!u)return{id:"EmptyResponse",category:Lr.PARSER,message:"Empty response"};if(u.length<=2&&u.match(/^\d+$/))return{id:`UVError#${u}`,category:Lr.NETWORK,message:`UV Error ${u}`};let e=u.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Lr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(u,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Lr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Lr.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as vd,assertNonNullable as gt,ErrorCategory as ni,filter as Po,filterChanged as Jm,flattenObject as ja,fromEvent as oi,getTraceSubscriptionMethod as Zm,interval as ef,isNonNullable as Ft,isNullable as ds,map as Ao,merge as ls,now as tf,Subject as _t,Subscription as yd,SubscriptionRemovable as rf,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";var Ze=u=>{let e=new URL(u);return e.searchParams.set("quic","1"),e.toString()};var Ci=u=>{let e=u.get("X-Delivery-Type"),t=u.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Dr,assertNever as Gc,ErrorCategory as Br,flattenObject as Oi,fromEvent as Yc,merge as am,now as Cr,Subject as Ni,Subscription as nm,ValueSubject as bo}from"@vkontakte/videoplayer-shared/evergreen";var Ie=u=>u instanceof DOMException&&(u.name==="AbortError"||u.code===20);var Vi=u=>{let e=new URL(u);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Va=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Ni;this.manifestReceived=new Ni;this.firstBytesRequested=new Ni;this.firstBytesReceived=new Ni;this.lastConnectionType$=new bo(void 0);this.lastConnectionReused$=new bo(void 0);this.lastRequestFirstBytes$=new bo(void 0);this.recoverableError$=new Ni;this.error$=new Ni;this.abortAllController=new AbortController;this.subscription=new nm;this.fetchManifest=Dr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ca);return r?(t.log("success",Oi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Oi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Dr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:Gc(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=am(Yc(this.abortAllController.signal,"abort"),Yc(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){Ca(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){Ca(T)}p=I.signal}let f=0,b=Cr();l.log("startRequest",Oi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=Cr();if(!g)return l.error("error",{message:"No response in request"}),l.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){m?.unsubscribe();let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){m?.unsubscribe();let I=Cr(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",Oi(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),E,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(E=P),!E&&i&&(E=i.to-i.from+1);let A=E?new Uint8Array(E):new Uint8Array(0),w=!1,L=I=>{m?.unsubscribe(),w=!0,Ca(I)},k=Dr(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Cr()-b),this.firstBytesReceived.next()),p.aborted){m?.unsubscribe();return}if(!I&&T){if(c&&E)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),m?.unsubscribe();let N=Cr(),D={failed:w,requestStartedAt:b,requestEndedAt:N,duration:N-b};return w?(l.error("endRequest",Oi(D)),l.end(),null):(l.log("endRequest",Oi(D)),l.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=Dr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:p,initDataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Dr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(a=>({...a,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:Gc(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Br.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Br.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Br.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Br.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Br.FATAL})}}},Ca=u=>{if(!Ie(u))throw u};var So=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 um,isNullable as Jc}from"@vkontakte/videoplayer-shared/evergreen";var Kc=u=>{if(u.includes("/")){let e=u.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(u)};var Xc=u=>{try{let e=om(),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 om(){let u="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",h=`^(?:(?<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(h,"i")}var Zc=u=>{if(!u?.startsWith("P"))return;let e=(a,n)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(u),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Oe=(u,e)=>{let t=u;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,o)=>Jc(s)?n:Jc(o)?s:s.padStart(parseInt(o,10),"0"))}return t},_i=(u,e)=>{let i=new DOMParser().parseFromString(u,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(L=>L.textContent?.trim()??""),n=a.at(0)??"",o=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],l=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:c?new Date(c).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:l?new Date(l).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],v=y.reduce((L,k)=>({...L,[k.id]:k.children}),{}),w=y.reduce((L,k)=>({...L,[k.id]:k.getAttribute("duration")}),{});S?g=Zc(S):Object.values(w).filter(L=>L).length&&!o?g=Object.values(w).reduce((L,k)=>L+(Zc(k)??0),0):f&&(g=parseInt(f,10));let P=0,A=s.getAttribute("profiles")?.split(",")??[];for(let L of y.map(k=>k.id))for(let k of v[L]){let N=k.getAttribute("id")??"id"+(P++).toString(10),D=k.getAttribute("mimeType")??"",I=k.getAttribute("codecs")??"",T=k.getAttribute("contentType")??D?.split("/")[0],O=k.getAttribute("profiles")?.split(",")??[],R=Xc(k.getAttribute("lang")??"")??{},U=k.querySelector("Label")?.textContent?.trim()??void 0,G=k.querySelectorAll("Representation"),ee=k.querySelector("SegmentTemplate"),re=k.querySelector("Role")?.getAttribute("value")??void 0,pe=T,me={id:N,language:R.language,isDefault:re==="main",label:U,codecs:I,hdr:pe==="video"&&So(I),mime:D,representations:[]};for(let H of G){let _=H.getAttribute("lang")??void 0,fe=U??k.getAttribute("label")??H.getAttribute("label")??void 0,we=H.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(we||n,e).toString(),Ue=H.getAttribute("mimeType")??D,kt=H.getAttribute("codecs")??I??"",We;if(T==="text"){let Ve=H.getAttribute("id")||"",xt=R.privateuse?.includes("x-auto")||Ve.includes("_auto"),Ge=H.querySelector("SegmentTemplate");if(Ge){let cr={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=parseInt(Ge.getAttribute("startNumber")??"",10)??1,bi=parseInt(Ge.getAttribute("timescale")??"",10),xn=Ge.querySelectorAll("SegmentTimeline S")??[],gi=Ge.getAttribute("media");if(!gi)continue;let Ys=[],Ks=0,Xs="",Si=0,dr=Gs,ke=0;for(let Ye of xn){let Gt=parseInt(Ye.getAttribute("d")??"",10),He=parseInt(Ye.getAttribute("r")??"",10)||0,Pt=parseInt(Ye.getAttribute("t")??"",10);ke=Number.isFinite(Pt)?Pt:ke;let Yt=Gt/bi*1e3,vi=ke/bi*1e3;for(let it=0;it<He+1;it++){let At=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:(ke+it*Gt).toString(10)}),yi=(vi??0)+it*Yt,hr=yi+Yt;dr++,Ys.push({time:{from:yi,to:hr},url:At})}ke+=(He+1)*Gt,Ks+=(He+1)*Yt}Si=ke/bi*1e3,Xs=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:ke.toString(10)});let lr={time:{from:Si,to:1/0},url:Xs},ct={type:"template",baseUrl:ce,segmentTemplateUrl:gi,initUrl:"",totalSegmentsDurationMs:Ks,segments:Ys,nextSegmentBeyondManifest:lr,timescale:bi};We={id:Ve,kind:"text",segmentReference:ct,profiles:[],duration:g,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:xt}}else We={id:Ve,isAuto:xt,kind:"text",url:ce}}else{let Ve=H.getAttribute("contentType")??Ue?.split("/")[0]??T,xt=k.getAttribute("profiles")?.split(",")??[],Ge=parseInt(H.getAttribute("width")??"",10),cr=parseInt(H.getAttribute("height")??"",10),Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=H.getAttribute("frameRate")??"",bi=H.getAttribute("quality")??void 0,xn=Gs?Kc(Gs):void 0,gi=H.getAttribute("id")??"id"+(P++).toString(10),Ys=Ve==="video"?`${cr}p`:Ve==="audio"?`${Ws}Kbps`:kt,Ks=`${gi}@${Ys}`,Xs=[...A,...O,...xt],Si,dr=H.querySelector("SegmentBase"),ke=H.querySelector("SegmentTemplate")??ee;if(dr){let ct=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,Gt]=ct.split("-").map(At=>parseInt(At,10)),He={from:Ye,to:Gt},Pt=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Yt,vi]=Pt?Pt.split("-").map(At=>parseInt(At,10)):[],it=Pt?{from:Yt,to:vi}:void 0;Si={type:"byteRange",url:ce,initRange:He,indexRange:it}}else if(ke){let ct={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ye=parseInt(ke.getAttribute("timescale")??"",10),Gt=ke.getAttribute("initialization")??"",He=ke.getAttribute("media"),Pt=parseInt(ke.getAttribute("startNumber")??"",10)??1,Yt=Oe(Gt,ct);if(!He)throw new ReferenceError("No media attribute in SegmentTemplate");let vi=ke.querySelectorAll("SegmentTimeline S")??[],it=[],At=0,yi="",hr=0;if(vi.length){let Js=Pt,Ke=0;for(let Ti of vi){let rt=parseInt(Ti.getAttribute("d")??"",10),Kt=parseInt(Ti.getAttribute("r")??"",10)||0,Zs=parseInt(Ti.getAttribute("t")??"",10);Ke=Number.isFinite(Zs)?Zs:Ke;let Pn=rt/Ye*1e3,Yl=Ke/Ye*1e3;for(let ea=0;ea<Kt+1;ea++){let Kl=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:(Ke+ea*rt).toString(10)}),Iu=(Yl??0)+ea*Pn,Xl=Iu+Pn;Js++,it.push({time:{from:Iu,to:Xl},url:Kl})}Ke+=(Kt+1)*rt,At+=(Kt+1)*Pn}hr=Ke/Ye*1e3,yi=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:Ke.toString(10)})}else if(um(g)){let Ke=parseInt(ke.getAttribute("duration")??"",10)/Ye*1e3,Ti=Math.ceil(g/Ke),rt=0;for(let Kt=1;Kt<Ti;Kt++){let Zs=Oe(He,{...ct,segmentNumber:Kt.toString(10),segmentTime:rt.toString(10)});it.push({time:{from:rt,to:rt+Ke},url:Zs}),rt+=Ke}hr=rt,yi=Oe(He,{...ct,segmentNumber:Ti.toString(10),segmentTime:rt.toString(10)})}let Gl={time:{from:hr,to:1/0},url:yi};Si={type:"template",baseUrl:ce,segmentTemplateUrl:He,initUrl:Yt,totalSegmentsDurationMs:At,segments:it,nextSegmentBeyondManifest:Gl,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ve||!Ue)continue;let lr={video:"video",audio:"audio",text:"text"}[Ve];if(!lr)continue;pe||=lr,We={id:Ks,kind:lr,segmentReference:Si,profiles:Xs,duration:g,bitrate:Ws,mime:Ue,codecs:kt,width:Ge,height:cr,fps:xn,quality:bi}}me.language||=_,me.label||=fe,me.mime||=Ue,me.codecs||=kt,me.hdr||=pe==="video"&&So(kt),me.representations.push(We)}if(pe){let H=r[pe].find(_=>_.id===me.id);if(H&&me.representations.every(_=>_.segmentReference.type==="template"))for(let _ of H.representations){let fe=me.representations.find(Ue=>Ue.id===_.id);if(!fe)continue;let we=fe.segmentReference,ce=_.segmentReference;ce.segments.push(...we.segments),ce.nextSegmentBeyondManifest=we.nextSegmentBeyondManifest}else r[pe].push(me)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as Fa}from"@vkontakte/videoplayer-shared/evergreen";var Na=u=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(u){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Fa(u)}},ed=({webmCodec:u,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Na(u),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Na(u),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Na(u),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Na(u),...s,"HLS","HLS_ONDEMAND"];default:Fa(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Fa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},td=({androidPreferredFormat:u,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,o=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(u){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:Fa(u)}else $.video.nativeHlsSupported&&!o&&!$.browser.isChromiumBased?n=a:o?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},vo=u=>u?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ui=u=>{if(u.size===0)return;if(u.size===1)return u.values().next().value.split(".").at(0);for(let t of u){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return u.values().next().value.split(".").at(0)},Hi=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return hm().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},ji=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return pm().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Vt=u=>u.split(".")[0].replace("0",""),hm=()=>["av1","vp9","hev1","avc1"],pm=()=>["opus","mp4a"];import{abortable as wo,assertNonNullable as ot,ErrorCategory as Bm,fromEvent as Cm,getExponentialDelay as Vm,isHigher as Om,isNonNullable as ie,isNullable as le,once as Nm,Subject as Fm,Subscription as _m,ValueSubject as os}from"@vkontakte/videoplayer-shared/evergreen";var _a=u=>u.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,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 Qi=class extends Q{};import{assertNever as mm}from"@vkontakte/videoplayer-shared/evergreen";var Vr=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:mm(e)}}};var Or=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Nr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Fr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var _r=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ur=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var si=class extends Y{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,n=this.readUint32();r=this.readUint32();let o=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}};var Hr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qr=class extends Y{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var zr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var qr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Wr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends Y{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Yr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Jr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends Y{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var es=class extends Y{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ts=class extends Y{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var is=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var ss=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var bm={ftyp:Or,moov:Nr,mvhd:Fr,moof:_r,mdat:Ur,sidx:si,trak:Hr,mdia:Wr,mfhd:Xr,tkhd:Gr,traf:Jr,tfhd:Zr,tfdt:es,trun:ts,minf:Yr,sv3d:jr,st3d:Qr,prhd:zr,proj:Kr,equi:qr,uuid:Vr,stbl:is,stsd:rs,avc1:ss,unknown:Qi},ft=class u{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!_a(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=bm[e];return i?new i(t,new u):new Qi(t,new u)}};var Ot=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{_a(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 Sm=new TextDecoder("ascii"),vm=u=>Sm.decode(new DataView(u.buffer,u.byteOffset+4,4))==="ftyp",ym=u=>{let e=new si(u,new ft),t=e.earliestPresentationTime/e.timescale*1e3,i=u.byteOffset+u.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},Tm=(u,e)=>{let i=new ft().parse(u),r=new Ot(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],o=a[a.length-1],c=n.source.byteOffset,d=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(u.buffer,c,d)},Im=u=>{let t=new ft().parse(u),i=new Ot(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Em=u=>{let t=new ft().parse(u);return new Ot(t).find("sidx")?.timescale},wm=(u,e)=>{let i=new ft().parse(u),s=new Ot(i).findAll("traf"),a=s[s.length-1].children.find(d=>d.type==="tfhd"),n=s[s.length-1].children.find(d=>d.type==="tfdt"),o=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return o.sampleDuration.length?c=o.sampleDuration.reduce((d,l)=>d+l,0):c=a.defaultSampleDuration*o.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},km=u=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ft().parse(u),r=new Ot(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},id={validateData:vm,parseInit:km,getIndexRange:()=>{},parseSegments:ym,parseFeedableSegmentChunk:Tm,getChunkEndTime:wm,getServerLatencyTimestamps:Im,getTimescaleFromIndex:Em};import{assertNonNullable as yo,isNonNullable as nd,isNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as xm}from"@vkontakte/videoplayer-shared/evergreen";var rd={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"}},sd=u=>{let e=u.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=as(u,t),r=i in rd,s=r?rd[i].type:"binary",a=u.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let o=new DataView(u.buffer,u.byteOffset+t+1,n-1),c=a&255>>n,h=as(o),d=c*2**((n-1)*8)+h,l=t+n,p;return l+d>u.byteLength?p=new DataView(u.buffer,u.byteOffset+l):p=new DataView(u.buffer,u.byteOffset+l,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:l,tagSize:l+d,value:p,valueSize:d}},as=(u,e=u.byteLength)=>{switch(e){case 1:return u.getUint8(0);case 2:return u.getUint16(0);case 3:return u.getUint8(0)*2**16+u.getUint16(1);case 4:return u.getUint32(0);case 5:return u.getUint8(0)*2**32+u.getUint32(1);case 6:return u.getUint16(0)*2**32+u.getUint32(2);case 7:{let t=u.getUint8(0)*281474976710656+u.getUint16(1)*4294967296+u.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(u,e)=>{switch(e){case"int":return u.getInt8(0);case"uint":return as(u);case"float":return u.byteLength===4?u.getFloat32(0):u.getFloat64(0);case"string":return new TextDecoder("ascii").decode(u);case"utf8":return new TextDecoder("utf-8").decode(u);case"date":return new Date(Date.UTC(2001,0)+u.getInt8(0)).getTime();case"master":return u;case"binary":return u;default:xm(e)}},ai=(u,e)=>{let t=0;for(;t<u.byteLength;){let i=new DataView(u.buffer,u.byteOffset+t),r=sd(i);if(!e(r))return;r.type==="master"&&ai(r.value,e),t=r.value.byteOffset-u.byteOffset+r.valueSize}},ad=u=>{if(u.getUint32(0)!==440786851)return!1;let e,t,i,r=sd(u);return ai(r.value,({tag:s,type:a,value:n})=>(s===17143?e=et(n,a):s===17026?t=et(n,a):s===17029&&(i=et(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var od=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Am=[231,22612,22743,167,171,163,160,175],$m=u=>{let e,t,i,r,s=!1,a=!1,n=!1,o,c,h=!1,d=0;return ai(u,({tag:l,type:p,value:m,valueSize:f})=>{if(l===21419){let b=et(m,p);c=as(b)}else l!==21420&&(c=void 0);return l===408125543?(e=m.byteOffset,t=m.byteOffset+f):l===357149030?s=!0:l===290298740?a=!0:l===2807729?i=et(m,p):l===17545?r=et(m,p):l===21420&&c===475249515?o=et(m,p):l===374648427?ai(m,({tag:b,type:g,value:S})=>b===30321?(h=et(S,g)===1,!1):!0):s&&a&&od.includes(l)&&(n=!0),!n}),yo(e,"Failed to parse webm Segment start"),yo(t,"Failed to parse webm Segment end"),yo(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:h,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Mm=u=>{if(Pm(u.cuesSeekPosition))return;let e=u.segmentStart+u.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Rm=(u,e)=>{let t=!1,i=!1,r=n=>nd(n.time)&&nd(n.position),s=[],a;return ai(u,({tag:n,type:o,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=et(c,o));break;case 183:break;case 241:a&&(a.position=et(c,o));break;default:t&&od.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,o)=>{let{time:c,position:h}=n,d=s[o+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Lm=u=>{let e=0,t=!1;try{ai(u,i=>i.tag===524531317?i.tagSize<=u.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Am.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},ud={validateData:ad,parseInit:$m,getIndexRange:Mm,parseSegments:Rm,parseFeedableSegmentChunk:Lm};var ze=u=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(u);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ud;case"mp4":return id}}throw new ReferenceError(`Unsupported mime type ${u}`)};import{videoSizeToQuality as Dm}from"@vkontakte/videoplayer-shared/evergreen";var Nt=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Dm({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},ns=({id:u,bitrate:e})=>({id:u,bitrate:e}),cd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),dd=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),To=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Io=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Eo=u=>"url"in u,Ne=u=>u.type==="template";var zi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,manifest:n}){this.error$=new Fm;this.playingRepresentation$=new os(void 0);this.playingRepresentationInit$=new os(void 0);this.currentSegmentLength$=new os(0);this.onLastSegment$=new os(!1);this.fullyBuffered$=new os(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new AbortController;this.downloadAbortController=new AbortController;this.subscription=new _m;this.startWith=wo(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ze(t.mime),this.nativeBufferManager.init(t.mime,t.codecs),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=wo(this.destroyAbortController.signal,async function*(e,t=!0){if(le(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);ot(r,`No such representation ${e}`),ot(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),a=this.segments.get(r.id);ot(s,"No init buffer for switching representation"),ot(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,o=d=>d.segment.networkStatus!=="downloaded"||d.segment.time.to-n>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=d=>{let l=this.representations.get(d.representationId);return ot(l,"No itemRepresentation for previous track before switch"),d.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(l,r)},h=d=>t?o(d)&&c(d):o(d);this.bufferPlaybackQueue.filter(h).forEach(d=>d.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(d=>!h(d)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(n),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=wo(this.downloadAbortController.signal,async function*(){let e=Vm(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),this.subscription.add(Cm(window,"online").pipe(Nm()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=a,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=n?.baseUrls??[],this.representations=new Map(i.map(o=>[o.id,o]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){le(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return ie(t)&&ie(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from}getRepresentationInitialTime(){return le(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(le(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){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(),window.cancelIdleCallback)for(let e of this.idleCallbacks.values())window.cancelIdleCallback(e);this.idleCallbacks.clear(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Nt(e),s=Nt(t);i=ie(r)&&ie(s)&&Om(s.quality,r.quality)}else if(this.kind==="audio"){let r=ns(e),s=ns(t);i=ie(r?.bitrate)&&ie(s?.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,requestIdleCallback(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():ie(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:a,initDataView:n,segments:o}=await s??{};if(this.initDataPromises.delete(e.id),le(n)||le(o))return;a&&this.parsedInitData.set(e.id,a);let c=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,o),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:Bm.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(le(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(n=>this.withinInterval(e,n.segment.time)),i=this.bufferPlaybackQueue.find(n=>n.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),s=this.bufferPlaybackQueue[0],a=this.downloadAbortController.signal;ie(r)&&ie(i)&&ie(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),ie(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,a):await this.appendSegmentPartially(i,a)),ie(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,a),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){ot(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(le(t)||le(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(a=>e>=a.time.from&&e<a.time.to);ie(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(le(t)||t.length===0)return;let i=t[t?.length-1];le(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){ot(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;ie(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(n=>this.withinInterval(e,n.time))),r=r===-1?0:r;let a=[];for(;r<t.length&&s>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:n,to:o}=t[r].time;s-=o-n,r++}return a}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return ie(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return ie(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return ie(e)?e-i>t:!1}async appendSegmentFully(e,t){if(le(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(le(e.segment.data)||le(e.segment.loadedBytes)||le(e.segment.feedingBytes)||le(e.segment.fedBytes)||le(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||ie(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let a of this.segments.values())for(let n of a)ie(n.size)&&s>0&&n.time.to<=e-r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size);for(let a of this.segments.values())for(let n of[...a].reverse())ie(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(o=>o.segment===n)&&!this.downloadingBufferItems.find(o=>o.segment===n)&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as Um,isNonNullable as Hm,isNullable as ld,now as hd}from"@vkontakte/videoplayer-shared/evergreen";var Ua=class extends zi{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=hd(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,a=0;for(;a<this.downloadingBufferItems.length&&this.downloadingBufferItems[a].segment.networkStatus==="none"&&(e<=r||t<=s);){let n=this.downloadingBufferItems[a].segment;n.networkStatus="downloading",n.size=1/0,n.loadedBytes=0,n.feedingBytes=0,n.fedBytes=0,i.push(this.downloadingBufferItems[a]),e+=n.byte.to+1-n.byte.from,t+=n.time.to+1-n.time.from,a++}return i}prepareFetchParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(n,o)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=hd(),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:Um.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||ld(n)||ld(r)||a.aborted))for(let o of e){let{segment:c}=o,h=c.byte.from-r,d=c.byte.to-r,l=d-h+1,p=h<s,m=d<=s;c.size=l,p&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+h,l),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o),c.loadedBytes=Math.min(l,s-h),await this.onDownloadItem(o)):Hm(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(l,s-h),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+h,c.loadedBytes),await this.onDownloadItem(o))))}}updateRepresentationBaseUrl(e,t){if(Me(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as jm,isNullable as ko,now as pd}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends zi{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=pd(),ko(n))return;let o=e[0],c=new DataView(n);o.segment.size=c.byteLength,o.segment.loadedBytes=c.byteLength,o.segment.data=c,this.onItemFullyDownloaded(o),await this.onDownloadItem(o),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(a,n)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=pd(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,signal:r,representationId:t.id})}catch(o){this.error$.next({id:"SegmentFeeding",category:jm.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:o})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Me(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let a=e[0],{segment:n}=a,o=this.representations.get(i);!this.downloadingBufferItems.length||ko(o)||ko(n.feedingBytes)||n.networkStatus!=="downloading"||s.aborted||(n.loadedBytes=r,n.loadedBytes>n.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(n.data=new DataView(t.buffer,t.byteOffset,n.loadedBytes),await this.onDownloadItem(a)))}updateRepresentationBaseUrl(e,t){if(!Me(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as Qm,ErrorCategory as zm,isNullable as bt,ValueSubject as md}from"@vkontakte/videoplayer-shared/evergreen";var Ha=class extends qi{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new md(0);this.currentLowLatencySegmentLength$=new md(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=t.streams[this.kind].flatMap(r=>r.representations);for(let r of i){if(bt(r)||!Me(r.segmentReference))return;let s=r.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],o=n.at(-1)?.time.to??0,c=s?.findIndex(h=>o>=h.time.from+a&&o<=h.time.to+a);if(c===-1){let h=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,h)}else{let h=s.slice(c+1);this.segments.set(r.id,[...n,...h])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;Qm(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let r=t?.streams[this.kind]?.flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(bt(r))return;let s=this.segments.get(r.id);if(s?.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){if(bt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return bt(t)||!Me(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),bt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:a}=r.getServerLatencyTimestamps(i);s&&a&&this.currentLiveSegmentServerLatency$.next(a-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(bt(t.segment.data)||bt(r)||!Me(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:a}=r;t.segment.time.to=s.getChunkEndTime(i,a)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Me(s))return;let a=this.segments.get(r.id)??[],n=a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(n?.isCurrentLowLatency&&(n.time.to=t.segment.time.to,i=n.time.to-n.time.from,n.isCurrentLowLatency=!1),!!!a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*s.timescale/1e3).toString(10),h=Oe(s.segmentTemplateUrl,{segmentTime:c});a.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:h,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let s=this.tuning.dash.useFetchPriorityHints?i:"auto",a=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,a);let{initMetadata:n,initDataView:o,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),bt(o)||bt(c))return;n&&this.parsedInitData.set(t.id,n);let h=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,h);let d=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(t.id,d),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:zm.WTF,message:"loadInit threw",thrown:s})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],a=0,n=i.length-1;do s.unshift(i[n]),a+=i[n].time.to-i[n].time.from,n--;while(a<r&&n>=0);return this.liveInitialAdditionalOffset=a-r,this.isActiveLowLatency()?[s[0]]:s}};var us=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new Ha(e,t,i,r):Me(i[0].segmentReference)?new qi(e,t,i,r):new Ua(e,t,i,r)}};import{ErrorCategory as Gm,fromEvent as Ym,isNullable as Wi,Subject as Km,Subscription as Xm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as qm,ErrorCategory as fd,Subject as bd}from"@vkontakte/videoplayer-shared/evergreen";var Wm=18,gd=!1;try{gd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=Wm}catch(u){console.error(u)}var xo=class{constructor(e){this.bufferFull$=new bd;this.error$=new bd;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:fd.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};gd&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue[0];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:fd.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:qm(t)}}},Sd=xo;var ae=(u,e)=>{let t=0;for(let i=0;i<u.length;i++){let r=u.start(i)*1e3,s=u.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var cs=class{constructor(e){this.error$=new Km;this.subscription=new Xm;this.mediaSource=e}init(e,t){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Sd(this.sourceBuffer),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(i=>this.error$.next(i))),this.subscription.add(Ym(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gm.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(Wi(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!Wi(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Wi(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return Wi(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Wi(e)?0:ae(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Wi(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var sf=["timeupdate","progress","play","seeked","stalled","waiting"],Td=["timeupdate","progress","loadeddata","playing","seeked"],Qa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new yd;this.subscriptionRemovable=new rf;this.representationSubscription=new yd;this.forceEnded$=new _t;this.destroyController=new AbortController;this.state$=new V("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new _t;this.manifestRequested=new _t;this.manifestReceived=new _t;this.firstBytesRequested=new _t;this.firstBytesReceived=new _t;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.currentBuffer$=new K({from:0,to:0});this.bufferLength$=new K(0);this.nativeBufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new _t;this.fetcherError$=new _t;this.initRepresentations=vd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ja({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),gt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=vd(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){ds(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ni.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Va({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ni.PARSER,message:"No playable video representations"})}initBuffer(){gt(this.element),this.state$.setState("running"),this.subscription.add(ls(...sf.map(t=>oi(this.element,t)),oi(window,"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:ni.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(ls(...e.map(t=>oi(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(oi(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=ef(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:ni.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){gt(this.element),gt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",ja({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ft(this.element)&&Ft(this.source)&&Ft(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Ft(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(ds(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){gt(this.element),gt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",ja(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=tf(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,h=Ft(this.videoBufferManager)&&o<s&&r-a>i,d=Ft(this.audioBufferManager)&&c<s&&r-n>i;return(h||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(ds(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",ja(i)),i}parseManifest(e){try{return _i(e??"",this.manifestUrlString)}catch(t){let i=Bi(e)??{id:"ManifestParsing",category:ni.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:d,codecs:l})=>i(n,d,l));t[n]=c;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:l})=>l);n==="audio"&&(s=ji(d),h=s[0]),n==="video"&&(r=Hi(d),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?h=this.forceVideoCodec:h=r[0]),h&&(t[n]=c.filter(({codecs:l})=>Vt(l)===h))}else{let d=new Set(c.map(({codecs:l})=>l));h=Ui(d),h&&(t[n]=c.filter(({codecs:l})=>l.startsWith(h)))}if(n==="video"){let d=this.tuning.preferHDR,l=t.video.some(m=>m.hdr),p=t.video.some(m=>!m.hdr);$.display.isHDR&&d&&l?t.video=t.video.filter(m=>m.hdr):p&&(t.video=t.video.filter(m=>!m.hdr))}}let a={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(a.codecs={video:r,audio:s}),a}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){gt(this.manifest),gt(this.element);let s=o=>{this.representationSubscription.add(oi(o,"error").pipe(Po(c=>!!this.element?.played.length)).subscribe(c=>{this.error$.next({id:"VideoSource",category:ni.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:c})}))};this.source=Ii();let a=document.createElement("source");if(s(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Mt())if(r){let o=document.createElement("source");s(o),o.type="application/x-mpegurl",o.src=r.url,this.element.appendChild(o)}else this.element.disableRemotePlayback=!0;let n=this.manifest.streams.video.reduce((o,c)=>[...o,...c.representations],[]);if(this.videoNativeBufferManager=new cs(this.source),this.videoBufferManager=us.getBufferManager("video",this.videoNativeBufferManager,n,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],Ft(i)){this.audioNativeBufferManager=new cs(this.source);let o=this.manifest.streams.audio.reduce((c,h)=>[...c,...h.representations],[]);this.audioBufferManager=us.getBufferManager("audio",this.audioNativeBufferManager,o,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=setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:ni.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&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(ls(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),gt(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(ls(...Td.map(e=>oi(this.element,e))).pipe(Ao(e=>this.videoBufferManager?.getPlaybackBufferState()),Po(Ft),Ao(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(ls(...Td.map(e=>oi(this.element,e))).pipe(Ao(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),Jm()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Po(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=Zm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(ds(this.element)||ds(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 za,combine as af,ErrorCategory as nf,filter as $o,filterChanged as of,fromEvent as uf,isNonNullable as cf,map as Mo,merge as hs}from"@vkontakte/videoplayer-shared/evergreen";var qa=class extends Qa{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){za(this.manifest),za(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(t=>t.representations).flatMap(t=>{let i=[];return t.duration&&i.push(t.duration),Me(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){za(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){za(this.element);let e=hs(uf(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe($o(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(hs(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=hs(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Mo(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=hs(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Mo(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=af({allBuffersFull:e,someBufferEnded:t}).pipe(of(),Mo(({allBuffersFull:s,someBufferEnded:a})=>s&&a),$o(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:nf.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(hs(this.forceEnded$,i).pipe($o(s=>cf(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var Gi=class extends Rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(df()).subscribe(s=>{let a=[...this.videoTracksMap.entries()].find(([,{representation:d}])=>d.id===s);if(!a){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[n,{stream:o}]=a,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===o.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(n),e.currentVideoStream$.next($a(o));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r))}getPlayer(){return new qa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as Cf,assertNonNullable as Vf,combine as Of,debounce as Nf,ErrorCategory as Ld,filter as Fo,filterChanged as Ts,fromEvent as Ff,isNonNullable as Dd,isNullable as _f,map as Is,merge as Es,observableFrom as rn,once as Bd,Subscription as Uf,throttle as Hf}from"@vkontakte/videoplayer-shared/evergreen";var Ee=(u,e,t=0)=>{for(let i=0;i<u.length;i++)if(u.start(i)*1e3-t<=e&&u.end(i)*1e3+t>e)return!0;return!1};import{abortable as Co,assertNonNullable as Zi,combine as er,ErrorCategory as qe,filter as Za,filterChanged as Ss,flattenObject as vs,fromEvent as yt,getTraceSubscriptionMethod as Ef,interval as Vo,isNonNullable as ys,isNullable as $d,map as tr,merge as ci,now as Oo,Subject as Tt,Subscription as Md,SubscriptionRemovable as wf,tap as kf,throttle as xf,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as lf,ErrorCategory as Id,Subject as Ed}from"@vkontakte/videoplayer-shared/evergreen";var hf=18,wd=!1;try{wd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=hf}catch(u){console.error(u)}var Ro=class{constructor(e,t=!1){this.bufferFull$=new Ed;this.error$=new Ed;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:Id.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)};wd&&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:Id.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:lf(t)}}},kd=Ro;var Yi=u=>{let e=0;for(let t=0;t<u.length;t++)e+=u.end(t)-u.start(t);return e*1e3};import{abortable as Ut,assertNonNullable as Re,ErrorCategory as St,fromEvent as Lo,getExponentialDelay as Do,isHigher as pf,isNonNullable as Ht,isNullable as ne,now as Wa,once as mf,Subject as ff,Subscription as bf,ValueSubject as ui}from"@vkontakte/videoplayer-shared/evergreen";var ps=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new ui(0);this.currentLowLatencySegmentLength$=new ui(0);this.currentSegmentLength$=new ui(0);this.onLastSegment$=new ui(!1);this.fullyBuffered$=new ui(!1);this.playingRepresentation$=new ui(void 0);this.playingRepresentationInit$=new ui(void 0);this.error$=new ff;this.gaps=[];this.subscription=new bf;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kd(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:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(Lo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:St.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=this.getForwardBufferDuration(n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Ht(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Ht(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ut(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Ne(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Re(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Re(s,"No segments for starting representation");let a=this.initData.get(i);if(Re(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ne(n)||ne(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Re(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Ht(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||Ht(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),ne(r)||ne(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);Ht(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=Nt(i),m=Nt(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ht(p)&&Ht(m)&&pf(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=[];if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Ht(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!Ne(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ne(r))return;let s=this.segments.get(i.id)??[],a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Ne(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ut(n,async function*(){let h=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Wa(),!h)return;let d=new DataView(h),l=ze(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ne(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let o=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Lo(window,"online").pipe(mf()).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=Wa(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ne(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Wa(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ne(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Wa();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=ze(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(!p)continue;let f=ze(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===l?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:St.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Eo(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,n=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ze(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:c,dataView:h,segments:d}=o,l=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ne(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:St.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let r=[],s=0,a=o=>{o.sort((h,d)=>h.from-d.from);let c=[o[0]];for(let h=1;h<o.length;h++){let{from:d,to:l}=o[h],p=c[c.length-1];p.to>=d?p.to=Math.max(p.to,l):c.push(o[h])}return c},n=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let c=Eo(o)?o.size??0:o.byte.to-o.byte.from;s+=c};for(let o of this.segments.values())for(let c of o){let h=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||d)&&c.status==="fed"&&n(c)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let c=this.sourceBuffer.buffered.start(o)*1e3,h=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let l of this.segments.values())for(let p of l)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)&&d++;if(d===this.segments.size){let l={time:{from:c,to:h},url:"",status:"none"};n(l)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let h of c)h.time.from>=e+o&&h.status==="fed"&&n(h)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,h)=>c||h,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let a=0;a<s.length;a++){let 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||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let a=Math.round(s.from),n=Math.round(s.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:St.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ne(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=e.some(h=>h.from-t<=a&&h.to+t>=n),c=e.filter(h=>a>=h.from&&a<h.to-t||n>h.from+t&&n<=h.to);o||(c.length===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:St.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as ms,assertNever as xd,fromEvent as Pd,merge as gf,now as fs,Subject as Ki,ValueSubject as Bo,flattenObject as Xi,ErrorCategory as bs,SubscriptionRemovable as Sf}from"@vkontakte/videoplayer-shared/evergreen";var Ya=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 Bo(void 0);this.lastConnectionReused$=new Bo(void 0);this.lastRequestFirstBytes$=new Bo(void 0);this.recoverableError$=new Ki;this.error$=new Ki;this.abortAllController=new AbortController;this.subscription=new Sf;this.fetchManifest=ms(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ga);return r?(t.log("success",Xi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Xi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ms(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:h=!1}={}){let d=e,l=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(d,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:xd(t)}this.requestQuic&&(d=Ze(d));let m=this.abortAllController.signal,f;if(a){let T=new AbortController;if(f=gf(Pd(this.abortAllController.signal,"abort"),Pd(a,"abort")).subscribe(()=>{try{T.abort()}catch(O){Ga(O)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(O){Ga(O)}m=T.signal}let b=0,g=fs();p.log("startRequest",Xi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(d,{priority:s,headers:l,signal:m},{ignoreNetworkErrors:h}),y=fs();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(y-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let T=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!n){this.unsubscribeAbortSubscription(f);let T=fs(),O={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",Xi(O)),p.end(),S.arrayBuffer()}let v=S.body;if(n){let T;[v,T]=S.body.tee(),this.throughputEstimator?.trackStream(T,o)}let w=v.getReader(),P,A=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(A)&&(P=A),!P&&i&&(P=i.to-i.from+1);let E=P?new Uint8Array(P):new Uint8Array(0),L=!1,k=T=>{this.unsubscribeAbortSubscription(f),L=!0,Ga(T)},N=ms(m,async function*({done:T,value:O}){if(b===0&&(this.lastRequestFirstBytes$.next(fs()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!T&&O){if(c&&P)E.set(O,b),b+=O.byteLength;else{let R=new Uint8Array(E.length+O.length);R.set(E),R.set(O,E.length),E=R,b+=O.byteLength}r?.(new DataView(E.buffer),b),yield w?.read().then(N,k)}}.bind(this));yield w?.read().then(N,k),this.unsubscribeAbortSubscription(f);let D=fs(),I={failed:L,requestStartedAt:g,requestEndedAt:D,duration:D-g};return L?(p.error("endRequest",Xi(I)),p.end(),null):(p.log("endRequest",Xi(I)),p.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=ms(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},measureThroughput:!1,...i});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=ms(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:xd(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:bs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:bs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:bs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:bs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:bs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ga=u=>{if(!Ie(u))throw u};import{isNullable as vf,ValueSubject as Ad}from"@vkontakte/videoplayer-shared/evergreen";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ad(e.initial),this.debounced$=new Ad(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(vf(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ka=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pt(this.slow,e,this.params.emaAlphaSlow),this.fast=pt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xa=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ao(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pt(this.emaSmoothed,e,this.params.emaAlpha);let i=Uc(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ja=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?pt(this.smoothed,t,this.params.emaAlpha):t}};var vt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ka({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xa({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 Ja({initial:e,label:"liveEdgeDelay",...t})}};var Ji=(u,e)=>{u&&u.playbackRate!==e&&(u.playbackRate=e)};import{isNullable as yf,ValueSubject as Tf}from"@vkontakte/videoplayer-shared/evergreen";var gs=class u{constructor(e,t){this.currentRepresentation$=new Tf(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(!yf(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ne(t.segmentReference))}};var Pf=["timeupdate","progress","play","seeked","stalled","waiting"],Af=["timeupdate","progress","loadeddata","playing","seeked"];var en=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Md;this.subscriptionRemovable=new wf;this.representationSubscription=new Md;this.state$=new V("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Tt;this.manifestRequested$=new Tt;this.firstBytesManifest$=new Tt;this.manifestReceived$=new Tt;this.firstBytesRequested$=new Tt;this.firstBytesReceived$=new Tt;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Tt;this.fetcherError$=new Tt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=Co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Co(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qe.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Bi(e)??{id:"ManifestParsing",category:qe.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";if(d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p),d&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:qe.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",vs(n)),n}.bind(this));this.initRepresentations=Co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",vs({initialVideo:e,initialAudio:t,sourceHls:i})),Zi(this.manifest),Zi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(yt(d,"error").pipe(Za(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((d,l)=>[...d,...l.representations],[]);if(this.videoBufferManager=new ps("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],ys(t)){let d=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=new ps("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}if(gs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new gs(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ci(...Af.map(d=>yt(this.element,d))).pipe(tr(d=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Ss(),kf(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ss()).subscribe(l=>this.liveStreamEndTimestamp=Oo())),this.subscription.add(yt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:l}=this.tuning.dash;this.livePauseWatchdogSubscription=Vo(l).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+l,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(yt(this.element,"play").subscribe(l=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(er({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(tr(({isActiveLive:l,isLowLatency:p})=>l&&p),Ss()).subscribe(l=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(er({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Za(({bufferLength:l,isActiveLive:p,isLowLatency:m})=>p&&m&&!!l)).subscribe(({bufferLength:l})=>this.liveBuffer.next(l))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(l=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!l)return;let p=this.liveSeekableDuration$.getValue()-l/1e3;this.liveSeekableDuration$.next(Math.max(p,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+l/1e3)})),this.representationSubscription.add(er({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Za(({isLive:l})=>l),Ss((l,p)=>p.bufferLength<l.bufferLength),tr(({rtt:l,bufferLength:p,segmentServerLatency:m})=>{let f=$t(this.manifestUrlString,2);return(l/2+p+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(er({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:l,isActiveLive:p,isLowLatency:m})=>{if(!m||!p)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=l-f;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*g),Ji(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(l=>{let p=0;if(l){let m=(this.element?.currentTime??0)*1e3;p=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==p&&this.liveLoadBufferLength$.next(p)}));let d=0;this.representationSubscription.add(er({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xf(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:l,bufferLength:p})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=$t(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(l)?l:p,w=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let A="none";if(w?A="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(E=>E.proceedLowLatencyLive()),A="active_low_latency"):f!==0&&v<g?A="live_forward_buffering":v<g+y&&(A="live_with_target_offset"),isFinite(l)&&(d=l>d?l:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let E=d-(g+S),L=this.normalizeLiveOffset(Math.trunc(f+E/m)),k=Math.abs(L-f),N=0;!l||k<=this.tuning.dashCmafLive.offsetCalculationError?N=f:L>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=te(this.manifestUrlString,N,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},l=>{this.error$.next({id:"updateLive",category:qe.VIDEO_PIPELINE,thrown:l,message:"Failed to update live with subscription"})}))}let o=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(tr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(tr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=er({allBuffersFull:o,someBufferEnded:c}).pipe(Ss(),tr(({allBuffersFull:d,someBufferEnded:l})=>d&&l),Za(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(l=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){l();return}this.error$.next({id:"OpenOfStream",category:qe.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),l()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ne(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&ys(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=Vo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:qe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Ya({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Zi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Oo()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Zi(this.element),this.state$.setState("running"),this.subscription.add(ci(...Pf.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:a}=this.tuning.dash,n=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let h=this.currentStallDuration$.getValue();h+=a,this.currentStallDuration$.next(h);let d={timeInWaiting:h},l=Oo(),p=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,b=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,S=b<p&&l-m>r,y=this.audioBufferManager&&g<p&&l-f>r;if((!t||c)&&((S||y)&&h>r||h>=i))throw new Error(`Stall timeout exceeded: ${h} ms`);if(n&&h%s===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:qe.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),d.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),d.position=v}this.tracer.log("stallIntervalCallback",vs(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Vo(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:qe.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Zi(this.element),Zi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!($d(this.element)||$d(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",vs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ys(this.element)&&ys(this.source)&&ys(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=Ef(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",vs(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as $f,map as Mf,observeElementSize as Rf,Subscription as Lf,ValueSubject as No,noop as Df}from"@vkontakte/videoplayer-shared/evergreen";var tn=class{constructor(){this.subscription=new Lf;this.pipSize$=new No(void 0);this.videoSize$=new No(void 0);this.elementSize$=new No(void 0);this.pictureInPictureWindowRemoveEventListener=Df}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Rf(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($f({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Mf(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new Uf;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Cf(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new en({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;_f(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Ld.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(Fo(d=>!!d.length),Bd()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Is(d=>d.to.state!=="none"),Ts());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Fo(Dd),Bd()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Is(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Vf(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(To(b));let g=[];for(let S of b.representations){let y=ns(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(Io(f));let b=[];for(let g of f.representations){let S=Nt({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=cd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=Es(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$,Ff(this.video,"progress")).pipe(Fo(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(Hf(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);Dd(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(Of({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Es(rn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Is(d=>d.to)))}).pipe(Is(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Ts()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ts()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Io(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ts()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(To(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Is(({to:d})=>d==="ready"),Ts());this.subscription.add(Es(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,rn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Es(c,this.player.state$.stateChangeEnded$,rn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Es(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rn(["init"])).pipe(Nf(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?Qe:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:E})=>E===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:E})=>E===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:E})=>E===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ld.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var ws=class extends di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as _o,merge as Cd,filter as Vd,filterChanged as Od,isNullable as Uo,map as Nd,ValueSubject as Ho,isNonNullable as jf}from"@vkontakte/videoplayer-shared/evergreen";var ks=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new Ho(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Od()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Nd(o=>o.to)).subscribe(this.player.isLowLatency$)).add(_o({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Nd(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(_o({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Cd(r.playbackRateState$,new Ho(1))}).pipe(Vd(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||Uo(h)||(t=o-h)})).add(_o({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Cd(r.playbackRateState$,new Ho(1))}).pipe(Od((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||Uo(o)||Uo(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=dd(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Vd(o=>jf(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as gb,assertNonNullable as Sb,combine as vb,debounce as yb,ErrorCategory as Zd,filter as iu,filterChanged as Cs,fromEvent as Tb,isNonNullable as el,isNullable as Ib,map as Vs,merge as Os,observableFrom as hn,once as tl,Subscription as Eb}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Xo,assertNonNullable as sr,combine as ar,ErrorCategory as tt,filter as cn,filterChanged as Ls,flattenObject as Ds,fromEvent as ut,getTraceSubscriptionMethod as nb,interval as Jo,isNonNullable as Bs,isNullable as Xd,map as nr,merge as mi,now as Zo,Subject as It,Subscription as eu,SubscriptionRemovable as ob,tap as ub,throttle as Jd,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Qf,ErrorCategory as Fd,Subject as _d}from"@vkontakte/videoplayer-shared/evergreen";var zf=18,Ud=!1;try{Ud=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=zf}catch(u){console.error(u)}var jo=class{constructor(e,t=!1){this.bufferFull$=new _d;this.error$=new _d;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:Fd.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)};Ud&&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:Fd.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:Qf(t)}}},Hd=jo;import{abortable as Qt,assertNonNullable as Le,ErrorCategory as hi,fromEvent as Wo,getExponentialDelay as Go,isHigher as Kf,isNonNullable as zt,isNullable as oe,now as nn,once as Xf,Subject as Jf,Subscription as Zf,ValueSubject as pi}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as qf,throttleFn as Wf}from"@vkontakte/videoplayer-shared/evergreen";var xs=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??qf({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},jd=({id:u,bitrate:e})=>({id:u,bitrate:e}),Qd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),zd=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Qo=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),zo=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),qo=u=>"url"in u,Fe=u=>u.type==="template";var qd=u=>{u.sort((t,i)=>t.from-i.from);let e=[u[0]];for(let t=1;t<u.length;t++){let{from:i,to:r}=u[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(u[t])}return e},li=(u,e)=>{for(let t of u)if(e(t))return t;return null},Wd=u=>{let e=!1,t=Wf(()=>{e=!0},u);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Gf,Subscription as Yf}from"@vkontakte/videoplayer-shared/evergreen";var sn=u=>{let e=[];for(let t=0;t<u.length;t++){let i=Math.floor(u.start(t)*1e3),r=Math.ceil(u.end(t)*1e3);e.push(i,r)}return e};var an=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Yf;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Gf(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=sn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],n=t[i+1];if(a>r||n<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ps=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new pi(0);this.currentLowLatencySegmentLength$=new pi(0);this.currentSegmentLength$=new pi(0);this.onLastSegment$=new pi(!1);this.fullyBuffered$=new pi(!1);this.playingRepresentation$=new pi(void 0);this.playingRepresentationInit$=new pi(void 0);this.error$=new Jf;this.gaps=[];this.subscription=new Zf;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Qt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hd(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new an(this.mediaSource,this.sourceBuffer),this.subscription.add(Wo(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Wo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:hi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=ae(this.sourceBuffer.buffered,n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();zt(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=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();zt(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=Qt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Fe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Le(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Le(s,"No segments for starting representation");let a=this.initData.get(i);if(Le(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Qt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Le(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(oe(n)||oe(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Le(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!B(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();zt(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!oe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(oe(e)||oe(this.downloadingRepresentationId)||oe(this.playingRepresentationId)||oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||zt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),oe(r)||oe(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);zt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=xs(i),m=xs(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&zt(p)&&zt(m)&&Kf(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ae(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h?.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&ae(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ae(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;zt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Fe(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Fe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Fe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Qt(n,async function*(){let h=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=nn(),!h)return;let d=new DataView(h),l=ze(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Fe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Qt(a,async function*(){let o=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Wo(window,"online").pipe(Xf()).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=nn(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Fe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=nn(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Fe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=nn();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=ze(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:c}=o,h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(p){if(c.status==="downloading"&&m){c.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),b=o.loadedBytes===l?f:ze(n.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(c.status="partially_fed",o.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(o.fedBytes+=b.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:hi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",qo(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,async function*(){let n=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ze(e.mime),r)).then(n=>{if(!n)return;let{init:o,dataView:c,segments:h}=n,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let l=h;this.isLive&&Fe(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:hi.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||oe(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=n=>{if(s>=t)return;r.push({...n.time});let o=qo(n)?n.size??0:n.byte.to-n.byte.from;s+=o};for(let n of this.segments.values())for(let o of n){let c=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||h)&&o.status==="fed"&&a(o)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let o=this.sourceBuffer.buffered.start(n)*1e3,c=this.sourceBuffer.buffered.end(n)*1e3,h=0;for(let d of this.segments.values())for(let l of d)["none","partially_ejected"].includes(l.status)&&Math.round(l.time.from)<=Math.round(o)&&Math.round(l.time.to)>=Math.round(c)&&h++;if(h===this.segments.size){let d={time:{from:o,to:c},url:"",status:"none"};a(d)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let c of o)c.time.from>=e+n&&c.status==="fed"&&a(c)}return r.length?(r=qd(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,c)=>o||c,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||oe(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,n=i.end(s)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){r=void 0;break}n>t.time.from&&n<t.time.to&&(r.from=n),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),a=Math.round(r.to);for(let n=0;n<i.length;n++)if(s>=Math.round(i.start(n)*1e3)&&a<=Math.round(i.end(n)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:hi.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||oe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=sn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=!1,c=0;for(let h=0;h<e.length;h+=2){let d=e[h],l=e[h+1];o||(o=d-t<=a&&l+t>=n),(a>=d&&a<l-t||n>d+t&&n<=l)&&(c+=1)}o||(c===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:hi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as As,assertNever as Gd,fromEvent as Yd,merge as eb,now as $s,Subject as ir,ValueSubject as Yo,flattenObject as rr,ErrorCategory as Ms,SubscriptionRemovable as tb}from"@vkontakte/videoplayer-shared/evergreen";var un=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new ir;this.firstBytesManifest$=new ir;this.firstBytesRequested$=new ir;this.firstBytesReceived$=new ir;this.lastConnectionType$=new Yo(void 0);this.lastConnectionReused$=new Yo(void 0);this.lastRequestFirstBytes$=new Yo(void 0);this.recoverableError$=new ir;this.error$=new ir;this.abortAllController=new AbortController;this.subscription=new tb;this.fetchManifest=As(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(on);return r?(t.log("success",rr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=As(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:Gd(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=eb(Yd(this.abortAllController.signal,"abort"),Yd(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){on(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){on(T)}p=I.signal}let f=0,b=$s();l.log("startRequest",rr({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested$.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=$s();if(!g)return l.error("error",{message:"No response in request"}),l.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){this.unsubscribeAbortSubscription(m);let I=$s(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",rr(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),w,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(w=P),!w&&i&&(w=i.to-i.from+1);let A=w?new Uint8Array(w):new Uint8Array(0),E=!1,L=I=>{this.unsubscribeAbortSubscription(m),E=!0,on(I)},k=As(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next($s()-b),this.firstBytesReceived$.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&T){if(c&&w)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),this.unsubscribeAbortSubscription(m);let N=$s(),D={failed:E,requestStartedAt:b,requestEndedAt:N,duration:N-b};return E?(l.error("endRequest",rr(D)),l.end(),null):(l.log("endRequest",rr(D)),l.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=As(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=As(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Gd(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ms.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ms.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ms.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ms.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ms.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},on=u=>{if(!Ie(u))throw u};import{isNullable as ib,ValueSubject as rb}from"@vkontakte/videoplayer-shared/evergreen";var Rs=class u{constructor(e,t){this.currentRepresentation$=new rb(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(!ib(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Fe(t.segmentReference))}};var cb=["progress","play","seeked","stalled","waiting"],db=["timeupdate","progress","loadeddata","playing","seeked"];var dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new eu;this.subscriptionRemovable=new ob;this.representationSubscription=new eu;this.state$=new V("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new It;this.manifestRequested$=new It;this.firstBytesManifest$=new It;this.manifestReceived$=new It;this.firstBytesRequested$=new It;this.firstBytesReceived$=new It;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new It;this.fetcherError$=new It;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new It;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Xo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:tt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xo(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:tt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Bi(e)??{id:"ManifestParsing",category:tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Ds(n)),n}.bind(this));this.initRepresentations=Xo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ds({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new eu,this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(ut(l,"error").pipe(cn(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Ps("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Bs(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Ps("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...db.map(l=>ut(this.element,l))).pipe(nr(l=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Ls(),ub(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(ut(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ls()).subscribe(p=>this.liveStreamEndTimestamp=Zo())),this.subscription.add(ut(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Jo(1e3).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ut(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ar({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(nr(({isActiveLive:p,isLowLatency:m})=>p&&m),Ls()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(ar({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(cn(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(ar({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(cn(({isLive:p})=>p),Ls((p,m)=>m.bufferLength<p.bufferLength),nr(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=$t(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ar({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(y)>g&&(v=1+Math.sign(y)*S),Ji(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add(ar({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Jd(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=$t(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let E="none";if(P?E="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),E="active_low_latency"):b!==0&&w<S?E="live_forward_buffering":w<S+v&&(E="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),E==="live_forward_buffering"||E==="live_with_target_offset"){let L=l-(S+y),k=this.normolizeLiveOffset(Math.trunc(b+L/f)),N=Math.abs(k-b),D=0;!p||N<=this.tuning.dashCmafLive.offsetCalculationError?D=b:k>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(D=k),this.manifestUrlString=te(this.manifestUrlString,D,2)}(E==="live_with_target_offset"||E==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:tt.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let c=mi(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(nr(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),h=mi(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(nr(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=ar({allBuffersFull:c,someBufferEnded:h}).pipe(Ls(),nr(({allBuffersFull:l,someBufferEnded:p})=>l&&p),cn(l=>l));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(mi(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Fe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Bs(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=Jo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:tt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new un({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Zo()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){sr(this.element),this.state$.setState("running");let e=ut(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Jd(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(mi(...cb.map(t=>ut(this.element,t)),ut(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:tt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ut(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ut(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Zo(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,c=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=c<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,l=this.audioBufferManager&&h<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||l)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:tt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Ds(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Jo(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:tt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Xd(this.element)||Xd(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ds({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Bs(this.element)&&Bs(this.source)&&Bs(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=nb(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,n=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a=1/0:(a===null||c.to>a)&&(a=c.to));if(a!==null){let o=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Ds({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as lb,map as hb,observeElementSize as pb,Subscription as mb,ValueSubject as tu,noop as fb}from"@vkontakte/videoplayer-shared/evergreen";var ln=class{constructor(){this.subscription=new mb;this.pipSize$=new tu(void 0);this.videoSize$=new tu(void 0);this.elementSize$=new tu(void 0);this.pictureInPictureWindowRemoveEventListener=fb}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(pb(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(lb({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(hb(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var fi=class{constructor(e){this.subscription=new Eb;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new ln;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return gb(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new dn({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;Ib(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Zd.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(iu(d=>!!d.length),tl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Vs(d=>d.to.state!=="none"),Cs());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(iu(el),tl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Vs(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Sb(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(Qo(b));let g=[];for(let S of b.representations){let y=jd(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(zo(f));let b=[];for(let g of f.representations){let S=xs({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=Qd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:n}=this.params.tuning.dash,o=n&&Wd(n)||null;this.subscription.add(Os(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$,Tb(this.video,"progress")).pipe(iu(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l||d==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=li(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);el(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(vb({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Os(hn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Vs(d=>d.to)))}).pipe(Vs(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Cs()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Cs()).subscribe(d=>{let l=li(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(zo(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Cs()).subscribe(d=>{let l=li(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Qo(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Vs(({to:d})=>d==="ready"),Cs());this.subscription.add(Os(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,hn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Os(c,this.player.state$.stateChangeEnded$,hn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Os(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hn(["init"])).pipe(yb(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?Qe:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=li(this.videoTracksMap.keys(),E=>E.id===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=li(this.videoStreamsMap.keys(),E=>E.id===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=g?.id&&li(this.audioStreamsMap.keys(),E=>E.id===g.id)||this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let E=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}if(c){let E=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,E?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=w&&this.audioTracksMap.get(w)?.representation;P&&A?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=A):P&&!A&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zd.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var Ns=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ru,merge as il,filter as rl,filterChanged as sl,isNullable as su,map as al,ValueSubject as au,isNonNullable as wb}from"@vkontakte/videoplayer-shared/evergreen";var Fs=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new au(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(sl()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(al(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ru({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(al(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o+c:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(rl(o=>wb(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(ru({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:il(r.playbackRateState$,new au(1))}).pipe(rl(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||su(h)||(t=o-h)})).add(ru({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:il(r.playbackRateState$,new au(1))}).pipe(sl((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||su(o)||su(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=zd(o);this.params.output.availableTextTracks$.next([c])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var nl="X-Playback-Duration",nu=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(nl)?parseInt(e.headers.get(nl),10):void 0};import{assertNever as Cb,combine as Vb,debounce as Ob,ErrorCategory as fn,filter as Nb,filterChanged as Fb,isNonNullable as cl,isNullable as bn,map as dl,merge as _b,observableFrom as Ub,Subscription as Hb,ValueSubject as uu,VideoQuality as jb}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as kb,getExponentialDelay as xb}from"@vkontakte/videoplayer-shared/evergreen";var Pb=u=>{let e=null;if(u.QUALITY&&(e=nt(u.QUALITY)),!e&&u.RESOLUTION){let[t,i]=u.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kb({width:t,height:i})}return e??null},Ab=(u,e)=>{let t=u.split(`
|
|
177
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(h,"i")}var Zc=u=>{if(!u?.startsWith("P"))return;let e=(a,n)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(u),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Oe=(u,e)=>{let t=u;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,o)=>Jc(s)?n:Jc(o)?s:s.padStart(parseInt(o,10),"0"))}return t},_i=(u,e)=>{let i=new DOMParser().parseFromString(u,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(L=>L.textContent?.trim()??""),n=a.at(0)??"",o=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],l=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:c?new Date(c).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:l?new Date(l).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],v=y.reduce((L,k)=>({...L,[k.id]:k.children}),{}),E=y.reduce((L,k)=>({...L,[k.id]:k.getAttribute("duration")}),{});S?g=Zc(S):Object.values(E).filter(L=>L).length&&!o?g=Object.values(E).reduce((L,k)=>L+(Zc(k)??0),0):f&&(g=parseInt(f,10));let P=0,A=s.getAttribute("profiles")?.split(",")??[];for(let L of y.map(k=>k.id))for(let k of v[L]){let N=k.getAttribute("id")??"id"+(P++).toString(10),D=k.getAttribute("mimeType")??"",I=k.getAttribute("codecs")??"",T=k.getAttribute("contentType")??D?.split("/")[0],O=k.getAttribute("profiles")?.split(",")??[],R=Xc(k.getAttribute("lang")??"")??{},U=k.querySelector("Label")?.textContent?.trim()??void 0,G=k.querySelectorAll("Representation"),ee=k.querySelector("SegmentTemplate"),re=k.querySelector("Role")?.getAttribute("value")??void 0,pe=T,me={id:N,language:R.language,isDefault:re==="main",label:U,codecs:I,hdr:pe==="video"&&So(I),mime:D,representations:[]};for(let H of G){let _=H.getAttribute("lang")??void 0,fe=U??k.getAttribute("label")??H.getAttribute("label")??void 0,Ee=H.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(Ee||n,e).toString(),Ue=H.getAttribute("mimeType")??D,kt=H.getAttribute("codecs")??I??"",We;if(T==="text"){let Ve=H.getAttribute("id")||"",xt=R.privateuse?.includes("x-auto")||Ve.includes("_auto"),Ge=H.querySelector("SegmentTemplate");if(Ge){let cr={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=parseInt(Ge.getAttribute("startNumber")??"",10)??1,bi=parseInt(Ge.getAttribute("timescale")??"",10),xn=Ge.querySelectorAll("SegmentTimeline S")??[],gi=Ge.getAttribute("media");if(!gi)continue;let Ys=[],Ks=0,Xs="",Si=0,dr=Gs,ke=0;for(let Ye of xn){let Gt=parseInt(Ye.getAttribute("d")??"",10),He=parseInt(Ye.getAttribute("r")??"",10)||0,Pt=parseInt(Ye.getAttribute("t")??"",10);ke=Number.isFinite(Pt)?Pt:ke;let Yt=Gt/bi*1e3,vi=ke/bi*1e3;for(let it=0;it<He+1;it++){let At=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:(ke+it*Gt).toString(10)}),yi=(vi??0)+it*Yt,hr=yi+Yt;dr++,Ys.push({time:{from:yi,to:hr},url:At})}ke+=(He+1)*Gt,Ks+=(He+1)*Yt}Si=ke/bi*1e3,Xs=Oe(gi,{...cr,segmentNumber:dr.toString(10),segmentTime:ke.toString(10)});let lr={time:{from:Si,to:1/0},url:Xs},ct={type:"template",baseUrl:ce,segmentTemplateUrl:gi,initUrl:"",totalSegmentsDurationMs:Ks,segments:Ys,nextSegmentBeyondManifest:lr,timescale:bi};We={id:Ve,kind:"text",segmentReference:ct,profiles:[],duration:g,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:xt}}else We={id:Ve,isAuto:xt,kind:"text",url:ce}}else{let Ve=H.getAttribute("contentType")??Ue?.split("/")[0]??T,xt=k.getAttribute("profiles")?.split(",")??[],Ge=parseInt(H.getAttribute("width")??"",10),cr=parseInt(H.getAttribute("height")??"",10),Ws=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Gs=H.getAttribute("frameRate")??"",bi=H.getAttribute("quality")??void 0,xn=Gs?Kc(Gs):void 0,gi=H.getAttribute("id")??"id"+(P++).toString(10),Ys=Ve==="video"?`${cr}p`:Ve==="audio"?`${Ws}Kbps`:kt,Ks=`${gi}@${Ys}`,Xs=[...A,...O,...xt],Si,dr=H.querySelector("SegmentBase"),ke=H.querySelector("SegmentTemplate")??ee;if(dr){let ct=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,Gt]=ct.split("-").map(At=>parseInt(At,10)),He={from:Ye,to:Gt},Pt=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Yt,vi]=Pt?Pt.split("-").map(At=>parseInt(At,10)):[],it=Pt?{from:Yt,to:vi}:void 0;Si={type:"byteRange",url:ce,initRange:He,indexRange:it}}else if(ke){let ct={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ye=parseInt(ke.getAttribute("timescale")??"",10),Gt=ke.getAttribute("initialization")??"",He=ke.getAttribute("media"),Pt=parseInt(ke.getAttribute("startNumber")??"",10)??1,Yt=Oe(Gt,ct);if(!He)throw new ReferenceError("No media attribute in SegmentTemplate");let vi=ke.querySelectorAll("SegmentTimeline S")??[],it=[],At=0,yi="",hr=0;if(vi.length){let Js=Pt,Ke=0;for(let Ti of vi){let rt=parseInt(Ti.getAttribute("d")??"",10),Kt=parseInt(Ti.getAttribute("r")??"",10)||0,Zs=parseInt(Ti.getAttribute("t")??"",10);Ke=Number.isFinite(Zs)?Zs:Ke;let Pn=rt/Ye*1e3,Yl=Ke/Ye*1e3;for(let ea=0;ea<Kt+1;ea++){let Kl=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:(Ke+ea*rt).toString(10)}),Iu=(Yl??0)+ea*Pn,Xl=Iu+Pn;Js++,it.push({time:{from:Iu,to:Xl},url:Kl})}Ke+=(Kt+1)*rt,At+=(Kt+1)*Pn}hr=Ke/Ye*1e3,yi=Oe(He,{...ct,segmentNumber:Js.toString(10),segmentTime:Ke.toString(10)})}else if(um(g)){let Ke=parseInt(ke.getAttribute("duration")??"",10)/Ye*1e3,Ti=Math.ceil(g/Ke),rt=0;for(let Kt=1;Kt<Ti;Kt++){let Zs=Oe(He,{...ct,segmentNumber:Kt.toString(10),segmentTime:rt.toString(10)});it.push({time:{from:rt,to:rt+Ke},url:Zs}),rt+=Ke}hr=rt,yi=Oe(He,{...ct,segmentNumber:Ti.toString(10),segmentTime:rt.toString(10)})}let Gl={time:{from:hr,to:1/0},url:yi};Si={type:"template",baseUrl:ce,segmentTemplateUrl:He,initUrl:Yt,totalSegmentsDurationMs:At,segments:it,nextSegmentBeyondManifest:Gl,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ve||!Ue)continue;let lr={video:"video",audio:"audio",text:"text"}[Ve];if(!lr)continue;pe||=lr,We={id:Ks,kind:lr,segmentReference:Si,profiles:Xs,duration:g,bitrate:Ws,mime:Ue,codecs:kt,width:Ge,height:cr,fps:xn,quality:bi}}me.language||=_,me.label||=fe,me.mime||=Ue,me.codecs||=kt,me.hdr||=pe==="video"&&So(kt),me.representations.push(We)}if(pe){let H=r[pe].find(_=>_.id===me.id);if(H&&me.representations.every(_=>_.segmentReference.type==="template"))for(let _ of H.representations){let fe=me.representations.find(Ue=>Ue.id===_.id);if(!fe)continue;let Ee=fe.segmentReference,ce=_.segmentReference;ce.segments.push(...Ee.segments),ce.nextSegmentBeyondManifest=Ee.nextSegmentBeyondManifest}else r[pe].push(me)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{assertNever as Fa}from"@vkontakte/videoplayer-shared/evergreen";var Na=u=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(u){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Fa(u)}},ed=({webmCodec:u,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Na(u),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Na(u),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Na(u),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Na(u),...s,"HLS","HLS_ONDEMAND"];default:Fa(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Fa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},td=({androidPreferredFormat:u,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,o=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(u){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:Fa(u)}else $.video.nativeHlsSupported&&!o&&!$.browser.isChromiumBased?n=a:o?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},vo=u=>u?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ui=u=>{if(u.size===0)return;if(u.size===1)return u.values().next().value.split(".").at(0);for(let t of u){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return u.values().next().value.split(".").at(0)},Hi=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return hm().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},ji=u=>{let e=u.map(i=>Vt(i)),{codecs:t}=$.video;return pm().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Vt=u=>u.split(".")[0].replace("0",""),hm=()=>["av1","vp9","hev1","avc1"],pm=()=>["opus","mp4a"];import{abortable as Eo,assertNonNullable as ot,ErrorCategory as Bm,fromEvent as Cm,getExponentialDelay as Vm,isHigher as Om,isNonNullable as ie,isNullable as le,once as Nm,Subject as Fm,Subscription as _m,ValueSubject as os}from"@vkontakte/videoplayer-shared/evergreen";var _a=u=>u.valid,z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var zi=class extends z{};import{assertNever as mm}from"@vkontakte/videoplayer-shared/evergreen";var Vr=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:mm(e)}}};var Or=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Nr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends z{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Fr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var _r=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ur=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var si=class extends Y{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,n=this.readUint32();r=this.readUint32();let o=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}};var Hr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends Y{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var qr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Wr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends Y{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Yr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends Y{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var es=class extends Y{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ts=class extends Y{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var is=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var ss=class extends z{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var bm={ftyp:Or,moov:Nr,mvhd:Fr,moof:_r,mdat:Ur,sidx:si,trak:Hr,mdia:Wr,mfhd:Xr,tkhd:Gr,traf:Jr,tfhd:Zr,tfdt:es,trun:ts,minf:Yr,sv3d:jr,st3d:zr,prhd:Qr,proj:Kr,equi:qr,uuid:Vr,stbl:is,stsd:rs,avc1:ss,unknown:zi},ft=class u{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(n){if(!(n instanceof RangeError))throw n}if(!a||!_a(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=bm[e];return i?new i(t,new u):new zi(t,new u)}};var Ot=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{_a(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 Sm=new TextDecoder("ascii"),vm=u=>Sm.decode(new DataView(u.buffer,u.byteOffset+4,4))==="ftyp",ym=u=>{let e=new si(u,new ft),t=e.earliestPresentationTime/e.timescale*1e3,i=u.byteOffset+u.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},Tm=(u,e)=>{let i=new ft().parse(u),r=new Ot(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],o=a[a.length-1],c=n.source.byteOffset,d=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(u.buffer,c,d)},Im=u=>{let t=new ft().parse(u),i=new Ot(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},wm=u=>{let t=new ft().parse(u);return new Ot(t).find("sidx")?.timescale},Em=(u,e)=>{let i=new ft().parse(u),s=new Ot(i).findAll("traf"),a=s[s.length-1].children.find(d=>d.type==="tfhd"),n=s[s.length-1].children.find(d=>d.type==="tfdt"),o=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return o.sampleDuration.length?c=o.sampleDuration.reduce((d,l)=>d+l,0):c=a.defaultSampleDuration*o.sampleCount,(Number(n.baseMediaDecodeTime)+c)/e*1e3},km=u=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ft().parse(u),r=new Ot(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},id={validateData:vm,parseInit:km,getIndexRange:()=>{},parseSegments:ym,parseFeedableSegmentChunk:Tm,getChunkEndTime:Em,getServerLatencyTimestamps:Im,getTimescaleFromIndex:wm};import{assertNonNullable as yo,isNonNullable as nd,isNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as xm}from"@vkontakte/videoplayer-shared/evergreen";var rd={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"}},sd=u=>{let e=u.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=as(u,t),r=i in rd,s=r?rd[i].type:"binary",a=u.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let o=new DataView(u.buffer,u.byteOffset+t+1,n-1),c=a&255>>n,h=as(o),d=c*2**((n-1)*8)+h,l=t+n,p;return l+d>u.byteLength?p=new DataView(u.buffer,u.byteOffset+l):p=new DataView(u.buffer,u.byteOffset+l,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:l,tagSize:l+d,value:p,valueSize:d}},as=(u,e=u.byteLength)=>{switch(e){case 1:return u.getUint8(0);case 2:return u.getUint16(0);case 3:return u.getUint8(0)*2**16+u.getUint16(1);case 4:return u.getUint32(0);case 5:return u.getUint8(0)*2**32+u.getUint32(1);case 6:return u.getUint16(0)*2**32+u.getUint32(2);case 7:{let t=u.getUint8(0)*281474976710656+u.getUint16(1)*4294967296+u.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(u,e)=>{switch(e){case"int":return u.getInt8(0);case"uint":return as(u);case"float":return u.byteLength===4?u.getFloat32(0):u.getFloat64(0);case"string":return new TextDecoder("ascii").decode(u);case"utf8":return new TextDecoder("utf-8").decode(u);case"date":return new Date(Date.UTC(2001,0)+u.getInt8(0)).getTime();case"master":return u;case"binary":return u;default:xm(e)}},ai=(u,e)=>{let t=0;for(;t<u.byteLength;){let i=new DataView(u.buffer,u.byteOffset+t),r=sd(i);if(!e(r))return;r.type==="master"&&ai(r.value,e),t=r.value.byteOffset-u.byteOffset+r.valueSize}},ad=u=>{if(u.getUint32(0)!==440786851)return!1;let e,t,i,r=sd(u);return ai(r.value,({tag:s,type:a,value:n})=>(s===17143?e=et(n,a):s===17026?t=et(n,a):s===17029&&(i=et(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var od=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Am=[231,22612,22743,167,171,163,160,175],$m=u=>{let e,t,i,r,s=!1,a=!1,n=!1,o,c,h=!1,d=0;return ai(u,({tag:l,type:p,value:m,valueSize:f})=>{if(l===21419){let b=et(m,p);c=as(b)}else l!==21420&&(c=void 0);return l===408125543?(e=m.byteOffset,t=m.byteOffset+f):l===357149030?s=!0:l===290298740?a=!0:l===2807729?i=et(m,p):l===17545?r=et(m,p):l===21420&&c===475249515?o=et(m,p):l===374648427?ai(m,({tag:b,type:g,value:S})=>b===30321?(h=et(S,g)===1,!1):!0):s&&a&&od.includes(l)&&(n=!0),!n}),yo(e,"Failed to parse webm Segment start"),yo(t,"Failed to parse webm Segment end"),yo(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:h,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Mm=u=>{if(Pm(u.cuesSeekPosition))return;let e=u.segmentStart+u.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Rm=(u,e)=>{let t=!1,i=!1,r=n=>nd(n.time)&&nd(n.position),s=[],a;return ai(u,({tag:n,type:o,value:c})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=et(c,o));break;case 183:break;case 241:a&&(a.position=et(c,o));break;default:t&&od.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,o)=>{let{time:c,position:h}=n,d=s[o+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Lm=u=>{let e=0,t=!1;try{ai(u,i=>i.tag===524531317?i.tagSize<=u.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Am.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},ud={validateData:ad,parseInit:$m,getIndexRange:Mm,parseSegments:Rm,parseFeedableSegmentChunk:Lm};var Qe=u=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(u);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ud;case"mp4":return id}}throw new ReferenceError(`Unsupported mime type ${u}`)};import{videoSizeToQuality as Dm}from"@vkontakte/videoplayer-shared/evergreen";var Nt=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??Dm({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},ns=({id:u,bitrate:e})=>({id:u,bitrate:e}),cd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),dd=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),To=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Io=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),wo=u=>"url"in u,Ne=u=>u.type==="template";var Qi=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,manifest:n}){this.error$=new Fm;this.playingRepresentation$=new os(void 0);this.playingRepresentationInit$=new os(void 0);this.currentSegmentLength$=new os(0);this.onLastSegment$=new os(!1);this.fullyBuffered$=new os(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new AbortController;this.downloadAbortController=new AbortController;this.subscription=new _m;this.startWith=Eo(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Qe(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Eo(this.destroyAbortController.signal,async function*(e,t=!0){if(le(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);ot(r,`No such representation ${e}`),ot(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),a=this.segments.get(r.id);ot(s,"No init buffer for switching representation"),ot(a,"No segments for switching representation");let n=this.getCurrentPosition()??0,o=d=>d.segment.networkStatus!=="downloaded"||d.segment.time.to-n>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=d=>{let l=this.representations.get(d.representationId);return ot(l,"No itemRepresentation for previous track before switch"),d.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(l,r)},h=d=>t?o(d)&&c(d):o(d);this.bufferPlaybackQueue.filter(h).forEach(d=>d.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(d=>!h(d)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(n),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Eo(this.downloadAbortController.signal,async function*(){let e=Vm(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),this.subscription.add(Cm(window,"online").pipe(Nm()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=a,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=n?.baseUrls??[],this.representations=new Map(i.map(o=>[o.id,o]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){le(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return ie(t)&&ie(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from}getRepresentationInitialTime(){return le(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(le(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){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(),window.cancelIdleCallback)for(let e of this.idleCallbacks.values())window.cancelIdleCallback(e);this.idleCallbacks.clear(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Nt(e),s=Nt(t);i=ie(r)&&ie(s)&&Om(s.quality,r.quality)}else if(this.kind==="audio"){let r=ns(e),s=ns(t);i=ie(r?.bitrate)&&ie(s?.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,requestIdleCallback(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():ie(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,s);let{initMetadata:a,initDataView:n,segments:o}=await s??{};if(this.initDataPromises.delete(e.id),le(n)||le(o))return;a&&this.parsedInitData.set(e.id,a);let c=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,o),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:Bm.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(le(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(n=>this.withinInterval(e,n.segment.time)),i=this.bufferPlaybackQueue.find(n=>n.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),s=this.bufferPlaybackQueue[0],a=this.downloadAbortController.signal;ie(r)&&ie(i)&&ie(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),ie(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,a):await this.appendSegmentPartially(i,a)),ie(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,a),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){ot(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(le(t)||le(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(a=>e>=a.time.from&&e<a.time.to);ie(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(le(t)||t.length===0)return;let i=t[t?.length-1];le(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){ot(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;ie(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(n=>this.withinInterval(e,n.time))),r=r===-1?0:r;let a=[];for(;r<t.length&&s>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:n,to:o}=t[r].time;s-=o-n,r++}return a}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return ie(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return ie(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return ie(e)?e-i>t:!1}async appendSegmentFully(e,t){if(le(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(le(e.segment.data)||le(e.segment.loadedBytes)||le(e.segment.feedingBytes)||le(e.segment.fedBytes)||le(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||ie(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let a of this.segments.values())for(let n of a)ie(n.size)&&s>0&&n.time.to<=e-r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size);for(let a of this.segments.values())for(let n of[...a].reverse())ie(n.size)&&s>0&&n.time.from>=e+r&&n.bufferStatus==="none"&&n.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(o=>o.segment===n)&&!this.downloadingBufferItems.find(o=>o.segment===n)&&(n.data=null,n.networkStatus="none",this.currentVirtualBufferSize-=n.size,s-=n.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as Um,isNonNullable as Hm,isNullable as ld,now as hd}from"@vkontakte/videoplayer-shared/evergreen";var Ua=class extends Qi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...a,priority:i}),this.lastDataObtainedTimestampMs=hd(),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,a=0;for(;a<this.downloadingBufferItems.length&&this.downloadingBufferItems[a].segment.networkStatus==="none"&&(e<=r||t<=s);){let n=this.downloadingBufferItems[a].segment;n.networkStatus="downloading",n.size=1/0,n.loadedBytes=0,n.feedingBytes=0,n.fedBytes=0,i.push(this.downloadingBufferItems[a]),e+=n.byte.to+1-n.byte.from,t+=n.time.to+1-n.time.from,a++}return i}prepareFetchParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(n,o)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=hd(),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:Um.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||ld(n)||ld(r)||a.aborted))for(let o of e){let{segment:c}=o,h=c.byte.from-r,d=c.byte.to-r,l=d-h+1,p=h<s,m=d<=s;c.size=l,p&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+h,l),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o),c.loadedBytes=Math.min(l,s-h),await this.onDownloadItem(o)):Hm(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(l,s-h),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(o)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+h,c.loadedBytes),await this.onDownloadItem(o))))}}updateRepresentationBaseUrl(e,t){if(Me(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as jm,isNullable as ko,now as pd}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends Qi{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let n=await this.fetcher.fetch(s,{...a,priority:i});if(this.lastDataObtainedTimestampMs=pd(),ko(n))return;let o=e[0],c=new DataView(n);o.segment.size=c.byteLength,o.segment.loadedBytes=c.byteLength,o.segment.data=c,this.onItemFullyDownloaded(o),await this.onDownloadItem(o),this.failedDownloads=0}catch(n){this.abortDownloadingItems(),Ie(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(a,n)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=pd(),await this.onSomeDataLoaded({downloadingItems:e,dataView:a,loaded:n,signal:r,representationId:t.id})}catch(o){this.error$.next({id:"SegmentFeeding",category:jm.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:o})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Me(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let a=e[0],{segment:n}=a,o=this.representations.get(i);!this.downloadingBufferItems.length||ko(o)||ko(n.feedingBytes)||n.networkStatus!=="downloading"||s.aborted||(n.loadedBytes=r,n.loadedBytes>n.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(n.data=new DataView(t.buffer,t.byteOffset,n.loadedBytes),await this.onDownloadItem(a)))}updateRepresentationBaseUrl(e,t){if(!Me(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};import{assertNonNullable as zm,ErrorCategory as Qm,isNullable as bt,ValueSubject as md}from"@vkontakte/videoplayer-shared/evergreen";var Ha=class extends qi{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new md(0);this.currentLowLatencySegmentLength$=new md(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=t.streams[this.kind].flatMap(r=>r.representations);for(let r of i){if(bt(r)||!Me(r.segmentReference))return;let s=r.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),a=100,n=this.segments.get(r.id)??[],o=n.at(-1)?.time.to??0,c=s?.findIndex(h=>o>=h.time.from+a&&o<=h.time.to+a);if(c===-1){let h=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,h)}else{let h=s.slice(c+1);this.segments.set(r.id,[...n,...h])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;zm(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let r=t?.streams[this.kind]?.flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(bt(r))return;let s=this.segments.get(r.id);if(s?.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){if(bt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return bt(t)||!Me(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),bt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:a}=r.getServerLatencyTimestamps(i);s&&a&&this.currentLiveSegmentServerLatency$.next(a-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(bt(t.segment.data)||bt(r)||!Me(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:a}=r;t.segment.time.to=s.getChunkEndTime(i,a)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Me(s))return;let a=this.segments.get(r.id)??[],n=a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.from));if(n?.isCurrentLowLatency&&(n.time.to=t.segment.time.to,i=n.time.to-n.time.from,n.isCurrentLowLatency=!1),!!!a.find(c=>Math.floor(c.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let c=Math.round(t.segment.time.to*s.timescale/1e3).toString(10),h=Oe(s.segmentTemplateUrl,{segmentTime:c});a.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:h,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let s=this.tuning.dash.useFetchPriorityHints?i:"auto",a=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s);this.initDataPromises.set(t.id,a);let{initMetadata:n,initDataView:o,segments:c}=await a??{};if(this.initDataPromises.delete(t.id),bt(o)||bt(c))return;n&&this.parsedInitData.set(t.id,n);let h=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,h);let d=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(t.id,d),this.failedDownloads=0}catch(s){r&&this.error$.next({id:"LoadInits",category:Qm.WTF,message:"loadInit threw",thrown:s})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],a=0,n=i.length-1;do s.unshift(i[n]),a+=i[n].time.to-i[n].time.from,n--;while(a<r&&n>=0);return this.liveInitialAdditionalOffset=a-r,this.isActiveLowLatency()?[s[0]]:s}};var us=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new Ha(e,t,i,r):Me(i[0].segmentReference)?new qi(e,t,i,r):new Ua(e,t,i,r)}};import{ErrorCategory as Gm,fromEvent as Ym,isNullable as Wi,Subject as Km,Subscription as Xm}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as qm,ErrorCategory as fd,Subject as bd}from"@vkontakte/videoplayer-shared/evergreen";var Wm=18,gd=!1;try{gd=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=Wm}catch(u){console.error(u)}var xo=class{constructor(e,t=!1){this.bufferFull$=new bd;this.error$=new bd;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:fd.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)};gd&&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:fd.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:qm(t)}}},Sd=xo;var ae=(u,e)=>{let t=0;for(let i=0;i<u.length;i++){let r=u.start(i)*1e3,s=u.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var cs=class{constructor(e){this.error$=new Km;this.subscription=new Xm;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Sd(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(Ym(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gm.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(Wi(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!Wi(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Wi(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return Wi(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Wi(e)?0:ae(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Wi(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var sf=["timeupdate","progress","play","seeked","stalled","waiting"],Td=["timeupdate","progress","loadeddata","playing","seeked"],za=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new yd;this.subscriptionRemovable=new rf;this.representationSubscription=new yd;this.forceEnded$=new _t;this.destroyController=new AbortController;this.state$=new V("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new _t;this.manifestRequested=new _t;this.manifestReceived=new _t;this.firstBytesRequested=new _t;this.firstBytesReceived=new _t;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.currentBuffer$=new K({from:0,to:0});this.bufferLength$=new K(0);this.nativeBufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new _t;this.fetcherError$=new _t;this.initRepresentations=vd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ja({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),gt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=vd(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){ds(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ni.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Va({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ni.PARSER,message:"No playable video representations"})}initBuffer(){gt(this.element),this.state$.setState("running"),this.subscription.add(ls(...sf.map(t=>oi(this.element,t)),oi(window,"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:ni.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(ls(...e.map(t=>oi(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(oi(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=ef(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:ni.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){gt(this.element),gt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",ja({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ft(this.element)&&Ft(this.source)&&Ft(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Ft(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(ds(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){gt(this.element),gt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",ja(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=tf(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,c=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,h=Ft(this.videoBufferManager)&&o<s&&r-a>i,d=Ft(this.audioBufferManager)&&c<s&&r-n>i;return(h||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(ds(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",ja(i)),i}parseManifest(e){try{return _i(e??"",this.manifestUrlString)}catch(t){let i=Bi(e)??{id:"ManifestParsing",category:ni.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text"),r,s;for(let n of["video","audio"]){let c=e.streams[n].filter(({mime:d,codecs:l})=>i(n,d,l));t[n]=c;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:l})=>l);n==="audio"&&(s=ji(d),h=s[0]),n==="video"&&(r=Hi(d),this.forceVideoCodec&&r.includes(this.forceVideoCodec)?h=this.forceVideoCodec:h=r[0]),h&&(t[n]=c.filter(({codecs:l})=>Vt(l)===h))}else{let d=new Set(c.map(({codecs:l})=>l));h=Ui(d),h&&(t[n]=c.filter(({codecs:l})=>l.startsWith(h)))}if(n==="video"){let d=this.tuning.preferHDR,l=t.video.some(m=>m.hdr),p=t.video.some(m=>!m.hdr);$.display.isHDR&&d&&l?t.video=t.video.filter(m=>m.hdr):p&&(t.video=t.video.filter(m=>!m.hdr))}}let a={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(a.codecs={video:r,audio:s}),a}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){gt(this.manifest),gt(this.element);let s=o=>{this.representationSubscription.add(oi(o,"error").pipe(Po(c=>!!this.element?.played.length)).subscribe(c=>{this.error$.next({id:"VideoSource",category:ni.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:c})}))};this.source=Ii();let a=document.createElement("source");if(s(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Mt())if(r){let o=document.createElement("source");s(o),o.type="application/x-mpegurl",o.src=r.url,this.element.appendChild(o)}else this.element.disableRemotePlayback=!0;let n=this.manifest.streams.video.reduce((o,c)=>[...o,...c.representations],[]);if(this.videoNativeBufferManager=new cs(this.source),this.videoBufferManager=us.getBufferManager("video",this.videoNativeBufferManager,n,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],Ft(i)){this.audioNativeBufferManager=new cs(this.source);let o=this.manifest.streams.audio.reduce((c,h)=>[...c,...h.representations],[]);this.audioBufferManager=us.getBufferManager("audio",this.audioNativeBufferManager,o,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=setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:ni.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&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(ls(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),gt(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(ls(...Td.map(e=>oi(this.element,e))).pipe(Ao(e=>this.videoBufferManager?.getPlaybackBufferState()),Po(Ft),Ao(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(ls(...Td.map(e=>oi(this.element,e))).pipe(Ao(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),Jm()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Po(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=Zm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(ds(this.element)||ds(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as Qa,combine as af,ErrorCategory as nf,filter as $o,filterChanged as of,fromEvent as uf,isNonNullable as cf,map as Mo,merge as hs}from"@vkontakte/videoplayer-shared/evergreen";var qa=class extends za{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){Qa(this.manifest),Qa(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(t=>t.representations).flatMap(t=>{let i=[];return t.duration&&i.push(t.duration),Me(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){Qa(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Qa(this.element);let e=hs(uf(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe($o(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(hs(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=hs(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Mo(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=hs(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Mo(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=af({allBuffersFull:e,someBufferEnded:t}).pipe(of(),Mo(({allBuffersFull:s,someBufferEnded:a})=>s&&a),$o(s=>s)),r=()=>{try{this.source?.endOfStream()}catch(s){this.error$.next({id:"EndOfStream",category:nf.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:s})}};this.representationSubscription.add(hs(this.forceEnded$,i).pipe($o(s=>cf(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(a=>!a.updating))).subscribe(r))}};var Gi=class extends Rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(df()).subscribe(s=>{let a=[...this.videoTracksMap.entries()].find(([,{representation:d}])=>d.id===s);if(!a){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[n,{stream:o}]=a,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===o.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(n),e.currentVideoStream$.next($a(o));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r))}getPlayer(){return new qa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as Cf,assertNonNullable as Vf,combine as Of,debounce as Nf,ErrorCategory as Ld,filter as Fo,filterChanged as Ts,fromEvent as Ff,isNonNullable as Dd,isNullable as _f,map as Is,merge as ws,observableFrom as rn,once as Bd,Subscription as Uf,throttle as Hf}from"@vkontakte/videoplayer-shared/evergreen";var we=(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 Co,assertNonNullable as Zi,combine as er,ErrorCategory as qe,filter as Za,filterChanged as Ss,flattenObject as vs,fromEvent as yt,getTraceSubscriptionMethod as wf,interval as Vo,isNonNullable as ys,isNullable as $d,map as tr,merge as ci,now as Oo,Subject as Tt,Subscription as Md,SubscriptionRemovable as Ef,tap as kf,throttle as xf,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as lf,ErrorCategory as Id,Subject as wd}from"@vkontakte/videoplayer-shared/evergreen";var hf=18,Ed=!1;try{Ed=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=hf}catch(u){console.error(u)}var Ro=class{constructor(e,t=!1){this.bufferFull$=new wd;this.error$=new wd;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:Id.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)};Ed&&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:Id.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:lf(t)}}},kd=Ro;var Yi=u=>{let e=0;for(let t=0;t<u.length;t++)e+=u.end(t)-u.start(t);return e*1e3};import{abortable as Ut,assertNonNullable as Re,ErrorCategory as St,fromEvent as Lo,getExponentialDelay as Do,isHigher as pf,isNonNullable as Ht,isNullable as ne,now as Wa,once as mf,Subject as ff,Subscription as bf,ValueSubject as ui}from"@vkontakte/videoplayer-shared/evergreen";var ps=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new ui(0);this.currentLowLatencySegmentLength$=new ui(0);this.currentSegmentLength$=new ui(0);this.onLastSegment$=new ui(!1);this.fullyBuffered$=new ui(!1);this.playingRepresentation$=new ui(void 0);this.playingRepresentationInit$=new ui(void 0);this.error$=new ff;this.gaps=[];this.subscription=new bf;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kd(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:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(Lo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:St.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=this.getForwardBufferDuration(n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Ht(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Ht(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ut(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Ne(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Re(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Re(s,"No segments for starting representation");let a=this.initData.get(i);if(Re(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ne(n)||ne(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Re(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Ht(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||Ht(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),ne(r)||ne(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);Ht(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=Nt(i),m=Nt(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ht(p)&&Ht(m)&&pf(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let E=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:E?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=[];if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Ht(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!Ne(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ne(r))return;let s=this.segments.get(i.id)??[],a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(we(this.sourceBuffer.buffered,p)&&we(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Ne(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ut(n,async function*(){let h=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Wa(),!h)return;let d=new DataView(h),l=Qe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ne(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let o=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Lo(window,"online").pipe(mf()).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=Wa(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ne(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Wa(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ne(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Wa();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=Qe(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(!p)continue;let f=Qe(n.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===l?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(we(this.sourceBuffer.buffered,e.segment.time.from,100)&&we(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:St.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",wo(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,n=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Do(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qe(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:c,dataView:h,segments:d}=o,l=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ne(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:St.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let r=[],s=0,a=o=>{o.sort((h,d)=>h.from-d.from);let c=[o[0]];for(let h=1;h<o.length;h++){let{from:d,to:l}=o[h],p=c[c.length-1];p.to>=d?p.to=Math.max(p.to,l):c.push(o[h])}return c},n=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let c=wo(o)?o.size??0:o.byte.to-o.byte.from;s+=c};for(let o of this.segments.values())for(let c of o){let h=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||d)&&c.status==="fed"&&n(c)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let c=this.sourceBuffer.buffered.start(o)*1e3,h=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let l of this.segments.values())for(let p of l)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)&&d++;if(d===this.segments.size){let l={time:{from:c,to:h},url:"",status:"none"};n(l)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let h of c)h.time.from>=e+o&&h.status==="fed"&&n(h)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,h)=>c||h,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let a=0;a<s.length;a++){let 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||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let a=Math.round(s.from),n=Math.round(s.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:St.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ne(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ne(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=e.some(h=>h.from-t<=a&&h.to+t>=n),c=e.filter(h=>a>=h.from&&a<h.to-t||n>h.from+t&&n<=h.to);o||(c.length===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:St.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as ms,assertNever as xd,fromEvent as Pd,merge as gf,now as fs,Subject as Ki,ValueSubject as Bo,flattenObject as Xi,ErrorCategory as bs,SubscriptionRemovable as Sf}from"@vkontakte/videoplayer-shared/evergreen";var Ya=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 Bo(void 0);this.lastConnectionReused$=new Bo(void 0);this.lastRequestFirstBytes$=new Bo(void 0);this.recoverableError$=new Ki;this.error$=new Ki;this.abortAllController=new AbortController;this.subscription=new Sf;this.fetchManifest=ms(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ga);return r?(t.log("success",Xi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Xi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ms(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:h=!1}={}){let d=e,l=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(d,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:xd(t)}this.requestQuic&&(d=Ze(d));let m=this.abortAllController.signal,f;if(a){let T=new AbortController;if(f=gf(Pd(this.abortAllController.signal,"abort"),Pd(a,"abort")).subscribe(()=>{try{T.abort()}catch(O){Ga(O)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(O){Ga(O)}m=T.signal}let b=0,g=fs();p.log("startRequest",Xi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(d,{priority:s,headers:l,signal:m},{ignoreNetworkErrors:h}),y=fs();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(y-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let T=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!n){this.unsubscribeAbortSubscription(f);let T=fs(),O={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",Xi(O)),p.end(),S.arrayBuffer()}let v=S.body;if(n){let T;[v,T]=S.body.tee(),this.throughputEstimator?.trackStream(T,o)}let E=v.getReader(),P,A=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(A)&&(P=A),!P&&i&&(P=i.to-i.from+1);let w=P?new Uint8Array(P):new Uint8Array(0),L=!1,k=T=>{this.unsubscribeAbortSubscription(f),L=!0,Ga(T)},N=ms(m,async function*({done:T,value:O}){if(b===0&&(this.lastRequestFirstBytes$.next(fs()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!T&&O){if(c&&P)w.set(O,b),b+=O.byteLength;else{let R=new Uint8Array(w.length+O.length);R.set(w),R.set(O,w.length),w=R,b+=O.byteLength}r?.(new DataView(w.buffer),b),yield E?.read().then(N,k)}}.bind(this));yield E?.read().then(N,k),this.unsubscribeAbortSubscription(f);let D=fs(),I={failed:L,requestStartedAt:g,requestEndedAt:D,duration:D-g};return L?(p.error("endRequest",Xi(I)),p.end(),null):(p.log("endRequest",Xi(I)),p.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=ms(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},measureThroughput:!1,...i});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=ms(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:xd(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:bs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:bs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:bs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:bs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:bs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ga=u=>{if(!Ie(u))throw u};import{isNullable as vf,ValueSubject as Ad}from"@vkontakte/videoplayer-shared/evergreen";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ad(e.initial),this.debounced$=new Ad(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(vf(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ka=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pt(this.slow,e,this.params.emaAlphaSlow),this.fast=pt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xa=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ao(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pt(this.emaSmoothed,e,this.params.emaAlpha);let i=Uc(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ja=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?pt(this.smoothed,t,this.params.emaAlpha):t}};var vt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ka({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xa({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 Ja({initial:e,label:"liveEdgeDelay",...t})}};var Ji=(u,e)=>{u&&u.playbackRate!==e&&(u.playbackRate=e)};import{isNullable as yf,ValueSubject as Tf}from"@vkontakte/videoplayer-shared/evergreen";var gs=class u{constructor(e,t){this.currentRepresentation$=new Tf(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(!yf(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ne(t.segmentReference))}};var Pf=["timeupdate","progress","play","seeked","stalled","waiting"],Af=["timeupdate","progress","loadeddata","playing","seeked"];var en=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Md;this.subscriptionRemovable=new Ef;this.representationSubscription=new Md;this.state$=new V("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Tt;this.manifestRequested$=new Tt;this.firstBytesManifest$=new Tt;this.manifestReceived$=new Tt;this.firstBytesRequested$=new Tt;this.firstBytesReceived$=new Tt;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Tt;this.fetcherError$=new Tt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=Co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Co(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qe.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Bi(e)??{id:"ManifestParsing",category:qe.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";if(d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p),d&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:qe.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",vs(n)),n}.bind(this));this.initRepresentations=Co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",vs({initialVideo:e,initialAudio:t,sourceHls:i})),Zi(this.manifest),Zi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(yt(d,"error").pipe(Za(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((d,l)=>[...d,...l.representations],[]);if(this.videoBufferManager=new ps("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],ys(t)){let d=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=new ps("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}if(gs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new gs(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ci(...Af.map(d=>yt(this.element,d))).pipe(tr(d=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Ss(),kf(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ss()).subscribe(l=>this.liveStreamEndTimestamp=Oo())),this.subscription.add(yt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:l}=this.tuning.dash;this.livePauseWatchdogSubscription=Vo(l).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+l,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(yt(this.element,"play").subscribe(l=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(er({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(tr(({isActiveLive:l,isLowLatency:p})=>l&&p),Ss()).subscribe(l=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(er({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Za(({bufferLength:l,isActiveLive:p,isLowLatency:m})=>p&&m&&!!l)).subscribe(({bufferLength:l})=>this.liveBuffer.next(l))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(l=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!l)return;let p=this.liveSeekableDuration$.getValue()-l/1e3;this.liveSeekableDuration$.next(Math.max(p,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+l/1e3)})),this.representationSubscription.add(er({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Za(({isLive:l})=>l),Ss((l,p)=>p.bufferLength<l.bufferLength),tr(({rtt:l,bufferLength:p,segmentServerLatency:m})=>{let f=$t(this.manifestUrlString,2);return(l/2+p+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(er({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:l,isActiveLive:p,isLowLatency:m})=>{if(!m||!p)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=l-f;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*g),Ji(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(l=>{let p=0;if(l){let m=(this.element?.currentTime??0)*1e3;p=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==p&&this.liveLoadBufferLength$.next(p)}));let d=0;this.representationSubscription.add(er({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xf(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:l,bufferLength:p})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=$t(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(l)?l:p,E=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let A="none";if(E?A="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),A="active_low_latency"):f!==0&&v<g?A="live_forward_buffering":v<g+y&&(A="live_with_target_offset"),isFinite(l)&&(d=l>d?l:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let w=d-(g+S),L=this.normalizeLiveOffset(Math.trunc(f+w/m)),k=Math.abs(L-f),N=0;!l||k<=this.tuning.dashCmafLive.offsetCalculationError?N=f:L>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=te(this.manifestUrlString,N,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},l=>{this.error$.next({id:"updateLive",category:qe.VIDEO_PIPELINE,thrown:l,message:"Failed to update live with subscription"})}))}let o=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(tr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(tr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=er({allBuffersFull:o,someBufferEnded:c}).pipe(Ss(),tr(({allBuffersFull:d,someBufferEnded:l})=>d&&l),Za(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(l=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){l();return}this.error$.next({id:"OpenOfStream",category:qe.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),l()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ne(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&ys(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=Vo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:qe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Ya({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Zi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Oo()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Zi(this.element),this.state$.setState("running"),this.subscription.add(ci(...Pf.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&we(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:a}=this.tuning.dash,n=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let h=this.currentStallDuration$.getValue();h+=a,this.currentStallDuration$.next(h);let d={timeInWaiting:h},l=Oo(),p=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,b=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,S=b<p&&l-m>r,y=this.audioBufferManager&&g<p&&l-f>r;if((!t||c)&&((S||y)&&h>r||h>=i))throw new Error(`Stall timeout exceeded: ${h} ms`);if(n&&h%s===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(E=>{this.error$.next({id:"stallIntervalCallback",category:qe.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:E})}),d.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),d.position=v}this.tracer.log("stallIntervalCallback",vs(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Vo(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:qe.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Zi(this.element),Zi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),we(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!($d(this.element)||$d(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",vs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ys(this.element)&&ys(this.source)&&ys(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=wf(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",vs(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as $f,map as Mf,observeElementSize as Rf,Subscription as Lf,ValueSubject as No,noop as Df}from"@vkontakte/videoplayer-shared/evergreen";var tn=class{constructor(){this.subscription=new Lf;this.pipSize$=new No(void 0);this.videoSize$=new No(void 0);this.elementSize$=new No(void 0);this.pictureInPictureWindowRemoveEventListener=Df}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Rf(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($f({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Mf(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new Uf;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Cf(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new en({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;_f(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Ld.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(Fo(d=>!!d.length),Bd()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Is(d=>d.to.state!=="none"),Ts());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Fo(Dd),Bd()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Is(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Vf(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(To(b));let g=[];for(let S of b.representations){let y=ns(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(Io(f));let b=[];for(let g of f.representations){let S=Nt({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=cd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=ws(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ff(this.video,"progress")).pipe(Fo(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(n=n.pipe(Hf(o))),this.subscription.add(n.subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);Dd(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(Of({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ws(rn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Is(d=>d.to)))}).pipe(Is(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Ts()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ts()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Io(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ts()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(To(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Is(({to:d})=>d==="ready"),Ts());this.subscription.add(ws(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,rn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ws(c,this.player.state$.stateChangeEnded$,rn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rn(["init"])).pipe(Nf(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:w})=>w===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let w=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}if(c){let w=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=E&&this.audioTracksMap.get(E)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ld.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var Es=class extends di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as _o,merge as Cd,filter as Vd,filterChanged as Od,isNullable as Uo,map as Nd,ValueSubject as Ho,isNonNullable as jf}from"@vkontakte/videoplayer-shared/evergreen";var ks=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new Ho(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Od()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Nd(o=>o.to)).subscribe(this.player.isLowLatency$)).add(_o({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Nd(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(_o({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Cd(r.playbackRateState$,new Ho(1))}).pipe(Vd(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||Uo(h)||(t=o-h)})).add(_o({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Cd(r.playbackRateState$,new Ho(1))}).pipe(Od((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||Uo(o)||Uo(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=dd(o);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Vd(o=>jf(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as gb,assertNonNullable as Sb,combine as vb,debounce as yb,ErrorCategory as Zd,filter as iu,filterChanged as Cs,fromEvent as Tb,isNonNullable as el,isNullable as Ib,map as Vs,merge as Os,observableFrom as hn,once as tl,Subscription as wb}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Xo,assertNonNullable as sr,combine as ar,ErrorCategory as tt,filter as cn,filterChanged as Ls,flattenObject as Ds,fromEvent as ut,getTraceSubscriptionMethod as nb,interval as Jo,isNonNullable as Bs,isNullable as Xd,map as nr,merge as mi,now as Zo,Subject as It,Subscription as eu,SubscriptionRemovable as ob,tap as ub,throttle as Jd,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as zf,ErrorCategory as Fd,Subject as _d}from"@vkontakte/videoplayer-shared/evergreen";var Qf=18,Ud=!1;try{Ud=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=Qf}catch(u){console.error(u)}var jo=class{constructor(e,t=!1){this.bufferFull$=new _d;this.error$=new _d;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:Fd.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)};Ud&&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:Fd.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:zf(t)}}},Hd=jo;import{abortable as zt,assertNonNullable as Le,ErrorCategory as hi,fromEvent as Wo,getExponentialDelay as Go,isHigher as Kf,isNonNullable as Qt,isNullable as oe,now as nn,once as Xf,Subject as Jf,Subscription as Zf,ValueSubject as pi}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as qf,throttleFn as Wf}from"@vkontakte/videoplayer-shared/evergreen";var xs=({id:u,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?nt(s):void 0)??qf({width:e,height:t});return n&&{id:u,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},jd=({id:u,bitrate:e})=>({id:u,bitrate:e}),zd=({language:u,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),Qd=({language:u,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:u,label:e}),zo=({id:u,language:e,label:t,codecs:i,isDefault:r})=>({id:u,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Qo=({id:u,language:e,label:t,hdr:i,codecs:r})=>({id:u,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),qo=u=>"url"in u,Fe=u=>u.type==="template";var qd=u=>{u.sort((t,i)=>t.from-i.from);let e=[u[0]];for(let t=1;t<u.length;t++){let{from:i,to:r}=u[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(u[t])}return e},li=(u,e)=>{for(let t of u)if(e(t))return t;return null},Wd=u=>{let e=!1,t=Wf(()=>{e=!0},u);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Gf,Subscription as Yf}from"@vkontakte/videoplayer-shared/evergreen";var sn=u=>{let e=[];for(let t=0;t<u.length;t++){let i=Math.floor(u.start(t)*1e3),r=Math.ceil(u.end(t)*1e3);e.push(i,r)}return e};var an=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Yf;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Gf(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=sn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],n=t[i+1];if(a>r||n<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ps=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:o=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new pi(0);this.currentLowLatencySegmentLength$=new pi(0);this.currentSegmentLength$=new pi(0);this.onLastSegment$=new pi(!1);this.fullyBuffered$=new pi(!1);this.playingRepresentation$=new pi(void 0);this.playingRepresentationInit$=new pi(void 0);this.error$=new Jf;this.gaps=[];this.subscription=new Zf;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hd(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new an(this.mediaSource,this.sourceBuffer),this.subscription.add(Wo(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Wo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:hi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!B(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,Yi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let c=ae(this.sourceBuffer.buffered,n),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Qt(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Qt(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=zt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let c=t.find(l=>l.id===o);c&&this.representations.set(o,c);let h=this.representations.get(o);if(!h||!Fe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Le(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Le(s,"No segments for starting representation");let a=this.initData.get(i);if(Le(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=n,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Le(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(oe(n)||oe(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Le(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Qt(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!oe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(oe(e)||oe(this.downloadingRepresentationId)||oe(this.playingRepresentationId)||oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||Qt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),oe(r)||oe(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);Qt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let n=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=xs(i),m=xs(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Qt(p)&&Qt(m)&&Kf(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?n+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+o&&(n=a?a.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let E=v.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:y,status:E?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ae(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,n),h?.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&ae(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ae(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Qt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Fe(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,o=r?.findIndex(c=>n>=c.time.from+s&&n<=c.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(o+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Fe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Oe(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(l==="none"||l==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(we(this.sourceBuffer.buffered,p)&&we(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,o=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(n<=h||o<=d);l++){let p=a[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){Fe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:n,onProgress:o,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await zt(n,async function*(){let h=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=nn(),!h)return;let d=new DataView(h),l=Qe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(d,f)}o&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Ie(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Fe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await zt(a,async function*(){let o=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,o),Wo(window,"online").pipe(Xf()).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=nn(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Ie(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Fe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(n,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=nn(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Fe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=nn();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:hi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:o}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),h=Qe(a.mime).parseFeedableSegmentChunk(c,this.isLive);h?.byteLength&&(o.status="partially_fed",n.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),n.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:c}=o,h=c.byte.from-i,d=c.byte.to-i,l=d-h+1,p=h<r,m=d<=r;if(p){if(c.status==="downloading"&&m){c.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(o.loadedBytes=Math.min(l,r-h),o.loadedBytes>o.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+o.feedingBytes,o.loadedBytes-o.feedingBytes),b=o.loadedBytes===l?f:Qe(n.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(c.status="partially_fed",o.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(o.fedBytes+=b.byteLength,o.fedBytes===l&&this.onSegmentFullyAppended(o,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(we(this.sourceBuffer.buffered,e.segment.time.from,100)&&we(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:hi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",qo(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?zt(this.destroyAbortController.signal,async function*(){let n=Go(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qe(e.mime),r)).then(n=>{if(!n)return;let{init:o,dataView:c,segments:h}=n,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let l=h;this.isLive&&Fe(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:hi.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||oe(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=n=>{if(s>=t)return;r.push({...n.time});let o=qo(n)?n.size??0:n.byte.to-n.byte.from;s+=o};for(let n of this.segments.values())for(let o of n){let c=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||h)&&o.status==="fed"&&a(o)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let o=this.sourceBuffer.buffered.start(n)*1e3,c=this.sourceBuffer.buffered.end(n)*1e3,h=0;for(let d of this.segments.values())for(let l of d)["none","partially_ejected"].includes(l.status)&&Math.round(l.time.from)<=Math.round(o)&&Math.round(l.time.to)>=Math.round(c)&&h++;if(h===this.segments.size){let d={time:{from:o,to:c},url:"",status:"none"};a(d)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let c of o)c.time.from>=e+n&&c.status==="fed"&&a(c)}return r.length?(r=qd(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,c)=>o||c,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||oe(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,n=i.end(s)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){r=void 0;break}n>t.time.from&&n<t.time.to&&(r.from=n),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),a=Math.round(r.to);for(let n=0;n<i.length;n++)if(s>=Math.round(i.start(n)*1e3)&&a<=Math.round(i.end(n)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:hi.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(oe(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||oe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=sn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),n=Math.ceil(r.time.to),o=!1,c=0;for(let h=0;h<e.length;h+=2){let d=e[h],l=e[h+1];o||(o=d-t<=a&&l+t>=n),(a>=d&&a<l-t||n>d+t&&n<=l)&&(c+=1)}o||(c===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:hi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as As,assertNever as Gd,fromEvent as Yd,merge as eb,now as $s,Subject as ir,ValueSubject as Yo,flattenObject as rr,ErrorCategory as Ms,SubscriptionRemovable as tb}from"@vkontakte/videoplayer-shared/evergreen";var un=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new ir;this.firstBytesManifest$=new ir;this.firstBytesRequested$=new ir;this.firstBytesReceived$=new ir;this.lastConnectionType$=new Yo(void 0);this.lastConnectionReused$=new Yo(void 0);this.lastRequestFirstBytes$=new Yo(void 0);this.recoverableError$=new ir;this.error$=new ir;this.abortAllController=new AbortController;this.subscription=new tb;this.fetchManifest=As(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ze(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vi(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(on);return r?(t.log("success",rr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=As(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:o=!1,bufferOptimisation:c=!1}={}){let h=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:Gd(t)}this.requestQuic&&(h=Ze(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=eb(Yd(this.abortAllController.signal,"abort"),Yd(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){on(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){on(T)}p=I.signal}let f=0,b=$s();l.log("startRequest",rr({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested$.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=$s();if(!g)return l.error("error",{message:"No response in request"}),l.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:I}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!n){this.unsubscribeAbortSubscription(m);let I=$s(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return l.log("endRequest",rr(T)),l.end(),g.arrayBuffer()}let y=g.body;if(n){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,o)}let v=y.getReader(),E,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(E=P),!E&&i&&(E=i.to-i.from+1);let A=E?new Uint8Array(E):new Uint8Array(0),w=!1,L=I=>{this.unsubscribeAbortSubscription(m),w=!0,on(I)},k=As(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next($s()-b),this.firstBytesReceived$.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&T){if(c&&E)A.set(T,f),f+=T.byteLength;else{let O=new Uint8Array(A.length+T.length);O.set(A),O.set(T,A.length),A=O,f+=T.byteLength}r?.(new DataView(A.buffer),f),yield v?.read().then(k,L)}}.bind(this));yield v?.read().then(k,L),this.unsubscribeAbortSubscription(m);let N=$s(),D={failed:w,requestStartedAt:b,requestEndedAt:N,duration:N-b};return w?(l.error("endRequest",rr(D)),l.end(),null):(l.log("endRequest",rr(D)),l.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=As(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,o=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,o=s+1===c,o&&(a=Math.min(c,r),n=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!d)return null;let l=new DataView(d,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=As(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Gd(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ms.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ms.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ms.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ms.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ms.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},on=u=>{if(!Ie(u))throw u};import{isNullable as ib,ValueSubject as rb}from"@vkontakte/videoplayer-shared/evergreen";var Rs=class u{constructor(e,t){this.currentRepresentation$=new rb(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(!ib(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,n=r.segments[s-1].time.to;if(e<a||e>n)continue;let o=r.segments.find(c=>c.time.from<=e&&c.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=u.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>u.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Fe(t.segmentReference))}};var cb=["progress","play","seeked","stalled","waiting"],db=["timeupdate","progress","loadeddata","playing","seeked"];var dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new eu;this.subscriptionRemovable=new ob;this.representationSubscription=new eu;this.state$=new V("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new It;this.manifestRequested$=new It;this.firstBytesManifest$=new It;this.manifestReceived$=new It;this.firstBytesRequested$=new It;this.firstBytesReceived$=new It;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new It;this.fetcherError$=new It;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new It;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Xo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:tt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xo(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:tt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=_i(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(o){let c=Bi(e)??{id:"ManifestParsing",category:tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(c)}if(!t)return null;let i=(o,c,h)=>!!(this.element?.canPlayType?.(c)&&xe()?.isTypeSupported?.(`${c}; codecs="${h}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:d}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((c-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let h=t.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));r[o]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);o==="audio"&&(a=ji(l),d=a[0]),o==="video"&&(s=Hi(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=h.filter(({codecs:p})=>Vt(p)===d))}else{let l=new Set(h.map(({codecs:p})=>p));d=Ui(l),d&&(r[o]=h.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);$.display.isHDR&&l&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let n={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Ds(n)),n}.bind(this));this.initRepresentations=Xo(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ds({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new eu,this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(ut(l,"error").pipe(cn(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Ii();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Mt())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},n=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Ps("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],Bs(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Ps("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...db.map(l=>ut(this.element,l))).pipe(nr(l=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Ls(),ub(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(ut(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ls()).subscribe(p=>this.liveStreamEndTimestamp=Zo())),this.subscription.add(ut(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Jo(1e3).subscribe(p=>{let m=$t(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ut(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ar({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(nr(({isActiveLive:p,isLowLatency:m})=>p&&m),Ls()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ji(this.element,1)})),this.representationSubscription.add(ar({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(cn(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(ar({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(cn(({isLive:p})=>p),Ls((p,m)=>m.bufferLength<p.bufferLength),nr(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=$t(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ar({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(y)>g&&(v=1+Math.sign(y)*S),Ji(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add(ar({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Jd(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=$t(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let w="none";if(P?w="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),w="active_low_latency"):b!==0&&E<S?w="live_forward_buffering":E<S+v&&(w="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),w==="live_forward_buffering"||w==="live_with_target_offset"){let L=l-(S+y),k=this.normolizeLiveOffset(Math.trunc(b+L/f)),N=Math.abs(k-b),D=0;!p||N<=this.tuning.dashCmafLive.offsetCalculationError?D=b:k>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(D=k),this.manifestUrlString=te(this.manifestUrlString,D,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:tt.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let c=mi(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(nr(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),h=mi(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(nr(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),d=ar({allBuffersFull:c,someBufferEnded:h}).pipe(Ls(),nr(({allBuffersFull:l,someBufferEnded:p})=>l&&p),cn(l=>l));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(mi(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:tt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Fe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Bs(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=Jo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:tt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new un({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Zo()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=te(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){sr(this.element),this.state$.setState("running");let e=ut(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Jd(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(mi(...cb.map(t=>ut(this.element,t)),ut(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:tt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ut(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ut(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&we(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Zo(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,c=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=c<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,l=this.audioBufferManager&&h<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||l)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:tt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Ds(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Jo(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:tt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),we(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Xd(this.element)||Xd(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ds({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Bs(this.element)&&Bs(this.source)&&Bs(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=nb(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,n=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let c of o.gaps)(c.persistent||o.playingRepresentation$.getValue()===c.representation)&&c.from-n<=s&&c.to+n>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a=1/0:(a===null||c.to>a)&&(a=c.to));if(a!==null){let o=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Ds({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as lb,map as hb,observeElementSize as pb,Subscription as mb,ValueSubject as tu,noop as fb}from"@vkontakte/videoplayer-shared/evergreen";var ln=class{constructor(){this.subscription=new mb;this.pipSize$=new tu(void 0);this.videoSize$=new tu(void 0);this.elementSize$=new tu(void 0);this.pictureInPictureWindowRemoveEventListener=fb}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(pb(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(lb({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(hb(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var fi=class{constructor(e){this.subscription=new wb;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new Lt;this.stallsManager=new Di;this.elementSizeManager=new ln;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Je;this.audioTrackSwitchHistory=new Je;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return gb(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bt(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new dn({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;Ib(this.observableVideo)&&(this.observableVideo=ye(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Zd.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(iu(d=>!!d.length),tl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Vs(d=>d.to.state!=="none"),Cs());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(iu(el),tl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Vs(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Sb(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(zo(b));let g=[];for(let S of b.representations){let y=jd(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of l.video){m.push(Qo(f));let b=[];for(let g of f.representations){let S=xs({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of l.text)for(let b of f.representations){let g=zd(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:n}=this.params.tuning.dash,o=n&&Wd(n)||null;this.subscription.add(Os(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$,Tb(this.video,"progress")).pipe(iu(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||l||d==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=li(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);el(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(vb({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Os(hn([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Vs(d=>d.to)))}).pipe(Vs(({videoState:d,autoVideoTrackState:l})=>d.to!=="stopped"&&l),Cs()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Cs()).subscribe(d=>{let l=li(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Qo(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Cs()).subscribe(d=>{let l=li(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(zo(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Vs(({to:d})=>d==="ready"),Cs());this.subscription.add(Os(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,hn(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Os(c,this.player.state$.stateChangeEnded$,hn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Os(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hn(["init"])).pipe(yb(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ri:ii,t=this.params.tuning.useNewAutoSelectVideoTrack?Ri:Mi,i=this.params.tuning.useNewAutoSelectVideoTrack?ze:$i,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,o=li(this.videoTracksMap.keys(),w=>w.id===n),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=li(this.videoStreamsMap.keys(),w=>w.id===h.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let p=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=g?.id&&li(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,y=0;if(S){if(o&&!a){let w=e(o,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}if(c){let w=e(c,l,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,w?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=i(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=S&&t(v,l,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(v)?.representation,A=E&&this.audioTracksMap.get(E)?.representation;P&&A?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=A):P&&!A&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zd.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Se(this.video),this.tracer.end()}};var Ns=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ru,merge as il,filter as rl,filterChanged as sl,isNullable as su,map as al,ValueSubject as au,isNonNullable as Eb}from"@vkontakte/videoplayer-shared/evergreen";var Fs=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let n=new au(1);a(r.playbackRateState$,n),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(sl()).subscribe(o=>{let c=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!o&&!c&&d?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(al(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ru({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(al(({liveBufferTime:o,liveAvailabilityStartTime:c})=>o&&c?o+c:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(rl(o=>Eb(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(ru({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:il(r.playbackRateState$,new au(1))}).pipe(rl(({liveStreamStatus:o,liveDuration:c})=>o==="active"&&!!c)).subscribe(({liveDuration:o,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-l||this.video.paused||su(h)||(t=o-h)})).add(ru({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:il(r.playbackRateState$,new au(1))}).pipe(sl((o,c)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===c.liveDuration:o.time===c.time)).subscribe(({time:o,liveDuration:c,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-l||su(o)||su(c))return;let p=-1*(c-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let c=Qd(o);this.params.output.availableTextTracks$.next([c])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var nl="X-Playback-Duration",nu=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(nl)?parseInt(e.headers.get(nl),10):void 0};import{assertNever as Cb,combine as Vb,debounce as Ob,ErrorCategory as fn,filter as Nb,filterChanged as Fb,isNonNullable as cl,isNullable as bn,map as dl,merge as _b,observableFrom as Ub,Subscription as Hb,ValueSubject as uu,VideoQuality as jb}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as kb,getExponentialDelay as xb}from"@vkontakte/videoplayer-shared/evergreen";var Pb=u=>{let e=null;if(u.QUALITY&&(e=nt(u.QUALITY)),!e&&u.RESOLUTION){let[t,i]=u.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kb({width:t,height:i})}return e??null},Ab=(u,e)=>{let t=u.split(`
|
|
178
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("="))),h=c.QUALITY??`stream-${c.BANDWIDTH}`,d=Pb(c),l;c.BANDWIDTH&&(l=parseInt(c.BANDWIDTH,10)/1e3||void 0),!l&&c["AVERAGE-BANDWIDTH"]&&(l=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,m;if(c.RESOLUTION){let[b,g]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();d&&i.push({id:h,quality:d,url:f,bandwidth:l,size:m,fps:p})}if(o){let c=Object.fromEntries(o[1].split(",").map(p=>{let m=p.indexOf("=");return[p.substring(0,m),p.substring(m+1)]}).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),h=c.URI?.replace(/playlist$/,"subtitles.vtt"),d=c.LANGUAGE,l=c.NAME;h&&d&&r.push({type:"internal",id:d,label:l,language:d,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},$b=u=>new Promise(e=>{setTimeout(()=>{e()},u)}),ou=0,ol=async(u,e=u,t,i)=>{let s=await(await fetch(u,i)).text();ou+=1;try{let{qualityManifests:a,textTracks:n}=Ab(s,e);return{qualityManifests:a,textTracks:n}}catch{if(ou<=t.manifestRetryMaxCount)return await $b(xb(ou-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ol(u,e,t)}return{qualityManifests:[],textTracks:[]}},pn=ol;import{isNonNullable as Mb,Subscription as Rb,throttle as Lb,ValueSubject as ul,Subject as Db,ErrorCategory as Bb}from"@vkontakte/videoplayer-shared/evergreen";var mn=class{constructor(e,t,i,r,s){this.subscription=new Rb;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ul(null);this.getCurrentTime$=new ul(null);this.error$=new Db;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Lb(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(),h=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:c}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),l=new Date(i.programDateTime).valueOf();i.segmentStartTime=l-d}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=o;let c=new Date(o);c.setMilliseconds(0),s=c.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Mb(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:Bb.WTF,thrown:t,message:e})}};var _s=class{constructor(e){this.subscription=new Hb;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new uu([]);this.liveOffset=new ei;this.manifestStartTime$=new uu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Cb(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jb.INVARIANT,url:this.params.source.url};let t=(i,r)=>pn(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 mn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:fn.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:fn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new uu(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:fn.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(Fb(),dl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&cl(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let l=this.manifests$.getValue().find(p=>p.id===d);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(se(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(Vb({startTime:this.manifestStartTime$.pipe(Nb(cl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:o})=>this.params.output.liveTime$.next(n+o*1e3),i)),this.subscription.add(this.manifests$.pipe(dl(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=_b(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ub(["init"])).pipe(Ob(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(bn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:o}=t?.to??i??{};for(let[c,h]of[[n,"mq"],[o,"lq"]]){let d=String(parseFloat(c||""));h&&c&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=te(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),nu(a).then(n=>{if(!bn(n))this.maxSeekBackTime$.next(n);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(bn(o)||!isFinite(o))&&fetch(a).then(c=>c.text()).then(c=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){let d=new URL(h,a).toString();nu(d).then(l=>{bn(l)||this.maxSeekBackTime$.next(l)})}}).catch(()=>{})}})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=te(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Qb,debounce as zb,ErrorCategory as cu,fromEvent as du,isNonNullable as qb,isNullable as Wb,map as ll,merge as hl,observableFrom as pl,Subscription as Gb,ValueSubject as ml,VideoQuality as Yb}from"@vkontakte/videoplayer-shared/evergreen";var Us=class{constructor(e){this.subscription=new Gb;this.videoState=new V("stopped");this.manifests$=new ml([]);this.unmuteAfterBrowserResetsHappened=new ml(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Qb(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Yb.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),pn(te(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cu.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:cu.WTF,message:"HlsProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ll(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&qb(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(se(m.url)))}let d=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n.state==="requested"&&this.seek(n.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(ll(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(hl(du(n,"addtrack"),du(n,"removetrack"),du(n,"change"),pl(["init"])).subscribe(()=>{for(let o=0;o<n.length;o++)n[o].mode="hidden"},i))}let a=hl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,pl(["init"])).pipe(zb(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(Wb(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[n,o]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));o&&n&&r.searchParams.set(o,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Kb,assertNonNullable as fl,debounce as Xb,ErrorCategory as bl,isHigherOrEqual as Jb,isLowerOrEqual as Zb,isNonNullable as eg,merge as tg,observableFrom as ig,Subscription as rg,map as sg}from"@vkontakte/videoplayer-shared/evergreen";var Hs=class{constructor(e){this.subscription=new rg;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:o}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Kb(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"MpegProvider",category:bl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(sg(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&eg(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let o=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(o!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(o),h.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=tg(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ig(["init"])).pipe(Xb(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;fl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ze(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(se(t))}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Qe(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||xi(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?Zb(r,e.max):!0,o=e.min?Jb(r,e.min):!0;n&&o||i(e)}};import{assertNever as Sl,debounce as ug,merge as vl,observableFrom as cg,Subscription as dg,map as yl,ValueSubject as lg,ErrorCategory as hu,VideoQuality as hg}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as ag}from"@vkontakte/videoplayer-shared/evergreen";var gl=["stun:videostun.mycdn.me:80"],ng=1e3,og=3,lu=()=>null,gn=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=lu;this.externalStopCallback=lu;this.externalErrorCallback=lu;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:gl}]};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:ag.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),ng)}normalizeOptions(e={}){let t={stunServerList:gl,maxRetryNumber:og,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var js=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new lg(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Sl(e)}};this.subscription=new dg,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new gn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:hu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(vl(this.videoState.stateChangeStarted$.pipe(yl(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(yl(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(a,n)=>this.subscription.add(a.subscribe(n,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Sl(a.to)}},i)).add(vl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,cg(["init"])).pipe(ug(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:hg.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:hu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var or=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Qs,assertNonNullable as Et,ErrorCategory as Sn,filter as xl,isNonNullable as Pl,isNullable as vg,map as yg,merge as Tg,once as Ig,Subject as Z,Subscription as Al,ValueSubject as F,flattenObject as pu,devNull as Eg}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as pg,map as Tl,Subscription as mg,Subject as fg}from"@vkontakte/videoplayer-shared/evergreen";var Il=u=>new pg(e=>{let t=new mg,i=u.desiredPlaybackState$.stateChangeStarted$.pipe(Tl(({from:c,to:h})=>`${c}-${h}`)),r=u.desiredPlaybackState$.stateChangeEnded$,s=u.providerChanged$.pipe(Tl(({type:c})=>c!==void 0)),a=new fg,n=0,o="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),o=c,n=window.setTimeout(()=>a.next(c),u.maxTransitionInterval),C({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{C({m:"hangup.cl",id:n}),window.clearTimeout(n),o="unknown",n=0})),t.add(s.subscribe(c=>{n&&(C({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(o),u.maxTransitionInterval),C({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as bg,Subscription as gg,combine as Sg,filter as wl,once as kl}from"@vkontakte/videoplayer-shared/evergreen";function El(){return new(window.AudioContext||window.webkitAudioContext)}var ur=class u{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new gg;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wl(s=>!!s.type),kl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Sg({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),kl()).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=El();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:u.errorId,category:bg.VIDEO_PIPELINE,message:e?.message??`${u.errorId} exception`,thrown:e})}};var wg={chunkDuration:5e3,maxParallelRequests:5},zs=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new Z;this.noAvailableProvidersError$=new Z;this.volumeMultiplierError$=new Z;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableVideoCodecs$:new F([]),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),availableAudioCodecs$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),currentNativeBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new Z,fetcherError$:new Z,fetcherRecoverableError$:new Z,warning$:new Z,willSeekEvent$:new Z,soundProhibitedEvent$:new Z,seekedEvent$:new Z,loopedEvent$:new Z,endedEvent$:new Z,manifestRequested$:new Z,firstBytesManifest$:new Z,manifestReceived$:new Z,firstBytesRequested$:new Z,firstBytesReceived$:new Z,firstBytesEvent$:new Z,loadedMetadataEvent$:new Z,firstFrameEvent$:new Z,canplay$:new Z,isLive$:new F(void 0),isLiveEnded$:new F(null),canPlayLiveTailBuffer$:new F(!1),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new Z,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new Al;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=Dn([...td(this.params.tuning),...ed(this.params.tuning)]).filter(c=>Pl(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",pu(s)),this.screenFormatsIterator=new or(s);let a=[...vo(!0),...vo(!1)];this.chromecastFormatsIterator=new or(a.filter(c=>Pl(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&n!==1&&ur.isSupported()&&(this.volumeMultiplierManager=new ur(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}init(){C.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new or(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(vg(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Sn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Qs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),this.params.tuning.useNewDashProvider?new Ns({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ws({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),this.params.tuning.useNewDashProvider?new Fs({...n,source:o}):new ks({...n,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return Et(o),new Us({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new _s({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new Hs({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new Cc({...n,source:o,config:{...wg,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new js({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,n={meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof lt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return Et(c),new fr({...n,chromecastConnector:c})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Et(o),new vr({...n,connection:o})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Qs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Qs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Qs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Al,t=!1,i=0;e.add(Tg(this.providerOutput.error$.pipe(xl(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Il({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(yg(s=>({id:`ProviderHangup:${s}`,category:Sn.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(xl(({to:a})=>a==="playing"),Ig()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=C.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&window.console.log(`===== DASH_LIVE DEBUG START ====
|
|
179
|
+
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let o=r[++a],c=new URL(o,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:c}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),l=new Date(i.programDateTime).valueOf();i.segmentStartTime=l-d}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=o;let c=new Date(o);c.setMilliseconds(0),s=c.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Mb(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:Bb.WTF,thrown:t,message:e})}};var _s=class{constructor(e){this.subscription=new Hb;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new uu([]);this.liveOffset=new ei;this.manifestStartTime$=new uu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Cb(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jb.INVARIANT,url:this.params.source.url};let t=(i,r)=>pn(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 mn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:fn.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:fn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new uu(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:fn.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(Fb(),dl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&cl(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let l=this.manifests$.getValue().find(p=>p.id===d);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(se(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(Vb({startTime:this.manifestStartTime$.pipe(Nb(cl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:o})=>this.params.output.liveTime$.next(n+o*1e3),i)),this.subscription.add(this.manifests$.pipe(dl(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=_b(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ub(["init"])).pipe(Ob(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(bn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:o}=t?.to??i??{};for(let[c,h]of[[n,"mq"],[o,"lq"]]){let d=String(parseFloat(c||""));h&&c&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=te(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),nu(a).then(n=>{if(!bn(n))this.maxSeekBackTime$.next(n);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(bn(o)||!isFinite(o))&&fetch(a).then(c=>c.text()).then(c=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){let d=new URL(h,a).toString();nu(d).then(l=>{bn(l)||this.maxSeekBackTime$.next(l)})}}).catch(()=>{})}})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=te(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as zb,debounce as Qb,ErrorCategory as cu,fromEvent as du,isNonNullable as qb,isNullable as Wb,map as ll,merge as hl,observableFrom as pl,Subscription as Gb,ValueSubject as ml,VideoQuality as Yb}from"@vkontakte/videoplayer-shared/evergreen";var Us=class{constructor(e){this.subscription=new Gb;this.videoState=new V("stopped");this.manifests$=new ml([]);this.unmuteAfterBrowserResetsHappened=new ml(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||n){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return zb(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Yb.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),pn(te(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cu.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:cu.WTF,message:"HlsProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ll(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&qb(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(se(m.url)))}let d=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),n.state==="requested"&&this.seek(n.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(ll(n=>n.map(({id:o,quality:c,size:h,bandwidth:d,fps:l})=>({id:o,quality:c,size:h,fps:l,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(hl(du(n,"addtrack"),du(n,"removetrack"),du(n,"change"),pl(["init"])).subscribe(()=>{for(let o=0;o<n.length;o++)n[o].mode="hidden"},i))}let a=hl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,pl(["init"])).pipe(Qb(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(Wb(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[n,o]of[[s,"mq"],[a,"lq"]]){let c=String(parseFloat(n||""));o&&n&&r.searchParams.set(o,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Kb,assertNonNullable as fl,debounce as Xb,ErrorCategory as bl,isHigherOrEqual as Jb,isLowerOrEqual as Zb,isNonNullable as eg,merge as tg,observableFrom as ig,Subscription as rg,map as sg}from"@vkontakte/videoplayer-shared/evergreen";var Hs=class{constructor(e){this.subscription=new rg;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:o}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Kb(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"MpegProvider",category:bl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(sg(n=>n.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,i)),Ct({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&eg(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let o=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(o!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(o),h.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=tg(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ig(["init"])).pipe(Xb(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;fl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ze(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(se(t))}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=ze(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(c=>c.track);if(!r||!s||xi(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?Zb(r,e.max):!0,o=e.min?Jb(r,e.min):!0;n&&o||i(e)}};import{assertNever as Sl,debounce as ug,merge as vl,observableFrom as cg,Subscription as dg,map as yl,ValueSubject as lg,ErrorCategory as hu,VideoQuality as hg}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as ag}from"@vkontakte/videoplayer-shared/evergreen";var gl=["stun:videostun.mycdn.me:80"],ng=1e3,og=3,lu=()=>null,gn=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=lu;this.externalStopCallback=lu;this.externalErrorCallback=lu;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:gl}]};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:ag.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),ng)}normalizeOptions(e={}){let t={stunServerList:gl,maxRetryNumber:og,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var js=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new lg(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Sl(e)}};this.subscription=new dg,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new gn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:hu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(vl(this.videoState.stateChangeStarted$.pipe(yl(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(yl(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=ye(this.video);this.subscription.add(()=>r.destroy());let s=(a,n)=>this.subscription.add(a.subscribe(n,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Sl(a.to)}},i)).add(vl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,cg(["init"])).pipe(ug(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:hg.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:hu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var or=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as zs,assertNonNullable as wt,ErrorCategory as Sn,filter as xl,isNonNullable as Pl,isNullable as vg,map as yg,merge as Tg,once as Ig,Subject as Z,Subscription as Al,ValueSubject as F,flattenObject as pu,devNull as wg}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as pg,map as Tl,Subscription as mg,Subject as fg}from"@vkontakte/videoplayer-shared/evergreen";var Il=u=>new pg(e=>{let t=new mg,i=u.desiredPlaybackState$.stateChangeStarted$.pipe(Tl(({from:c,to:h})=>`${c}-${h}`)),r=u.desiredPlaybackState$.stateChangeEnded$,s=u.providerChanged$.pipe(Tl(({type:c})=>c!==void 0)),a=new fg,n=0,o="unknown";return t.add(i.subscribe(c=>{n&&window.clearTimeout(n),o=c,n=window.setTimeout(()=>a.next(c),u.maxTransitionInterval),C({m:"hangup.set",l:c,id:n})})),t.add(r.subscribe(()=>{C({m:"hangup.cl",id:n}),window.clearTimeout(n),o="unknown",n=0})),t.add(s.subscribe(c=>{n&&(C({m:"hangup.rs.0",id:n}),window.clearTimeout(n),n=0,c&&(n=window.setTimeout(()=>a.next(o),u.maxTransitionInterval),C({m:"hangup.rs.1",id:n})))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as bg,Subscription as gg,combine as Sg,filter as El,once as kl}from"@vkontakte/videoplayer-shared/evergreen";function wl(){return new(window.AudioContext||window.webkitAudioContext)}var ur=class u{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new gg;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(El(s=>!!s.type),kl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Sg({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(El(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),kl()).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=wl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:u.errorId,category:bg.VIDEO_PIPELINE,message:e?.message??`${u.errorId} exception`,thrown:e})}};var Eg={chunkDuration:5e3,maxParallelRequests:5},Qs=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new Z;this.noAvailableProvidersError$=new Z;this.volumeMultiplierError$=new Z;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableVideoCodecs$:new F([]),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),availableAudioCodecs$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),currentNativeBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new Z,fetcherError$:new Z,fetcherRecoverableError$:new Z,warning$:new Z,willSeekEvent$:new Z,soundProhibitedEvent$:new Z,seekedEvent$:new Z,loopedEvent$:new Z,endedEvent$:new Z,manifestRequested$:new Z,firstBytesManifest$:new Z,manifestReceived$:new Z,firstBytesRequested$:new Z,firstBytesReceived$:new Z,firstBytesEvent$:new Z,loadedMetadataEvent$:new Z,firstFrameEvent$:new Z,canplay$:new Z,isLive$:new F(void 0),isLiveEnded$:new F(null),canPlayLiveTailBuffer$:new F(!1),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new Z,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new Al;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=Dn([...td(this.params.tuning),...ed(this.params.tuning)]).filter(c=>Pl(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",pu(s)),this.screenFormatsIterator=new or(s);let a=[...vo(!0),...vo(!1)];this.chromecastFormatsIterator=new or(a.filter(c=>Pl(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&n!==1&&ur.isSupported()&&(this.volumeMultiplierManager=new ur(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}init(){C.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new or(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(vg(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Sn.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 zs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return wt(o),this.params.tuning.useNewDashProvider?new Ns({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new Gi({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Es({...n,source:o,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),this.params.tuning.useNewDashProvider?new Fs({...n,source:o}):new ks({...n,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return wt(o),new Us({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),new _s({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return wt(o),new Hs({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new Cc({...n,source:o,config:{...Eg,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new js({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 zs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,n={meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof lt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return wt(c),new fr({...n,chromecastConnector:c})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return wt(o),new vr({...n,connection:o})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return zs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return zs(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 zs(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 Al,t=!1,i=0;e.add(Tg(this.providerOutput.error$.pipe(xl(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Il({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(yg(s=>({id:`ProviderHangup:${s}`,category:Sn.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(xl(({to:a})=>a==="playing"),Ig()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=C.drain(),{logDashLiveDebug:a,sendDashLiveDebug:n}=this.params.tuning;if(a&&window.console.log(`===== DASH_LIVE DEBUG START ====
|
|
180
180
|
`,s.map(({time:o,data:c,stack:h})=>`${o}: ${JSON.stringify(c)}${h?`
|
|
181
181
|
`+h:""}`).join(`
|
|
182
182
|
`),`
|
|
183
|
-
===== DASH_LIVE DEBUG END ====`),n){let o=s.reduce((c,{time:h,data:d,stack:l})=>{let p=Object.entries(d).map(([m,f])=>`${m}:${f}`).join(",");return c+=`${h}: ${p}${l?`: ${l}`:""};`,c},"");Eg.push("core",{key:"vp_dash_live_debug",strings:[o]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(C({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{C({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let a=this.current$.getValue().destination,n={error:s,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=s.category===Sn.NETWORK,c=s.category===Sn.FATAL,h=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!c,l=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,p=h&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:h,tryFailover:p,canReinitProvider:d},d?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",pu(n)):this.tracer.error("providerError",pu(n))})),e}};import{fromEvent as vn,once as kg,combine as xg,Subscription as $l,ValueSubject as mu,map as Ml,filter as Pg,isNonNullable as yn,now as _e,safeStorage as fu}from"@vkontakte/videoplayer-shared/evergreen";var Ag=5e3,Rl="one_video_throughput",Ll="one_video_rtt",qs=window.navigator.connection,Dl=()=>{let u=qs?.downlink;if(yn(u)&&u!==10)return u*1e3},Bl=()=>{let u=qs?.rtt;if(yn(u)&&u!==3e3)return u},Cl=(u,e,t)=>{let i=t*8,r=i/u;return i/(r+e)},bu=class u{constructor(e){this.subscription=new $l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=u.load(Rl)||(e.useBrowserEstimation?Dl():void 0)||Ag,i=u.load(Ll)??(e.useBrowserEstimation?Bl():void 0)??0;if(this.throughput$=new mu(t),this.rtt$=new mu(i),this.rttAdjustedThroughput$=new mu(Cl(t,i,e.rttPenaltyRequestSize)),this.throughput=vt.getSmoothedValue(t,-1,e),this.rtt=vt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Dl();a&&this.throughput.next(a);let n=Bl();yn(n)&&this.rtt.next(n)};qs&&"onchange"in qs&&this.subscription.add(vn(qs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{fu.set(Rl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{fu.set(Ll,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Ml(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(xg({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Ml(({throughput:r,rtt:s})=>Cl(r,s,e.rttPenaltyRequestSize)),Pg(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 $l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(vn(e,"progress").pipe(kg()).subscribe(s=>{t=s.loaded,i=_e()}));break;case 1:case 0:r.add(vn(e,"loadstart").subscribe(()=>{t=0,i=_e()}));break}r.add(vn(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=_e(),o=a-t,c=n-i;this.addRawSpeed(o,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=_e(),a=0,n=_e(),o=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let l=_e();if(l-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||l-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=_e()}else a+=d.byteLength;n=_e()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&_e()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,_e()-n,this.concurrentDownloads.size),a=0,n=_e());await i?.read().then(c,o)}};this.concurrentDownloads.add(e),i?.read().then(c,o)}addRawSpeed(e,t,i=1,r=!1){if(u.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=fu.get(e);if(yn(t))return parseInt(t,10)??void 0}},Vl=bu;import{fillWithDefault as $g,VideoQuality as Tn}from"@vkontakte/videoplayer-shared/evergreen";var Ol={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Tn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Tn.Q_720P,trafficSavingLimit:Tn.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:Tn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},Nl=u=>({...$g(u,Ol),configName:[...u.configName??[],...Ol.configName]});import{assertNonNullable as Su,combine as wt,ErrorCategory as In,filter as ue,filterChanged as q,fromEvent as vu,isNonNullable as jl,isNullable as _g,Logger as Ug,map as z,mapTo as Ql,merge as qt,now as En,once as he,Subject as j,Subscription as zl,tap as yu,ValueSubject as M,isHigher as Hg,isInvariantQuality as ql,flattenObject as Wt,throttle as Tu,getTraceSubscriptionMethod as Wl,TracerFactory as jg,InternalsExposure as Qg,getPlayerId as zg,devNull as wn}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Mg,map as Rg,filter as Fl,isNonNullable as Lg}from"@vkontakte/videoplayer-shared/evergreen";var gu=({seekState:u,position$:e})=>Mg(u.stateChangeEnded$.pipe(Rg(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Fl(Lg)),e.pipe(Fl(()=>u.getState().state==="none")));import{assertNonNullable as Dg}from"@vkontakte/videoplayer-shared/evergreen";var _l=u=>{let e=typeof u.container=="string"?document.getElementById(u.container):u.container;return Dg(e,`Wrong container or containerId {${u.container}}`),e};import{filter as Bg,once as Cg}from"@vkontakte/videoplayer-shared/evergreen";var Ul=(u,e,t,i)=>{u!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bg(r=>r.length>0),Cg()).subscribe(r=>{r.find(i)&&e.startTransitionTo(u)}):(u===void 0||t?.getValue().find(i))&&e.startTransitionTo(u)};import{devNull as Vg}from"@vkontakte/videoplayer-shared/evergreen";var Hl=()=>{let u="mediaCapabilities"in navigator?Og:Ng,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Fg).map(async([r,s])=>({codec:r,supported:await u(s)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Vg.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},Og=async u=>{if(!u)return Promise.resolve({supported:!1});let e={["channels"in u?"audio":"video"]:u};return await navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Ng=u=>{if(!u)return Promise.resolve({supported:!1});let e="channels"in u?document.createElement("audio"):document.createElement("video");return Promise.resolve({supported:e.canPlayType(u?.contentType??"")==="probably"})},Fg={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 kn=class{constructor(e={configName:[]},t=jg.createRootTracer(!1),i){this.subscription=new zl;this.logger=new Ug;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willReady$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,fetcherRecoverableError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,manifestRequested$:new j,firstBytesManifest$:new j,manifestReceived$:new j,firstBytesRequested$:new j,firstBytesReceived$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j,fetcherError$:new j,severeStallOccured$:new j};this.experimental={element$:new M(void 0),tuningConfigName$:new M([]),enableDebugTelemetry$:new M(!1),dumpTelemetry:dc,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=Nl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(s=>s.setSuppressErrors(!0)),Object.values(this.events).forEach(s=>s.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new lt(r):new ra(r),this.throughputEstimator=new Vl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Qg("core",zg(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,wn.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let o=Reflect.get(s,a,n);return typeof o!="function"?o:(...c)=>{try{return o.apply(s,c)}catch(h){let d=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),l=`Player.${String(a)}`,p=`Exception calling ${l} (${d.join(", ")})`;throw this.events.fatalError$.next({id:l,category:In.WTF,message:p,thrown:h}),h}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Wt(a)),this.domContainer=_l(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new zs({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?(wn.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Hl())):wn.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(ue(s=>!!s),he()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),vu(document,"visibilitychange").pipe(he()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),wn.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(ue(t=>!!t),he()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Su(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(i=>i.length>0),he()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Ul(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(_g(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(qt(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(hc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),he()).subscribe(()=>{this.initedAt=En(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:In.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(he()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(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(wt({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)=>ql(o)?1:ql(c)?-1:Hg(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let o of a)o.fps&&(n[o.quality]=o.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(ue(a=>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.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(yu(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(wt({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(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(wt({atLiveEdge:wt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:gu({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(),yu(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(wt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:a,position:n,duration:o})=>a&&(Math.abs(o)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),q(),yu(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(gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(qt(e.providerOutput.endedEvent$.pipe(Ql(!0)),e.providerOutput.seekedEvent$.pipe(Ql(!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:In.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(he()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(he()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(he()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(he()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(he()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(he(),z(a=>a??En()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(he(),z(()=>En()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(he(),z(()=>En()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:a})=>a==="playing"),he()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(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(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":o?c?a?d="pip":n?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(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(ue(i=>i.length>0),he()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Qe(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(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;Su(this.providerContainer),Su(e),cc(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>uc(t)),this.providerContainer.current$.subscribe(({type:t})=>Er("provider",t)),e.duration$.subscribe(t=>Er("duration",t)),e.availableVideoTracks$.pipe(ue(t=>!!t.length),he()).subscribe(t=>Er("tracks",t)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe(z(t=>t?.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(t=>this.subscription.add(t)),Er("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=Wl(this.tracer.log.bind(this.tracer)),t=Wl(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(wt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(wt({currentBuffer:this.info.currentBuffer$.pipe(ue(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Tu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(wt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Tu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),ue(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(wt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Tu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),ue(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:In.DOM,message:String(r)})})};this.subscription.add(qt(vu(document,"visibilitychange"),vu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Wt({quality:t,availableTracks:Wt(e),track:Wt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ar()}};import{Subscription as P_,Observable as A_,Subject as $_,ValueSubject as M_,VideoQuality as R_}from"@vkontakte/videoplayer-shared/evergreen";var L_=`@vkontakte/videoplayer-core@${Eu}`;export{pr as ChromecastState,An as HttpConnectionType,A_ as Observable,be as PlaybackState,kn as Player,ta as PredefinedQualityLimits,L_ as SDK_VERSION,$_ as Subject,P_ as Subscription,$n as Surface,Eu as VERSION,M_ as ValueSubject,dt as VideoFormat,R_ as VideoQuality,gh as areValidLiveRecordSources,$ as clientChecker,Jt as isMobile};
|
|
183
|
+
===== DASH_LIVE DEBUG END ====`),n){let o=s.reduce((c,{time:h,data:d,stack:l})=>{let p=Object.entries(d).map(([m,f])=>`${m}:${f}`).join(",");return c+=`${h}: ${p}${l?`: ${l}`:""};`,c},"");wg.push("core",{key:"vp_dash_live_debug",strings:[o]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(C({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{C({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let a=this.current$.getValue().destination,n={error:s,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=s.category===Sn.NETWORK,c=s.category===Sn.FATAL,h=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!c,l=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,p=h&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:h,tryFailover:p,canReinitProvider:d},d?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a??"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",pu(n)):this.tracer.error("providerError",pu(n))})),e}};import{fromEvent as vn,once as kg,combine as xg,Subscription as $l,ValueSubject as mu,map as Ml,filter as Pg,isNonNullable as yn,now as _e,safeStorage as fu}from"@vkontakte/videoplayer-shared/evergreen";var Ag=5e3,Rl="one_video_throughput",Ll="one_video_rtt",qs=window.navigator.connection,Dl=()=>{let u=qs?.downlink;if(yn(u)&&u!==10)return u*1e3},Bl=()=>{let u=qs?.rtt;if(yn(u)&&u!==3e3)return u},Cl=(u,e,t)=>{let i=t*8,r=i/u;return i/(r+e)},bu=class u{constructor(e){this.subscription=new $l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=u.load(Rl)||(e.useBrowserEstimation?Dl():void 0)||Ag,i=u.load(Ll)??(e.useBrowserEstimation?Bl():void 0)??0;if(this.throughput$=new mu(t),this.rtt$=new mu(i),this.rttAdjustedThroughput$=new mu(Cl(t,i,e.rttPenaltyRequestSize)),this.throughput=vt.getSmoothedValue(t,-1,e),this.rtt=vt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Dl();a&&this.throughput.next(a);let n=Bl();yn(n)&&this.rtt.next(n)};qs&&"onchange"in qs&&this.subscription.add(vn(qs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{fu.set(Rl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{fu.set(Ll,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Ml(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(xg({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Ml(({throughput:r,rtt:s})=>Cl(r,s,e.rttPenaltyRequestSize)),Pg(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 $l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(vn(e,"progress").pipe(kg()).subscribe(s=>{t=s.loaded,i=_e()}));break;case 1:case 0:r.add(vn(e,"loadstart").subscribe(()=>{t=0,i=_e()}));break}r.add(vn(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=_e(),o=a-t,c=n-i;this.addRawSpeed(o,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=_e(),a=0,n=_e(),o=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let l=_e();if(l-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||l-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=_e()}else a+=d.byteLength;n=_e()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&_e()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,_e()-n,this.concurrentDownloads.size),a=0,n=_e());await i?.read().then(c,o)}};this.concurrentDownloads.add(e),i?.read().then(c,o)}addRawSpeed(e,t,i=1,r=!1){if(u.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=fu.get(e);if(yn(t))return parseInt(t,10)??void 0}},Vl=bu;import{fillWithDefault as $g,VideoQuality as Tn}from"@vkontakte/videoplayer-shared/evergreen";var Ol={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Tn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Tn.Q_720P,trafficSavingLimit:Tn.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:Tn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},Nl=u=>({...$g(u,Ol),configName:[...u.configName??[],...Ol.configName]});import{assertNonNullable as Su,combine as Et,ErrorCategory as In,filter as ue,filterChanged as q,fromEvent as vu,isNonNullable as jl,isNullable as _g,Logger as Ug,map as Q,mapTo as zl,merge as qt,now as wn,once as he,Subject as j,Subscription as Ql,tap as yu,ValueSubject as M,isHigher as Hg,isInvariantQuality as ql,flattenObject as Wt,throttle as Tu,getTraceSubscriptionMethod as Wl,TracerFactory as jg,InternalsExposure as zg,getPlayerId as Qg,devNull as En}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Mg,map as Rg,filter as Fl,isNonNullable as Lg}from"@vkontakte/videoplayer-shared/evergreen";var gu=({seekState:u,position$:e})=>Mg(u.stateChangeEnded$.pipe(Rg(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Fl(Lg)),e.pipe(Fl(()=>u.getState().state==="none")));import{assertNonNullable as Dg}from"@vkontakte/videoplayer-shared/evergreen";var _l=u=>{let e=typeof u.container=="string"?document.getElementById(u.container):u.container;return Dg(e,`Wrong container or containerId {${u.container}}`),e};import{filter as Bg,once as Cg}from"@vkontakte/videoplayer-shared/evergreen";var Ul=(u,e,t,i)=>{u!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bg(r=>r.length>0),Cg()).subscribe(r=>{r.find(i)&&e.startTransitionTo(u)}):(u===void 0||t?.getValue().find(i))&&e.startTransitionTo(u)};import{devNull as Vg}from"@vkontakte/videoplayer-shared/evergreen";var Hl=()=>{let u="mediaCapabilities"in navigator?Og:Ng,e=requestIdleCallback(async()=>{let t=await Promise.all(Object.entries(Fg).map(async([r,s])=>({codec:r,supported:await u(s)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Vg.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>cancelIdleCallback(e)},Og=async u=>{if(!u)return Promise.resolve({supported:!1});let e={["channels"in u?"audio":"video"]:u};return await navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},Ng=u=>{if(!u)return Promise.resolve({supported:!1});let e="channels"in u?document.createElement("audio"):document.createElement("video");return Promise.resolve({supported:e.canPlayType(u?.contentType??"")==="probably"})},Fg={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 kn=class{constructor(e={configName:[]},t=jg.createRootTracer(!1),i){this.subscription=new Ql;this.logger=new Ug;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willReady$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,fetcherRecoverableError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,manifestRequested$:new j,firstBytesManifest$:new j,manifestReceived$:new j,firstBytesRequested$:new j,firstBytesReceived$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j,fetcherError$:new j,severeStallOccured$:new j};this.experimental={element$:new M(void 0),tuningConfigName$:new M([]),enableDebugTelemetry$:new M(!1),dumpTelemetry:dc,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=Nl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(s=>s.setSuppressErrors(!0)),Object.values(this.events).forEach(s=>s.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new lt(r):new ra(r),this.throughputEstimator=new Vl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new zg("core",Qg(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,En.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,a,n)=>{let o=Reflect.get(s,a,n);return typeof o!="function"?o:(...c)=>{try{return o.apply(s,c)}catch(h){let d=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),l=`Player.${String(a)}`,p=`Exception calling ${l} (${d.join(", ")})`;throw this.events.fatalError$.next({id:l,category:In.WTF,message:p,thrown:h}),h}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Wt(a)),this.domContainer=_l(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Qs({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(En.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Hl())):En.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(ue(s=>!!s),he()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),vu(document,"visibilitychange").pipe(he()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),En.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(ue(t=>!!t),he()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof lt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Su(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(i=>i.length>0),he()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Ul(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(_g(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(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),he()).subscribe(()=>{this.initedAt=wn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:In.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(he()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Et({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(o=>n?n.id===o.streamId:!0).map(({quality:o})=>o).sort((o,c)=>ql(o)?1:ql(c)?-1:Hg(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let o of a)o.fps&&(n[o.quality]=o.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(ue(a=>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.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(Q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(Q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(yu(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Et({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(a=>a.to),q(),Q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(Et({atLiveEdge:Et({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:n,isLowLatency:o})=>{let c=this.getActiveLiveDelay(o);return a&&Math.abs(n)<c/1e3}),q(),yu(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(Et({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:n,duration:o})=>a&&(Math.abs(o)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),q(),yu(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(a=>a.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(a=>a.volume),q()).subscribe(this.info.volume$)).add(gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(qt(e.providerOutput.endedEvent$.pipe(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(Q(a=>({id:a?`No${a}`:"NoProviders",category:In.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(he()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(he()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(he()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(he()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(he()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(he(),Q(a=>a??wn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(he(),Q(()=>wn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(he(),Q(()=>wn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:a})=>a==="playing"),he()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let a=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return a&&!n}),q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":o?c?a?d="pip":n?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Ql;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(i=>i.length>0),he()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=ze(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Su(this.providerContainer),Su(e),cc(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>uc(t)),this.providerContainer.current$.subscribe(({type:t})=>wr("provider",t)),e.duration$.subscribe(t=>wr("duration",t)),e.availableVideoTracks$.pipe(ue(t=>!!t.length),he()).subscribe(t=>wr("tracks",t)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(t=>this.subscription.add(t)),wr("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=Wl(this.tracer.log.bind(this.tracer)),t=Wl(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(Et({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Et({currentBuffer:this.info.currentBuffer$.pipe(ue(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Tu(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(Et({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Tu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),ue(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),ue(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Et({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Tu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),ue(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:In.DOM,message:String(r)})})};this.subscription.add(qt(vu(document,"visibilitychange"),vu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Wt({quality:t,availableTracks:Wt(e),track:Wt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ar()}};import{Subscription as P_,Observable as A_,Subject as $_,ValueSubject as M_,VideoQuality as R_}from"@vkontakte/videoplayer-shared/evergreen";var L_=`@vkontakte/videoplayer-core@${wu}`;export{pr as ChromecastState,An as HttpConnectionType,A_ as Observable,be as PlaybackState,kn as Player,ta as PredefinedQualityLimits,L_ as SDK_VERSION,$_ as Subject,P_ as Subscription,$n as Surface,wu as VERSION,M_ as ValueSubject,dt as VideoFormat,R_ as VideoQuality,gh as areValidLiveRecordSources,$ as clientChecker,Jt as isMobile};
|