@vkontakte/videoplayer-core 2.0.166-dev.2d0cf8810.0 → 2.0.166-dev.abb27aca7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +5 -5
- package/es2015.esm.js +6 -6
- package/esnext.cjs +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
package/esnext.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.166-dev.
|
|
3
|
-
* Thu, 02 Jul 2026
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.166-dev.abb27aca7.0
|
|
3
|
+
* Thu, 02 Jul 2026 09:03:09 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-166/doc/
|
|
5
5
|
*/
|
|
6
|
-
var e=`2.0.166-dev.2d0cf8810.0`,t;(e=>{e.STOPPED=`stopped`,e.READY=`ready`,e.PLAYING=`playing`,e.PAUSED=`paused`})(t||={});var n;(e=>{e.MPEG=`MPEG`,e.DASH=`DASH`,e.DASH_SEP=`DASH_SEP`,e.DASH_SEP_VK=`DASH_SEP`,e.DASH_WEBM=`DASH_WEBM`,e.DASH_WEBM_AV1=`DASH_WEBM_AV1`,e.DASH_STREAMS=`DASH_STREAMS`,e.DASH_WEBM_VK=`DASH_WEBM`,e.DASH_ONDEMAND=`DASH_ONDEMAND`,e.DASH_ONDEMAND_VK=`DASH_ONDEMAND`,e.DASH_LIVE=`DASH_LIVE`,e.DASH_LIVE_CMAF=`DASH_LIVE_CMAF`,e.DASH_LIVE_WEBM=`DASH_LIVE_WEBM`,e.HLS=`HLS`,e.HLS_ONDEMAND=`HLS_ONDEMAND`,e.HLS_JS=`HLS`,e.HLS_FMP4=`HLS_FMP4`,e.HLS_LIVE=`HLS_LIVE`,e.HLS_LIVE_CMAF=`HLS_LIVE_CMAF`,e.WEB_RTC_LIVE=`WEB_RTC_LIVE`})(n||={});var r;(e=>{e.AV1=`av1`,e.VP9=`vp9`,e.AVC1=`avc1`,e.HEV1=`hev1`})(r||={});var i;(e=>{e.NOT_AVAILABLE=`NOT_AVAILABLE`,e.AVAILABLE=`AVAILABLE`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`})(i||={});var a;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.QUIC=`quic`})(a||={});var o;(e=>{e.NONE=`none`,e.INLINE=`inline`,e.FULLSCREEN=`fullscreen`,e.SECOND_SCREEN=`second_screen`,e.PIP=`pip`,e.INVISIBLE=`invisible`})(o||={});var s;(e=>{e.TRAFFIC_SAVING=`traffic_saving`,e.HIGH_QUALITY=`high_quality`,e.UNKNOWN=`unknown`})(s||={});import{assertNever as c,assertNonNullable as l,isNonNullable as u,ValueSubject as d,Subject as f,Subscription as p,merge as m,observableFrom as h,fromEvent as g,map as _,tap as v,filterChanged as y,isNullable as b,ErrorCategory as x}from"@vkontakte/videoplayer-shared";var S=e=>new Promise((t,n)=>{let r=document.createElement(`script`);r.setAttribute(`src`,e),r.onload=()=>t(),r.onerror=e=>n(e),document.body.appendChild(r)});class C{connection$=new d(void 0);castState$=new d(`NOT_AVAILABLE`);errorEvent$=new f;contentId;realCastState$=new d(`NOT_AVAILABLE`);subscription=new p;log;params;isDestroyed=!1;constructor(e){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 n=u(window.chrome?.cast),r=!!window.__onGCastApiAvailable;n?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&!this.isDestroyed&&this.initializeCastApi()},r||S(`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`).catch(()=>this.errorEvent$.next({id:`ChromecastLoading`,category:x.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(){u(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();b(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();b(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),n=cast.framework.CastContext.getInstance();this.subscription.add(g(n,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(e=>{switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=n.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 c(e.sessionState)}})).add(m(g(n,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(v(e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})}),_(e=>e.castState)),h([n.getCastState()])).pipe(y(),_(w),v(e=>{this.log({message:`realCastState$: ${e}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let i=r===`CONNECTED`,a=u(this.connection$.getValue());if(i&&!a){let r=n.getCurrentSession();l(r);let i=r.getCastDevice(),a=r.getMediaSession()?.media?.contentId;(b(a)||a===this.contentId)&&(this.log({message:`connection created`}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:r,castDevice:i}))}else!i&&a&&(this.log({message:`connection destroyed`}),this.connection$.next(void 0));this.castState$.next(r===`CONNECTED`?u(this.connection$.getValue())?`CONNECTED`:`AVAILABLE`:r)}))}initializeCastApi(){let e,t,n;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,n=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:n}),this.initListeners()}catch(e){this.errorEvent$.next({id:`ChromecastInitializer`,category:x.EXTERNAL_API,message:`[initializeCastApi] failed`,thrown:e})}}}var w=e=>{switch(e){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 c(e)}};import{assertNonNullable as T,combine as E,debounce as ee,ErrorCategory as te,filter as D,filterChanged as ne,isNonNullable as re,isNullable as ie,map as ae,Subscription as oe,ValueSubject as se}from"@vkontakte/videoplayer-shared";import{assertNever as ce,assertNonNullable as le,ErrorCategory as ue,getHighestQuality as de,isNonNullable as fe}from"@vkontakte/videoplayer-shared";import{assertNever as pe}from"@vkontakte/videoplayer-shared";var O=(e,t=0,n=0)=>{switch(n){case 0:return e.replace(`_offset_p`,t===0?``:`_`+t.toFixed(0));case 1:{if(t===0)return e;let n=new URL(e);return n.searchParams.append(`playback_shift`,t.toFixed(0)),n.toString()}case 2:{let n=new URL(e);return!n.searchParams.get(`offset_p`)&&t===0?e:(n.searchParams.set(`offset_p`,t.toFixed(0)),n.toString())}default:pe(n)}return e},me=(e,t)=>{switch(t){case 0:return NaN;case 1:{let t=new URL(e);return Number(t.searchParams.get(`playback_shift`))}case 2:{let t=new URL(e);return Number(t.searchParams.get(`offset_p`)??0)}default:pe(t)}},he=e=>{let{source:t,format:n,meta:r,output:i}=e,a,o,s;switch(n){case`MPEG`:{let e=t[n];le(e);let r=de(Object.keys(e));le(r);let i=e[r];le(i),a=i,o=`video/mp4`,s=ge();break}case`HLS`:case`HLS_FMP4`:case`HLS_ONDEMAND`:{let e=t[n];le(e),a=e.url,o=`application/x-mpegurl`,s=ge();break}case`DASH_SEP`:case`DASH_ONDEMAND`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_STREAMS`:{let e=t[n];le(e),a=e.url,o=`application/dash+xml`,s=ge();break}case`DASH_LIVE_CMAF`:{let e=t[n];le(e),a=e.url,o=`application/dash+xml`,s=_e();break}case`HLS_LIVE`:case`HLS_LIVE_CMAF`:{let e=t[n];le(e),a=O(e.url),o=`application/x-mpegurl`,s=_e();break}case`DASH_LIVE`:case`WEB_RTC_LIVE`:{let e=`Unsupported format for Chromecast`,t=Error(e);throw i.error$.next({id:`ChromecastProvider.createMediaInfo()`,category:ue.VIDEO_PIPELINE,message:e,thrown:t}),t}case`DASH`:case`DASH_LIVE_WEBM`:throw Error(`${n} is no longer supported`);default:return ce(n)}let c=ve(r.videoId??a,o);c.contentUrl=a,c.streamType=s,c.metadata=ye();let{title:l,subtitle:u}=r;return fe(l)&&(c.metadata.title=l),fe(u)&&(c.metadata.subtitle=u),c};function ge(){return chrome.cast?.media?.StreamType?.BUFFERED??`BUFFERED`}function _e(){return chrome.cast?.media?.StreamType?.LIVE??`LIVE`}function ve(e,t){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(e,t):{contentId:e,contentType:t,metadata:{title:``,subtitle:``},streamType:ge()}}function ye(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:``,subtitle:``,title:``,releaseYear:1970,type:0}}var k=(e,t,n=!1)=>{let r=e.getTransition();(n||!r||r.to===t)&&e.setState(t)};class be{params;interval=0;startVideoPosition;startTs;constructor(e){this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let e=(Date.now()-this.startTs)/1e3,t=this.startVideoPosition+e;this.params.output.position$.next(t)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}}import{assertNever as xe}from"@vkontakte/videoplayer-shared";import{isBrowserWindow as Se,ValueSubject as Ce}from"@vkontakte/videoplayer-shared";import{getWindow as we}from"@vkontakte/videoplayer-shared";class Te{_current;_current_version;_chromeVersion;_firefoxVersion;_safariVersion;_operaVersion;_edgeVersion;_yandexVersion;_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,n=/samsungbrowser/i.test(e)?`SamsungBrowser`:void 0,r=/chrome|crios/i.test(e)?`Chrome`:void 0,i=/chromium/i.test(e)?`Chromium`:void 0,a=/firefox|fxios/i.test(e)?`Firefox`:void 0,o=/webkit|safari|khtml/i.test(e)?`Safari`:void 0,s=/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||n||a||s||c||r||i||o||`Rest`}catch(e){console.error(e)}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}=we().navigator,n=t.match(e);if(!n)return;let r=n[1],i=parseInt(r,10);if(!isNaN(i))return this._current_version=i,i}catch(e){console.error(e)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}}import{getWindow as Ee,isBrowserWindow as De}from"@vkontakte/videoplayer-shared";var Oe=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;class ke{_displayChecker;_isMobile;_current;_iosVersion;_highEntropyValues={};_os={name:`Unknown`,version:`Unknown`,full:`Unknown`};_details={vendor:`Unknown`,model:`Unknown`};constructor(e){this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){return this._highEntropyValues.platform===`iOS`||this.os.name.toLowerCase().includes(`ios`)||[`iPhone`,`iPad`,`iPod`].includes(this.current)}get isMac(){return this._highEntropyValues.platform===`macOS`||this.os.name.toLowerCase().includes(`mac`)||this.current===`Mac`}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current===`iPad`||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform===`Android`||this.os.name.toLowerCase().includes(`android`)||this.current===`Android`}get isWindows(){return this.os.name.toLowerCase().includes(`windows`)}get isLinux(){return this.os.name.toLowerCase().includes(`linux`)&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=Ee();if(!De(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Oe()}catch(e){console.error(`DeviceChecker: calling isMobile error - `,e)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=Ee();if(!De(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let e=await t.getHighEntropyValues([`architecture`,`bitness`,`brands`,`mobile`,`platform`,`formFactor`,`model`,`platformVersion`,`wow64`]);this._highEntropyValues=e,e.platform&&(this._os.name=this.normalizeOSName(e.platform),e.platformVersion&&(this._os.version=this.normalizeOSVersion(e.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),e.model&&(this._details.model=e.model)}}detectDevice(e){try{let t=/android/i.test(e)?`Android`:void 0,n=/iphone/i.test(e)?`iPhone`:void 0,r=/ipad/i.test(e)?`iPad`:void 0,i=/ipod/i.test(e)?`iPod`:void 0,a=/mac/i.test(e)?`Mac`:void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?`RestMobile`:void 0;this._current=t||n||r||i||o||a||`Desktop`}catch(e){console.error(`DeviceChecker: device detection error - `,e)}}detectOS(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let t=n.length>0,i=n.length>1,a=`Unknown`,o=`Unknown`;if(t){let e=n[0];typeof e==`number`?e<r.length&&r[e]!==void 0&&(a=r[e]):a=e}if(i){let e=n[1];typeof e==`number`?e<r.length&&r[e]!==void 0&&(o=r[e]):e!==void 0&&(o=e)}else r[2]===void 0?r[1]!==void 0&&t&&typeof n[0]==`string`&&(o=r[1]):o=r[2];a=this.normalizeOSName(a),o=this.normalizeOSVersion(o,a),a===`iOS`&&/ipad/i.test(e)?a=`iPadOS`:a===`iPadOS`&&/ip(hone|od)/i.test(e)&&(a=`iOS`),this._os={name:a,version:o||`Unknown`,full:o&&o!==`Unknown`?`${a} ${o}`:a};break}}}catch(e){console.error(`DeviceChecker: OS detection error - `,e)}}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 t=parseFloat(e);if(!isNaN(t)){if(t>=11)return`11`;if(t>=10)return`10`;if(t===6.3)return`8.1`;if(t===6.2)return`8`;if(t===6.1)return`7`;if(t===6)return`Vista`;if(t===5.1||t===5.2)return`XP`;if(t===5)return`2000`;if(t===4)return`NT 4.0`}}return e}detectDeviceDetails(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let e=n[0],t=n[1],i=typeof e==`number`?r[e]===void 0?`Unknown`:this.normalizeVendorName(r[e]):this.normalizeVendorName(e),a=`Unknown`;typeof t==`number`?a=r[t]===void 0?`Unknown`:r[t]:t===void 0?r[1]===void 0?r[0]!==void 0&&(a=r[0]):a=r[1]:a=t,a=this.normalizeModelName(a,i),this.details.vendor=i,this.details.model=a;break}}}catch(e){console.error(`DeviceChecker: device details detection error - `,e)}}normalizeVendorName(e){return e?{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`}[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():`Unknown`}normalizeModelName(e,t){if(!e||e===`Unknown`)return e;if(e===`0`)return`Unknown`;let n=e.replace(/^build\//i,``).replace(/\s+bui$/i,``).replace(/\)$/,``).replace(/[;,)]/g,``).replace(/\s*\(.*?\)\s*/g,``).trim(),r=t.toLowerCase();return r.includes(`samsung`)?n=n.replace(/^(sm-|gt-|sgh-|sch-)/i,``):r.includes(`xiaomi`)?n=n.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,``):r.includes(`oneplus`)?n=n.replace(/^oneplus[\s\-_]*/i,``):r.includes(`google`)&&(n=n.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,``)),n=n.replace(/_/g,` `).replace(/-/g,` `).replace(/\s+/g,` `).trim(),n?(n.length>0&&/^[a-z]/.test(n)&&(n=n.charAt(0).toUpperCase()+n.slice(1)),n):`Unknown`}detectIOSVersion(){try{let e=Ee();if(!De(e))return;if(this._highEntropyValues.platformVersion){let e=this._highEntropyValues.platformVersion.split(`.`).slice(0,2).join(`.`);this._iosVersion=parseFloat(e);return}if(this._os.version!==`Unknown`){let e=this._os.version.split(`.`),t=e.length>=2?`${e[0]}.${e[1]}`:e[0];this._iosVersion=parseFloat(t);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,`.`)))}catch(e){console.error(`DeviceChecker: iOS version detection error - `,e)}}}import{getWindow as Ae,isBrowserWindow as je}from"@vkontakte/videoplayer-shared";class Me{_maxTouchPoints;_height;_width;_isHdr;_pixelRatio;_screenHeight;_screenWidth;_colorDepth;get isTouch(){return typeof this._maxTouchPoints==`number`?this._maxTouchPoints>1:`ontouchstart`in Ae()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let e=Ae();if(!je(e))return;let{navigator:t,screen:n}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia(`(dynamic-range: high)`)?.matches,this._colorDepth=n.colorDepth}catch(e){console.error(e)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=n.height,this._width=n.width,this._height=n.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(e){console.error(e)}}}import{getWindow as Ne,isBrowserWindow as Pe}from"@vkontakte/videoplayer-shared";var Fe=()=>window.ManagedMediaSource||window.MediaSource,Ie=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Le=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Re=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,ze=Ne().document?.createElement(`video`),Be=`video/mp4; codecs="avc1.42000a,mp4a.40.2"`,Ve=`video/mp4; codecs="hev1.1.6.L93.B0"`,He=`video/webm; codecs="vp09.00.10.08"`,Ue=`video/webm; codecs="av01.0.00M.08"`,We=`audio/mp4; codecs="mp4a.40.2"`,Ge=`audio/webm; codecs="opus"`,Ke;(async()=>{let e=Ne();if(!Pe(e)||!(`mediaCapabilities`in e.navigator))return;let t={type:`media-source`,video:{contentType:`video/webm`,width:1280,height:720,bitrate:1e6,framerate:30}},[n,r]=await Promise.all([e.navigator.mediaCapabilities.decodingInfo({...t,video:{...t.video,contentType:Ue}}),e.navigator.mediaCapabilities.decodingInfo({...t,video:{...t.video,contentType:He}})]);Ke={DASH_WEBM_AV1:n,DASH_WEBM:r}})().catch(e=>{console.log(ze),console.error(e)});class qe{_video;_deviceChecker;_browserChecker;_protocols;_containers;_codecs;_nativeHlsSupported;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 Ke}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=Ne();if(!Pe(e))return;let t=e.document;this._video=t.createElement(`video`);try{this._protocols={mms:Ie(),mse:Le(),hls:!!(this._video.canPlayType?.(`application/x-mpegurl`)||this._video.canPlayType?.(`vnd.apple.mpegURL`)),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.(`video/mp4`),webm:!!this._video.canPlayType?.(`video/webm`),cmaf:!0};let t=!!Fe()?.isTypeSupported?.(Be),n=!!Fe()?.isTypeSupported?.(Ve),r=!!Fe()?.isTypeSupported?.(We);this._codecs={h264:t,h265:n,vp9:!!Fe()?.isTypeSupported?.(He),av1:!!Fe()?.isTypeSupported?.(Ue),aac:r,opus:!!Fe()?.isTypeSupported?.(Ge),mpeg:(t||n)&&r},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}}import{getWindow as Je,isBrowserWindow as Ye}from"@vkontakte/videoplayer-shared";var Xe=`audio/mpeg`;class Ze{_audio;_containers;_codecs;supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=Je();if(!Ye(e))return;let t=e.document;this._audio=t.createElement(`audio`);try{this._containers={mpeg:!!this._audio.canPlayType?.(Xe)},this._codecs={mp3:!!Fe()?.isTypeSupported?.(Xe)}}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}}class Qe{isInited$=new Ce(!1);_displayChecker;_deviceChecker;_browserChecker;_videoChecker;_audioChecker;constructor(){this._displayChecker=new Me,this._deviceChecker=new ke(this._displayChecker),this._browserChecker=new Te,this._videoChecker=new qe(this._deviceChecker,this._browserChecker),this._audioChecker=new Ze,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(){Se()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}}var A=new Qe,$e=(e,t=!1)=>{let{containers:n,protocols:r,codecs:i,nativeHlsSupported:a}=A.video,{isMobile:o}=A.device,s=A.device.isMac&&A.browser.isSafari,c=t&&!o&&!s,l=(i.h264||i.h265)&&i.aac,u=r.mse||r.mms;return e.filter(e=>{switch(e){case`DASH_SEP`:return u&&n.mp4&&l;case`DASH_WEBM`:return u&&n.webm&&i.vp9&&i.opus;case`DASH_WEBM_AV1`:return u&&n.webm&&i.av1&&i.opus;case`DASH_STREAMS`:return u&&(n.mp4&&l||n.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case`DASH_LIVE`:return u&&n.mp4&&l;case`DASH_LIVE_CMAF`:return u&&n.mp4&&l&&n.cmaf;case`DASH_ONDEMAND`:return u&&n.mp4&&l;case`HLS`:case`HLS_ONDEMAND`:case`HLS_FMP4`:case`HLS_LIVE`:case`HLS_LIVE_CMAF`:return a&&!c;case`MPEG`:return n.mp4;case`DASH`:case`DASH_LIVE_WEBM`:return!1;case`WEB_RTC_LIVE`:return r.webrtc&&r.ws&&i.h264&&(n.mp4||n.webm);default:return xe(e)}})},et=e=>{switch(e){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 xe(e)}},tt=(e,t=!1)=>$e(Object.keys(e).filter(e=>!et(e)),t).length>0;class nt{subscription=new oe;log;params;sessionId$=new se(null);mediaSessionId$=new se(null);contentId$=new se(null);progressTicker;isMobile=Oe();mobileVolumeState={muted:!1,volume:0};media=null;lastRequestedVolume=null;constructor(e){this.params=e,this.progressTicker=new be(e),this.log=this.params.dependencies.logger.createComponentLog(`ChromecastPresentationApiProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(et(e.format)),this.subscribe()}subscribe(){let e=e=>{this.params.output.error$.next({category:te.WTF,id:`ChromecastPresentationApiProvider`,message:e?.message??`Unknown error`,thrown:e})};this.subscription.add(this.params.chromecastConnector.message$.pipe(D(e=>!!e)).subscribe(e=>{this.handleMessage(e)},e)),this.subscription.add(this.sessionId$.pipe(D(re),ne(),ee(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(ne(),ae(Boolean));this.subscription.add(E({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(D(({mediaLoaded:e})=>e)).subscribe(()=>{let e=this.params.desiredState.seekState.getState();e.state===`requested`&&this.seek(e.position/1e3)},e));let n=E({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(n.pipe(D(({mediaLoaded:e})=>e),ee(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(n.pipe(D(({mediaLoaded:e,playbackState:{from:t,to:n}})=>!e&&t===`stopped`&&n===`playing`)).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(E({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ee(30)),mediaLoaded:t}).pipe(D(({mediaLoaded:e})=>e)).subscribe(({volumeState:e})=>{let{muted:t,volume:n}=e.to;this.setVolume(n,t)},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 n=e.message?.receiver.volume;this.syncVolumeState(n)}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=he(this.params),t=this.media?.currentTime,n=this.params.desiredState.seekState.getState(),r=t??(n.state===`none`?0:n.position/1e3),i=this.params.desiredState.playbackState.getState()===`playing`;this.params.chromecastConnector.sendV2Message({type:`LOAD`,requestId:0,media:e,autoplay:i,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();T(e,`play on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PLAY`,mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();T(e,`pause on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PAUSE`,mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();T(t,`seek on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`SEEK`,currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let n=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(n=this.mobileVolumeState.volume,r+=`, mobile next volume: ${n}`),this.log({message:r}),this.lastRequestedVolume={volume:n,muted:t},this.params.chromecastConnector.sendV2Message({type:`SET_VOLUME`,requestId:0,volume:{level:t?0:n,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let n=this.params.output.isBuffering$.getValue(),r=e===`BUFFERING`;switch(n!==r&&this.params.output.isBuffering$.next(r),e){case`PAUSED`:k(this.params.desiredState.playbackState,`paused`);break;case`PLAYING`:k(this.params.desiredState.playbackState,`playing`);break;case`IDLE`:t===`FINISHED`?(this.params.output.endedEvent$.next(),k(this.params.desiredState.playbackState,`stopped`),this.contentId$.next(null)):k(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}}syncMediaState=e=>{if(ie(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 n=e.media?.duration;re(n)&&this.params.output.duration$.next(Math.max(0,n));let r=e.currentTime;if(re(r)){this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let t=this.params.output.isLive$.getValue();e.playerState===`PLAYING`&&!t?this.progressTicker.start(r):this.progressTicker.pause()}};syncVolumeState(e){if(ie(e))return;let{level:t,muted:n}=e,r={muted:n??!1,volume:t??0};this.lastRequestedVolume&&=(n&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!n&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),null);let i=`[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,i+=`, volume passed to state machine: ${r.volume}`),this.log({message:i}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}}import{assertNonNullable as rt,ErrorCategory as it,filter as at,Subject as ot,Subscription as st,tap as ct,ValueSubject as lt,fromEvent as ut,getWindow as dt}from"@vkontakte/videoplayer-shared";var ft=e=>({castDevice:{friendlyName:e},remotePlayer:{},remotePlayerController:{},session:{}}),pt=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));class mt{params;clientId;capabilities=[`WEB`];presentationRequest$=new lt(null);log;sessionId$=new lt(null);broadcastChannel=new BroadcastChannel(`vk_player_chromecast_events`);subscription=new st;subscriptionEvents=new st;isDestroyed=!1;sequenceNumber=0;presentationAvailable$=new lt(!1);presentationConnection$=new lt(null);message$=new lt(null);friendlyName$=new lt(null);errorEvent$=new ot;constructor(e){this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog(`ChromecastPresentationApiConnector`),this.log({message:`constructor`}),this.safeReinitPresentation(),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(),n=new PresentationRequest(t);this.presentationRequest$.next(n),this.log({message:`PresentationRequest created`}),n.getAvailability().then(e=>{let t=()=>{this.log({message:`PresentationRequest presentation availability: ${e.value}`}),this.presentationAvailable$.next(e.value)};this.subscriptionEvents.add(ut(e,`change`).subscribe(()=>{t()})),t()}).catch(()=>{this.presentationAvailable$.next(!0)}),dt().navigator.presentation.defaultRequest=n,e&&n.reconnect(`auto-join`).then(e=>{this.log({message:`PresentationRequest reconnect success`}),this.handleConnection(e)}).catch(()=>{this.log({message:`PresentationRequest reconnect failed`})})}safeReinitPresentation(e){try{this.reinitPresentation(e)}catch(e){this.errorEvent$.next({category:it.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`reinitPresentation error`,thrown:e})}}async connect(){this.log({message:`connect`});try{this.presentationRequest$.getValue()||(this.log({message:`reinitPresentation`}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();rt(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:it.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`connect error`,thrown:e});break}}}subscribe(){this.subscription.add(ut(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(ct(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),at(e=>!!e)).subscribe(e=>{let t=ut(e,`message`).subscribe(e=>{let t=JSON.parse(e.data);t.clientId===this.clientId&&(this.log({message:`[onmessage] ${e.data}`}),this.handleMessage(t),this.message$.next(t))}),n=ut(e,`connect`).subscribe(()=>{this.send(`client_connect`)}),r=ut(e,`close`).subscribe(e=>{switch(e.reason){case`error`:this.errorEvent$.next({category:it.WTF,id:`ChromecastPresentationApiConnector`,message:`Session error`,thrown:e});break;case`closed`:break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(n),this.subscriptionEvents.add(r)}))}send(e){switch(e){case`client_connect`:{let e={type:`client_connect`,message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(e));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let n={type:`v2_message`,sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(n))}}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:it.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)%(2**53-1),e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e=`__vk_player_chromecast_id`;return dt()[e]=dt()[e]||pt()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new st}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 ht,Subject as gt,map as _t,Subscription as vt,combine as yt,filterChanged as bt,assertNonNullable as xt}from"@vkontakte/videoplayer-shared";class St{subscription=new vt;log;contentId;connection$=new ht(void 0);castState$=new ht(`NOT_AVAILABLE`);errorEvent$=new gt;chromecastConnector;static isSupported(){return`chrome`in window&&`presentation`in navigator&&`BroadcastChannel`in window}constructor(e){let t=St.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 mt({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}subscribe(){xt(this.chromecastConnector,`subscribe with null chromecastConnector`),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=yt({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(bt())});this.subscription.add(e.pipe(_t(({connection:e,friendlyName:t})=>!!(e&&t)),bt()).subscribe(e=>{let t=this.chromecastConnector?.friendlyName$.getValue()??``;this.connection$.next(e?ft(t):void 0)})).add(e.subscribe(({available:e,connection:t})=>{e?t?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 Ct,Subject as wt,merge as Tt}from"@vkontakte/videoplayer-shared";var Et=(e,t)=>e===t;class Dt{comparator;state;prevState;transition;transitionStarted$=new wt;transitionEnded$=new wt;transitionUpdated$=new wt;forceChanged$=new wt;stateChangeStarted$=Tt(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=Tt(this.transitionEnded$,this.forceChanged$);constructor(e,t=Et){this.comparator=t,this.state=e,this.prevState=void 0}setState(e){let t=this.transition,n=this.state;this.transition=void 0,this.prevState=n,this.state=e,t?this.comparator(t.to,e)?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:n,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,n=this.state;this.comparator(n,e)||Ct(t)&&this.comparator(t.to,e)||(this.prevState=n,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:n,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}import{assertNever as Ot,debounce as kt,ErrorCategory as At,fromEvent as jt,map as Mt,merge as Nt,observableFrom as Pt,Subject as Ft,Subscription as It,timeout as Lt}from"@vkontakte/videoplayer-shared";var Rt=5,zt=5,Bt=500,Vt=7e3;class Ht{subscription=new It;loadMediaTimeoutSubscription=new It;videoState=new Dt(`stopped`);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`ChromecastProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(et(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 It;this.subscription.add(e),this.subscription.add(Nt(this.videoState.stateChangeStarted$.pipe(Mt(e=>`stateChangeStarted$ ${JSON.stringify(e)}`)),this.videoState.stateChangeEnded$.pipe(Mt(e=>`stateChangeEnded$ ${JSON.stringify(e)}`))).subscribe(e=>this.log({message:`[videoState] ${e}`})));let t=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let t=new Ft;e.add(t.pipe(kt(Bt)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(e=>{this.logRemoteEvent(e);let r=e.value;this.params.output.position$.next(r),(this.params.desiredState.seekState.getState().state===`applying`||Math.abs(r-n)>Rt)&&t.next(r),n=r})),e.add(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)}))}t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),e=>{this.logRemoteEvent(e);let{remotePlayer:t}=this.params.connection,n=e.value,r=this.params.output.isBuffering$.getValue(),i=n===chrome.cast.media.PlayerState.BUFFERING;switch(r!==i&&this.params.output.isBuffering$.next(i),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&t.duration-t.currentTime<zt&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:Ot(n)}}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}),t(Nt(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Pt([`init`])).pipe(kt(0)),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`),k(this.params.desiredState.playbackState,`paused`)):(this.videoState.setState(`playing`),k(this.params.desiredState.playbackState,`playing`));let e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:`none`})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=he(this.params),n=this.createLoadRequest(t);this.loadMedia(n)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`paused`||e===`playing`)&&(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`playing`||e===`paused`)&&(this.videoState.setState(`playing`),k(this.params.desiredState.playbackState,`playing`))}handleRemoteReady(){this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.params.desiredState.playbackState.getTransition()?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`)}handleRemoteStop(){this.videoState.getState()!==`stopped`&&this.videoState.setState(`stopped`)}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),n={volume:e.volume??t.volume,muted:e.muted??t.muted};(n.volume!==t.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:n}=this.params.connection;t.currentTime=e,n.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let n=this.params.desiredState.seekState.getState();return n.state===`applying`||n.state===`requested`?t.currentTime=this.params.output.isLive$.getValue()?0:n.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),n=new Promise((e,t)=>{this.loadMediaTimeoutSubscription.add(Lt(Vt).subscribe(()=>t(`timeout(${Vt})`)))});Promise.race([t,n]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},e=>{let t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:`ChromecastProvider.loadMedia`,category:At.VIDEO_PIPELINE,message:t,thrown:e})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.stop());return}if(!t){if(r?.to!==`paused`&&i.state===`requested`&&e!==`stopped`){this.seek(i.position/1e3);return}switch(n){case`ready`:switch(e){case`playing`:case`paused`:case`ready`:break;case`stopped`:this.videoState.startTransitionTo(`ready`),this.prepare();break;default:Ot(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:Ot(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:Ot(e)}break;default:Ot(n)}}}}import{clearVideoElement as Ut,fromEvent as Wt,getWindow as Gt,Subscription as Kt}from"@vkontakte/videoplayer-shared";import{clearVideoElement as qt}from"@vkontakte/videoplayer-shared";var Jt=(e,t)=>{try{e.pause(),e.playbackRate=0,qt(e,t),e.remove()}catch(e){console.error(e)}},Yt=`__spvc`;class Xt{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)}}var Zt=Gt(),Qt=Zt.WeakMap?new Zt.WeakMap:new Xt,$t=Zt.WeakMap?new Zt.WeakMap:new Map,en=(e,t=20)=>{let n=0;return Wt(e,`ratechange`).subscribe(r=>{n++,n>=t&&(e.currentTime=e.currentTime,n=0)})};function tn(e){e.style.position=`fixed`,e.style.left=`100%`,e.setAttribute(`data-role`,`screen`),Gt().document.body.appendChild(e)}function nn(e,t){e.style.position=``,e.style.left=``,t.appendChild(e)}var rn=(e,{audioVideoSyncRate:t,disableYandexPiP:n,clearVideoElementInnerHTML:r,reuseOwnVideoElement:i})=>{let a,o=e.querySelector(`video`),s=!!o,c=Gt().document.querySelector(`body > video[data-role=screen]`)||void 0;i?Zt[Yt]=c:(c?.remove(),delete Zt[Yt]),o?(a=o,Ut(a,r)):c&&c===Zt[Yt]?(a=c,nn(a,e)):(a=Gt().document.createElement(`video`),e.appendChild(a),i&&(Zt[Yt]=a)),Qt.set(a,s);let l=new Kt;return l.add(en(a,t)),$t.set(a,l),a.setAttribute(`crossorigin`,`anonymous`),a.setAttribute(`playsinline`,`playsinline`),n&&a.setAttribute(`x-yandex-pip`,`false`),a.controls=!1,a.setAttribute(`poster`,`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`),a},an=e=>(e.setAttribute(`crossorigin`,`anonymous`),e.controls=!1,e),on=(e,t)=>{if(e instanceof HTMLAudioElement){Jt(e,!0);return}if(e instanceof HTMLVideoElement){sn(e,t);return}};function sn(e,{keepVideoElement:t,clearVideoElementInnerHTML:n,reuseOwnVideoElement:r}){$t.get(e)?.unsubscribe(),$t.delete(e);let i=Qt.get(e);Qt.delete(e),i||t?Ut(e,n):r?(Ut(e,n),tn(e)):Jt(e,n)}import{assertNonNullable as cn,isNonNullable as ln,isNullable as un,fromEvent as dn,merge as fn,observableFrom as pn,filterChanged as mn,map as hn,Subject as gn,Subscription as _n,ValueSubject as vn,ErrorCategory as yn}from"@vkontakte/videoplayer-shared";import{isNonNullable as bn,isNullable as xn,Subscription as Sn}from"@vkontakte/videoplayer-shared";var Cn=(e,t,n,{equal:r=(e,t)=>e===t,changed$:i,onError:a}={})=>{let o=e.getState(),s=t(),c=xn(i),l=new Sn;return i&&l.add(i.subscribe(t=>{r(t,e.getState())&&e.setState(t)},a)),r(s,o)||(n(o),c&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe(t=>{n(t.to),c&&e.setState(t.to)},a)),l},wn=(e,t,n)=>Cn(t,()=>e.loop,t=>{bn(t)&&(e.loop=t)},{onError:n}),Tn=(e,t,n,r,i)=>Cn(t,()=>({muted:e.muted,volume:e.volume}),t=>{i?.skipVideoElVolumeSync$.getValue()||bn(t)&&(e.muted=t.muted,e.volume=t.volume)},{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:n,onError:r}),En=(e,t,n,r)=>Cn(t,()=>e.playbackRate,t=>{bn(t)&&(e.playbackRate=t)},{changed$:n,onError:r}),Dn=Cn,On=e=>[`__`,e.language,e.label].join(`|`),kn=(e,t)=>{if(e.id===t)return!0;let[n,r,i]=t.split(`|`);return e.language===r&&e.label===i};class An{available$=new gn;current$=new vn(void 0);error$=new gn;video;cueSettings;subscription=new _n;externalTracks=new Map;internalTracks=new Map;baseURL;constructor(e){this.baseURL=e}connect(e,t,n){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=e=>{this.error$.next({id:`TextTracksManager`,category:yn.WTF,message:`Generic HtmlVideoTextTrackManager error`,thrown:e})};this.subscription.add(this.available$.subscribe(n.availableTextTracks$)),this.subscription.add(this.current$.subscribe(n.currentTextTrack$)),this.subscription.add(this.error$.subscribe(n.error$)),this.subscription.add(Dn(t.internalTextTracks,()=>Object.values(this.internalTracks),e=>{ln(e)&&this.setInternal(e)},{equal:(e,t)=>ln(e)&&ln(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(hn(e=>e.filter(({type:e})=>e===`internal`))),onError:r})),this.subscription.add(Dn(t.externalTextTracks,()=>Object.values(this.externalTracks),e=>{ln(e)&&this.setExternal(e)},{equal:(e,t)=>ln(e)&&ln(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(hn(e=>e.filter(({type:e})=>e===`external`))),onError:r})),this.subscription.add(Dn(t.currentTextTrack,()=>{if(this.video)return;let e=this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`);return e&&this.htmlTextTrackToITextTrack(e).id},e=>this.select(e),{changed$:this.current$,onError:r})),this.subscription.add(Dn(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)}))}subscribe(){cn(this.video);let{textTracks:e}=this.video;this.subscription.add(dn(e,`addtrack`).subscribe(()=>{let e=this.current$.getValue();e&&this.select(e)})),this.subscription.add(fn(dn(e,`addtrack`),dn(e,`removetrack`),pn([`init`])).pipe(hn(()=>this.htmlTextTracksAsArray().map(e=>this.htmlTextTrackToITextTrack(e))),mn((e,t)=>e.length===t.length&&e.every(({id:e},n)=>e===t[n].id))).subscribe(this.available$)),this.subscription.add(fn(dn(e,`change`),pn([`init`])).pipe(hn(()=>this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`)),hn(e=>e&&this.htmlTextTrackToITextTrack(e).id),mn()).subscribe(this.current$));let t=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(dn(e,`addtrack`).subscribe(e=>{e.track?.addEventListener(`cuechange`,t);let n=e=>{let t=e.target?.cues??null;t&&t.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener(`cuechange`,n))};e.track?.addEventListener(`cuechange`,n)})),this.subscription.add(dn(e,`removetrack`).subscribe(e=>{e.track?.removeEventListener(`cuechange`,t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let n of Array.from(e)){let e=n;ln(t.align)&&(e.align=t.align),ln(t.position)&&(e.position=t.position),ln(t.size)&&(e.size=t.size),ln(t.line)&&(e.line=t.line)}}htmlTextTracksAsArray(e=!1){cn(this.video);let t=[...this.video.textTracks];return e?t:t.filter(An.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:n}=e,r=e.id?e.id:On(e),i=this.externalTracks.has(r),a=(i?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes(`auto`);return i?{id:r,type:`external`,isAuto:a,language:t,label:n,url:this.externalTracks.get(r)?.url}:{id:r,type:`internal`,isAuto:a,language:t,label:n,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(([,e])=>this.detach(e)),e.filter(({id:e})=>!this.externalTracks.has(e)).forEach(e=>this.attach(e)),Array.from(this.externalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:e,language:n,isAuto:r})=>!this.internalTracks.has(e)&&!t.some(([,e])=>e.language===n&&e.isAuto===r)).forEach(e=>this.attach(e)),Array.from(this.internalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}select(e){cn(this.video);for(let e of this.htmlTextTracksAsArray(!0))e.mode=`showing`;for(let t of this.htmlTextTracksAsArray(!0))(un(e)||!kn(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){cn(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){cn(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName(`track`),t=>t.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)}}var jn=An;class Mn{pausedTime=0;streamOffset=0;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 Nn=e=>{let t=e;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t?.parentNode;return t??void 0},Pn=e=>{let t=Nn(e);return!!(t&&t.fullscreenElement&&t.fullscreenElement===e)},Fn=e=>{let t=Nn(e);return!!(t&&t.pictureInPictureElement&&t.pictureInPictureElement===e)};import{fromEvent as j,map as M,merge as In,filterChanged as Ln,isNonNullable as Rn,Subject as zn,filter as Bn,mapTo as Vn,combine as Hn,once as Un,shareReplay as N,throttle as Wn,ErrorCategory as Gn,ValueSubject as Kn,Subscription as qn}from"@vkontakte/videoplayer-shared";var Jn=3,Yn=(e,t,n=Jn)=>{let r=0,i=0;for(let a=0;a<e.length;a++){let o=e.start(a),s=e.end(a);if(o<=t&&t<=s){if(r=o,i=s,!n)return{from:r,to:i};for(let t=a-1;t>=0;t--)e.end(t)+n>=r&&(r=e.start(t));for(let t=a+1;t<e.length;t++)e.start(t)-n<=i&&(i=e.end(t))}}return{from:r,to:i}},Xn=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t},Zn=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t*1e3},Qn=e=>{let t=t=>j(e,t).pipe(Vn(void 0),N(1)),n=new qn,r=()=>n.unsubscribe(),i=In(j(e,`progress`),j(e,`timeupdate`)),a=i.pipe(M(()=>Yn(e.buffered,e.currentTime)),N(1)),o=i.pipe(M(()=>Zn(e.buffered)),N(1)),s=i.pipe(M(()=>e.buffered.length),N(1)),c=A.browser.isSafari?Hn({play:t(`play`).pipe(Un()),playing:t(`playing`)}).pipe(Vn(void 0),N(1)):t(`playing`),l=j(e,`volumechange`).pipe(M(()=>({muted:e.muted,volume:e.volume})),N(1)),u=j(e,`ratechange`).pipe(M(()=>e.playbackRate),N(1)),d=j(e,`error`).pipe(Bn(()=>!!(e.error||e.played.length)),M(()=>{let t=e.error;return{id:t?`MediaError#${t.code}`:`HtmlVideoError`,category:Gn.VIDEO_PIPELINE,message:t?t.message:`Error event from HTML video element`,thrown:e.error??void 0,origin:`mediaError`,data:t?{code:t.code}:void 0}}),N(1)),f=j(e,`timeupdate`).pipe(M(()=>e.currentTime),N(1)),p=In(j(e,`loadedmetadata`),j(e,`timeupdate`),j(e,`pause`),j(e,`seeked`),j(e,`ended`)).pipe(M(()=>Xn(e.played)),Ln(),N(1)),m=[`waiting`,`seeking`,`seeked`,`timeupdate`],h=new zn,g=.3,_;n.add(In(...m.map(t=>j(e,t))).subscribe(t=>{let n=e.currentTime;e.loop&&Rn(_)&&Rn(n)&&_>=e.duration-g&&n<=g&&h.next(_),_=n}));let v=t(`pause`).pipe(Bn(()=>!e.error&&_!==e.duration),N(1)),y=j(e,`enterpictureinpicture`).pipe(N(1)),b=j(e,`leavepictureinpicture`).pipe(N(1)),x=new Kn(Fn(e));n.add(y.subscribe(()=>x.next(!0))),n.add(b.subscribe(()=>x.next(!1)));let S=new Kn(Pn(e)),C=j(e,`fullscreenchange`).pipe(N(1));n.add(C.pipe(M(()=>Pn(e))).subscribe(S));let w=j(e,`timeupdate`).pipe(M(t=>e.duration-e.currentTime<.1),Ln(),N(1)),T=In(w.pipe(Bn(t=>!e.loop&&t)),j(e,`ended`)).pipe(Wn(1e3),Vn(void 0),N(1)),E=In(...[`waiting`,`pause`,`canplay`,`play`,`canplaythrough`,`playing`,`seeking`,`seeked`,`ended`].map(t=>j(e,t)),w.pipe(M(e=>({type:e?`ended`:`unknown`})))).pipe(M(t=>A.browser.isFirefox&&t.type===`ended`?e.readyState<2:e.readyState<3),Ln(),N(1));return{playing$:c,pause$:v,canplay$:t(`canplay`),ended$:T,looped$:h,error$:d,seeked$:t(`seeked`),seeking$:t(`seeking`),progress$:t(`progress`),loadStart$:t(`loadstart`),loadedMetadata$:t(`loadedmetadata`),loadedData$:t(`loadeddata`),timeUpdate$:f,durationChange$:j(e,`durationchange`).pipe(M(()=>e.duration),N(1)),playedTime$:p,isBuffering$:E,currentBuffer$:a,totalBufferDuration$:o,bufferRangeCount$:s,volumeState$:l,playbackRateState$:u,inPiP$:x,inFullscreen$:S,enterPip$:y,leavePip$:b,destroy:r}};import{VideoQuality as $n}from"@vkontakte/videoplayer-shared";var er=e=>{switch(e){case`mobile`:return $n.Q_144P;case`lowest`:return $n.Q_240P;case`low`:return $n.Q_360P;case`sd`:case`medium`:return $n.Q_480P;case`hd`:case`high`:return $n.Q_720P;case`fullhd`:case`full`:return $n.Q_1080P;case`quadhd`:case`quad`:return $n.Q_1440P;case`ultrahd`:case`ultra`:return $n.Q_2160P}};import{isNonNullable as P,isNullable as tr,now as nr,isHigher as rr,isHigherOrEqual as ir,isInvariantQuality as ar,isLowerOrEqual as or,videoSizeToQuality as sr,assertNotEmptyArray as cr,assertNonNullable as lr}from"@vkontakte/videoplayer-shared";var ur=!1,dr={},fr=e=>{ur=e},pr=()=>{dr={}},mr=e=>{e(dr)},hr=(e,t)=>{ur&&(dr.meta=dr.meta??{},dr.meta[e]=t)};class gr{name;constructor(e){this.name=e}next(e){if(!ur)return;dr.series=dr.series??{};let t=dr.series[this.name]??[];t.push([Date.now(),e]),dr.series[this.name]=t}}import{isHigher as _r,isLower as vr,isNonNullable as yr,isNullable as br,videoHeightToQuality as xr}from"@vkontakte/videoplayer-shared";function Sr(e,t,n){return!e.max&&e.min===t?`high_quality`:!e.min&&e.max===n?`traffic_saving`:`unknown`}function Cr(e,t,n){return br(e)||yr(e.min)&&yr(e.max)&&vr(e.max,e.min)||yr(e.min)&&yr(t)&&_r(e.min,t)||yr(e.max)&&yr(n)&&vr(e.max,n)}function wr({limits:e,highestAvailableHeight:t,lowestAvailableHeight:n}){return Cr({max:e?.max?xr(e.max):void 0,min:e?.min?xr(e.min):void 0},t?xr(t):void 0,n?xr(n):void 0)}var Tr=new gr(`best_bitrate`),Er=(e,t,n)=>(t-n)*2**(-10*e)+n,Dr=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate));class Or{last;history={};recordSelection(e){this.history[e.id]=nr()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var kr=`Assertion "ABR Tracks is empty array" failed`,Ar=new WeakMap,jr=new WeakMap,Mr=new WeakMap,Nr=(e,t,n,r)=>{let i=[...t].sort(Dr(1)),a=[...n].sort(Dr(1)),o=a.filter(t=>P(t.bitrate)&&P(e.bitrate)?e.bitrate/t.bitrate>r:!0),s=a.at(Math.round(a.length*i.indexOf(e)/(i.length+1)))??a.at(-1);return s&&o.includes(s)?s:o.length?o.at(-1):a.at(0)},Pr=(e,t,n,r)=>{let i=Ar.get(t);i||(i=[...t].sort(Dr(1)),Ar.set(t,i));let a=Ar.get(n);a||(a=[...n].sort(Dr(1)),Ar.set(n,a));let o=Mr.get(e);o||(o=a.filter(t=>P(t.bitrate)&&P(e.bitrate)?e.bitrate/t.bitrate>r:!0),Mr.set(e,o));let s=a.at(Math.round(a.length*i.indexOf(e)/(i.length+1)))??a.at(-1);return s&&o.includes(s)?s:o.length?o.at(-1):a.at(0)},Fr=e=>`quality`in e,Ir=(e,t,n,r)=>{let i=P(r?.last?.bitrate)&&P(n?.bitrate)&&r.last.bitrate<n.bitrate?e.trackCooldownIncreaseQuality:e.trackCooldownDecreaseQuality,a=n&&r&&r.history[n.id]&&nr()-r.history[n.id]<=i&&(!r.last||n.id!==r.last.id);if(n?.id&&r&&!a&&r.recordSelection(n),a&&r?.last){let e=r.last;return r?.recordSwitch(e),t({message:`
|
|
6
|
+
var e=`2.0.166-dev.abb27aca7.0`,t;(e=>{e.STOPPED=`stopped`,e.READY=`ready`,e.PLAYING=`playing`,e.PAUSED=`paused`})(t||={});var n;(e=>{e.MPEG=`MPEG`,e.DASH=`DASH`,e.DASH_SEP=`DASH_SEP`,e.DASH_SEP_VK=`DASH_SEP`,e.DASH_WEBM=`DASH_WEBM`,e.DASH_WEBM_AV1=`DASH_WEBM_AV1`,e.DASH_STREAMS=`DASH_STREAMS`,e.DASH_WEBM_VK=`DASH_WEBM`,e.DASH_ONDEMAND=`DASH_ONDEMAND`,e.DASH_ONDEMAND_VK=`DASH_ONDEMAND`,e.DASH_LIVE=`DASH_LIVE`,e.DASH_LIVE_CMAF=`DASH_LIVE_CMAF`,e.DASH_LIVE_WEBM=`DASH_LIVE_WEBM`,e.HLS=`HLS`,e.HLS_ONDEMAND=`HLS_ONDEMAND`,e.HLS_JS=`HLS`,e.HLS_FMP4=`HLS_FMP4`,e.HLS_LIVE=`HLS_LIVE`,e.HLS_LIVE_CMAF=`HLS_LIVE_CMAF`,e.WEB_RTC_LIVE=`WEB_RTC_LIVE`})(n||={});var r;(e=>{e.AV1=`av1`,e.VP9=`vp9`,e.AVC1=`avc1`,e.HEV1=`hev1`})(r||={});var i;(e=>{e.NOT_AVAILABLE=`NOT_AVAILABLE`,e.AVAILABLE=`AVAILABLE`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`})(i||={});var a;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.QUIC=`quic`})(a||={});var o;(e=>{e.NONE=`none`,e.INLINE=`inline`,e.FULLSCREEN=`fullscreen`,e.SECOND_SCREEN=`second_screen`,e.PIP=`pip`,e.INVISIBLE=`invisible`})(o||={});var s;(e=>{e.TRAFFIC_SAVING=`traffic_saving`,e.HIGH_QUALITY=`high_quality`,e.UNKNOWN=`unknown`})(s||={});import{assertNever as c,assertNonNullable as l,isNonNullable as u,ValueSubject as d,Subject as f,Subscription as p,merge as m,observableFrom as h,fromEvent as g,map as _,tap as v,filterChanged as y,isNullable as b,ErrorCategory as x}from"@vkontakte/videoplayer-shared";var S=e=>new Promise((t,n)=>{let r=document.createElement(`script`);r.setAttribute(`src`,e),r.onload=()=>t(),r.onerror=e=>n(e),document.body.appendChild(r)});class C{connection$=new d(void 0);castState$=new d(`NOT_AVAILABLE`);errorEvent$=new f;contentId;realCastState$=new d(`NOT_AVAILABLE`);subscription=new p;log;params;isDestroyed=!1;constructor(e){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 n=u(window.chrome?.cast),r=!!window.__onGCastApiAvailable;n?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&!this.isDestroyed&&this.initializeCastApi()},r||S(`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`).catch(()=>this.errorEvent$.next({id:`ChromecastLoading`,category:x.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(){u(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();b(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();b(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),n=cast.framework.CastContext.getInstance();this.subscription.add(g(n,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(e=>{switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=n.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 c(e.sessionState)}})).add(m(g(n,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(v(e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})}),_(e=>e.castState)),h([n.getCastState()])).pipe(y(),_(w),v(e=>{this.log({message:`realCastState$: ${e}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let i=r===`CONNECTED`,a=u(this.connection$.getValue());if(i&&!a){let r=n.getCurrentSession();l(r);let i=r.getCastDevice(),a=r.getMediaSession()?.media?.contentId;(b(a)||a===this.contentId)&&(this.log({message:`connection created`}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:r,castDevice:i}))}else!i&&a&&(this.log({message:`connection destroyed`}),this.connection$.next(void 0));this.castState$.next(r===`CONNECTED`?u(this.connection$.getValue())?`CONNECTED`:`AVAILABLE`:r)}))}initializeCastApi(){let e,t,n;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,n=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:n}),this.initListeners()}catch(e){this.errorEvent$.next({id:`ChromecastInitializer`,category:x.EXTERNAL_API,message:`[initializeCastApi] failed`,thrown:e})}}}var w=e=>{switch(e){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 c(e)}};import{assertNonNullable as T,combine as E,debounce as ee,ErrorCategory as te,filter as D,filterChanged as ne,isNonNullable as re,isNullable as ie,map as ae,Subscription as oe,ValueSubject as se}from"@vkontakte/videoplayer-shared";import{assertNever as ce,assertNonNullable as le,ErrorCategory as ue,getHighestQuality as de,isNonNullable as fe}from"@vkontakte/videoplayer-shared";import{assertNever as pe}from"@vkontakte/videoplayer-shared";var O=(e,t=0,n=0)=>{switch(n){case 0:return e.replace(`_offset_p`,t===0?``:`_`+t.toFixed(0));case 1:{if(t===0)return e;let n=new URL(e);return n.searchParams.append(`playback_shift`,t.toFixed(0)),n.toString()}case 2:{let n=new URL(e);return!n.searchParams.get(`offset_p`)&&t===0?e:(n.searchParams.set(`offset_p`,t.toFixed(0)),n.toString())}default:pe(n)}return e},me=(e,t)=>{switch(t){case 0:return NaN;case 1:{let t=new URL(e);return Number(t.searchParams.get(`playback_shift`))}case 2:{let t=new URL(e);return Number(t.searchParams.get(`offset_p`)??0)}default:pe(t)}},he=e=>{let{source:t,format:n,meta:r,output:i}=e,a,o,s;switch(n){case`MPEG`:{let e=t[n];le(e);let r=de(Object.keys(e));le(r);let i=e[r];le(i),a=i,o=`video/mp4`,s=ge();break}case`HLS`:case`HLS_FMP4`:case`HLS_ONDEMAND`:{let e=t[n];le(e),a=e.url,o=`application/x-mpegurl`,s=ge();break}case`DASH_SEP`:case`DASH_ONDEMAND`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_STREAMS`:{let e=t[n];le(e),a=e.url,o=`application/dash+xml`,s=ge();break}case`DASH_LIVE_CMAF`:{let e=t[n];le(e),a=e.url,o=`application/dash+xml`,s=_e();break}case`HLS_LIVE`:case`HLS_LIVE_CMAF`:{let e=t[n];le(e),a=O(e.url),o=`application/x-mpegurl`,s=_e();break}case`DASH_LIVE`:case`WEB_RTC_LIVE`:{let e=`Unsupported format for Chromecast`,t=Error(e);throw i.error$.next({id:`ChromecastProvider.createMediaInfo()`,category:ue.VIDEO_PIPELINE,message:e,thrown:t}),t}case`DASH`:case`DASH_LIVE_WEBM`:throw Error(`${n} is no longer supported`);default:return ce(n)}let c=ve(r.videoId??a,o);c.contentUrl=a,c.streamType=s,c.metadata=ye();let{title:l,subtitle:u}=r;return fe(l)&&(c.metadata.title=l),fe(u)&&(c.metadata.subtitle=u),c};function ge(){return chrome.cast?.media?.StreamType?.BUFFERED??`BUFFERED`}function _e(){return chrome.cast?.media?.StreamType?.LIVE??`LIVE`}function ve(e,t){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(e,t):{contentId:e,contentType:t,metadata:{title:``,subtitle:``},streamType:ge()}}function ye(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:``,subtitle:``,title:``,releaseYear:1970,type:0}}var k=(e,t,n=!1)=>{let r=e.getTransition();(n||!r||r.to===t)&&e.setState(t)};class be{params;interval=0;startVideoPosition;startTs;constructor(e){this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let e=(Date.now()-this.startTs)/1e3,t=this.startVideoPosition+e;this.params.output.position$.next(t)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}}import{assertNever as xe}from"@vkontakte/videoplayer-shared";import{isBrowserWindow as Se,ValueSubject as Ce}from"@vkontakte/videoplayer-shared";import{getWindow as we}from"@vkontakte/videoplayer-shared";class Te{_current;_current_version;_chromeVersion;_firefoxVersion;_safariVersion;_operaVersion;_edgeVersion;_yandexVersion;_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,n=/samsungbrowser/i.test(e)?`SamsungBrowser`:void 0,r=/chrome|crios/i.test(e)?`Chrome`:void 0,i=/chromium/i.test(e)?`Chromium`:void 0,a=/firefox|fxios/i.test(e)?`Firefox`:void 0,o=/webkit|safari|khtml/i.test(e)?`Safari`:void 0,s=/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||n||a||s||c||r||i||o||`Rest`}catch(e){console.error(e)}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}=we().navigator,n=t.match(e);if(!n)return;let r=n[1],i=parseInt(r,10);if(!isNaN(i))return this._current_version=i,i}catch(e){console.error(e)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}}import{getWindow as Ee,isBrowserWindow as De}from"@vkontakte/videoplayer-shared";var Oe=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;class ke{_displayChecker;_isMobile;_current;_iosVersion;_highEntropyValues={};_os={name:`Unknown`,version:`Unknown`,full:`Unknown`};_details={vendor:`Unknown`,model:`Unknown`};constructor(e){this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){return this._highEntropyValues.platform===`iOS`||this.os.name.toLowerCase().includes(`ios`)||[`iPhone`,`iPad`,`iPod`].includes(this.current)}get isMac(){return this._highEntropyValues.platform===`macOS`||this.os.name.toLowerCase().includes(`mac`)||this.current===`Mac`}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current===`iPad`||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform===`Android`||this.os.name.toLowerCase().includes(`android`)||this.current===`Android`}get isWindows(){return this.os.name.toLowerCase().includes(`windows`)}get isLinux(){return this.os.name.toLowerCase().includes(`linux`)&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=Ee();if(!De(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Oe()}catch(e){console.error(`DeviceChecker: calling isMobile error - `,e)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=Ee();if(!De(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let e=await t.getHighEntropyValues([`architecture`,`bitness`,`brands`,`mobile`,`platform`,`formFactor`,`model`,`platformVersion`,`wow64`]);this._highEntropyValues=e,e.platform&&(this._os.name=this.normalizeOSName(e.platform),e.platformVersion&&(this._os.version=this.normalizeOSVersion(e.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),e.model&&(this._details.model=e.model)}}detectDevice(e){try{let t=/android/i.test(e)?`Android`:void 0,n=/iphone/i.test(e)?`iPhone`:void 0,r=/ipad/i.test(e)?`iPad`:void 0,i=/ipod/i.test(e)?`iPod`:void 0,a=/mac/i.test(e)?`Mac`:void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?`RestMobile`:void 0;this._current=t||n||r||i||o||a||`Desktop`}catch(e){console.error(`DeviceChecker: device detection error - `,e)}}detectOS(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let t=n.length>0,i=n.length>1,a=`Unknown`,o=`Unknown`;if(t){let e=n[0];typeof e==`number`?e<r.length&&r[e]!==void 0&&(a=r[e]):a=e}if(i){let e=n[1];typeof e==`number`?e<r.length&&r[e]!==void 0&&(o=r[e]):e!==void 0&&(o=e)}else r[2]===void 0?r[1]!==void 0&&t&&typeof n[0]==`string`&&(o=r[1]):o=r[2];a=this.normalizeOSName(a),o=this.normalizeOSVersion(o,a),a===`iOS`&&/ipad/i.test(e)?a=`iPadOS`:a===`iPadOS`&&/ip(hone|od)/i.test(e)&&(a=`iOS`),this._os={name:a,version:o||`Unknown`,full:o&&o!==`Unknown`?`${a} ${o}`:a};break}}}catch(e){console.error(`DeviceChecker: OS detection error - `,e)}}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 t=parseFloat(e);if(!isNaN(t)){if(t>=11)return`11`;if(t>=10)return`10`;if(t===6.3)return`8.1`;if(t===6.2)return`8`;if(t===6.1)return`7`;if(t===6)return`Vista`;if(t===5.1||t===5.2)return`XP`;if(t===5)return`2000`;if(t===4)return`NT 4.0`}}return e}detectDeviceDetails(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let e=n[0],t=n[1],i=typeof e==`number`?r[e]===void 0?`Unknown`:this.normalizeVendorName(r[e]):this.normalizeVendorName(e),a=`Unknown`;typeof t==`number`?a=r[t]===void 0?`Unknown`:r[t]:t===void 0?r[1]===void 0?r[0]!==void 0&&(a=r[0]):a=r[1]:a=t,a=this.normalizeModelName(a,i),this.details.vendor=i,this.details.model=a;break}}}catch(e){console.error(`DeviceChecker: device details detection error - `,e)}}normalizeVendorName(e){return e?{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`}[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():`Unknown`}normalizeModelName(e,t){if(!e||e===`Unknown`)return e;if(e===`0`)return`Unknown`;let n=e.replace(/^build\//i,``).replace(/\s+bui$/i,``).replace(/\)$/,``).replace(/[;,)]/g,``).replace(/\s*\(.*?\)\s*/g,``).trim(),r=t.toLowerCase();return r.includes(`samsung`)?n=n.replace(/^(sm-|gt-|sgh-|sch-)/i,``):r.includes(`xiaomi`)?n=n.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,``):r.includes(`oneplus`)?n=n.replace(/^oneplus[\s\-_]*/i,``):r.includes(`google`)&&(n=n.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,``)),n=n.replace(/_/g,` `).replace(/-/g,` `).replace(/\s+/g,` `).trim(),n?(n.length>0&&/^[a-z]/.test(n)&&(n=n.charAt(0).toUpperCase()+n.slice(1)),n):`Unknown`}detectIOSVersion(){try{let e=Ee();if(!De(e))return;if(this._highEntropyValues.platformVersion){let e=this._highEntropyValues.platformVersion.split(`.`).slice(0,2).join(`.`);this._iosVersion=parseFloat(e);return}if(this._os.version!==`Unknown`){let e=this._os.version.split(`.`),t=e.length>=2?`${e[0]}.${e[1]}`:e[0];this._iosVersion=parseFloat(t);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,`.`)))}catch(e){console.error(`DeviceChecker: iOS version detection error - `,e)}}}import{getWindow as Ae,isBrowserWindow as je}from"@vkontakte/videoplayer-shared";class Me{_maxTouchPoints;_height;_width;_isHdr;_pixelRatio;_screenHeight;_screenWidth;_colorDepth;get isTouch(){return typeof this._maxTouchPoints==`number`?this._maxTouchPoints>1:`ontouchstart`in Ae()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let e=Ae();if(!je(e))return;let{navigator:t,screen:n}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia(`(dynamic-range: high)`)?.matches,this._colorDepth=n.colorDepth}catch(e){console.error(e)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=n.height,this._width=n.width,this._height=n.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(e){console.error(e)}}}import{getWindow as Ne,isBrowserWindow as Pe}from"@vkontakte/videoplayer-shared";var Fe=()=>window.ManagedMediaSource||window.MediaSource,Ie=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Le=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Re=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,ze=Ne().document?.createElement(`video`),Be=`video/mp4; codecs="avc1.42000a,mp4a.40.2"`,Ve=`video/mp4; codecs="hev1.1.6.L93.B0"`,He=`video/webm; codecs="vp09.00.10.08"`,Ue=`video/webm; codecs="av01.0.00M.08"`,We=`audio/mp4; codecs="mp4a.40.2"`,Ge=`audio/webm; codecs="opus"`,Ke;(async()=>{let e=Ne();if(!Pe(e)||!(`mediaCapabilities`in e.navigator))return;let t={type:`media-source`,video:{contentType:`video/webm`,width:1280,height:720,bitrate:1e6,framerate:30}},[n,r]=await Promise.all([e.navigator.mediaCapabilities.decodingInfo({...t,video:{...t.video,contentType:Ue}}),e.navigator.mediaCapabilities.decodingInfo({...t,video:{...t.video,contentType:He}})]);Ke={DASH_WEBM_AV1:n,DASH_WEBM:r}})().catch(e=>{console.log(ze),console.error(e)});class qe{_video;_deviceChecker;_browserChecker;_protocols;_containers;_codecs;_nativeHlsSupported;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 Ke}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=Ne();if(!Pe(e))return;let t=e.document;this._video=t.createElement(`video`);try{this._protocols={mms:Ie(),mse:Le(),hls:!!(this._video.canPlayType?.(`application/x-mpegurl`)||this._video.canPlayType?.(`vnd.apple.mpegURL`)),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.(`video/mp4`),webm:!!this._video.canPlayType?.(`video/webm`),cmaf:!0};let t=!!Fe()?.isTypeSupported?.(Be),n=!!Fe()?.isTypeSupported?.(Ve),r=!!Fe()?.isTypeSupported?.(We);this._codecs={h264:t,h265:n,vp9:!!Fe()?.isTypeSupported?.(He),av1:!!Fe()?.isTypeSupported?.(Ue),aac:r,opus:!!Fe()?.isTypeSupported?.(Ge),mpeg:(t||n)&&r},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}}import{getWindow as Je,isBrowserWindow as Ye}from"@vkontakte/videoplayer-shared";var Xe=`audio/mpeg`;class Ze{_audio;_containers;_codecs;supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=Je();if(!Ye(e))return;let t=e.document;this._audio=t.createElement(`audio`);try{this._containers={mpeg:!!this._audio.canPlayType?.(Xe)},this._codecs={mp3:!!Fe()?.isTypeSupported?.(Xe)}}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}}class Qe{isInited$=new Ce(!1);_displayChecker;_deviceChecker;_browserChecker;_videoChecker;_audioChecker;constructor(){this._displayChecker=new Me,this._deviceChecker=new ke(this._displayChecker),this._browserChecker=new Te,this._videoChecker=new qe(this._deviceChecker,this._browserChecker),this._audioChecker=new Ze,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(){Se()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}}var A=new Qe,$e=(e,t=!1)=>{let{containers:n,protocols:r,codecs:i,nativeHlsSupported:a}=A.video,{isMobile:o}=A.device,s=A.device.isMac&&A.browser.isSafari,c=t&&!o&&!s,l=(i.h264||i.h265)&&i.aac,u=r.mse||r.mms;return e.filter(e=>{switch(e){case`DASH_SEP`:return u&&n.mp4&&l;case`DASH_WEBM`:return u&&n.webm&&i.vp9&&i.opus;case`DASH_WEBM_AV1`:return u&&n.webm&&i.av1&&i.opus;case`DASH_STREAMS`:return u&&(n.mp4&&l||n.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case`DASH_LIVE`:return u&&n.mp4&&l;case`DASH_LIVE_CMAF`:return u&&n.mp4&&l&&n.cmaf;case`DASH_ONDEMAND`:return u&&n.mp4&&l;case`HLS`:case`HLS_ONDEMAND`:case`HLS_FMP4`:case`HLS_LIVE`:case`HLS_LIVE_CMAF`:return a&&!c;case`MPEG`:return n.mp4;case`DASH`:case`DASH_LIVE_WEBM`:return!1;case`WEB_RTC_LIVE`:return r.webrtc&&r.ws&&i.h264&&(n.mp4||n.webm);default:return xe(e)}})},et=e=>{switch(e){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 xe(e)}},tt=(e,t=!1)=>$e(Object.keys(e).filter(e=>!et(e)),t).length>0;class nt{subscription=new oe;log;params;sessionId$=new se(null);mediaSessionId$=new se(null);contentId$=new se(null);progressTicker;isMobile=Oe();mobileVolumeState={muted:!1,volume:0};media=null;lastRequestedVolume=null;constructor(e){this.params=e,this.progressTicker=new be(e),this.log=this.params.dependencies.logger.createComponentLog(`ChromecastPresentationApiProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(et(e.format)),this.subscribe()}subscribe(){let e=e=>{this.params.output.error$.next({category:te.WTF,id:`ChromecastPresentationApiProvider`,message:e?.message??`Unknown error`,thrown:e})};this.subscription.add(this.params.chromecastConnector.message$.pipe(D(e=>!!e)).subscribe(e=>{this.handleMessage(e)},e)),this.subscription.add(this.sessionId$.pipe(D(re),ne(),ee(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(ne(),ae(Boolean));this.subscription.add(E({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(D(({mediaLoaded:e})=>e)).subscribe(()=>{let e=this.params.desiredState.seekState.getState();e.state===`requested`&&this.seek(e.position/1e3)},e));let n=E({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(n.pipe(D(({mediaLoaded:e})=>e),ee(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(n.pipe(D(({mediaLoaded:e,playbackState:{from:t,to:n}})=>!e&&t===`stopped`&&n===`playing`)).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(E({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ee(30)),mediaLoaded:t}).pipe(D(({mediaLoaded:e})=>e)).subscribe(({volumeState:e})=>{let{muted:t,volume:n}=e.to;this.setVolume(n,t)},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 n=e.message?.receiver.volume;this.syncVolumeState(n)}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=he(this.params),t=this.media?.currentTime,n=this.params.desiredState.seekState.getState(),r=t??(n.state===`none`?0:n.position/1e3),i=this.params.desiredState.playbackState.getState()===`playing`;this.params.chromecastConnector.sendV2Message({type:`LOAD`,requestId:0,media:e,autoplay:i,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();T(e,`play on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PLAY`,mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();T(e,`pause on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PAUSE`,mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();T(t,`seek on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`SEEK`,currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let n=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(n=this.mobileVolumeState.volume,r+=`, mobile next volume: ${n}`),this.log({message:r}),this.lastRequestedVolume={volume:n,muted:t},this.params.chromecastConnector.sendV2Message({type:`SET_VOLUME`,requestId:0,volume:{level:t?0:n,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let n=this.params.output.isBuffering$.getValue(),r=e===`BUFFERING`;switch(n!==r&&this.params.output.isBuffering$.next(r),e){case`PAUSED`:k(this.params.desiredState.playbackState,`paused`);break;case`PLAYING`:k(this.params.desiredState.playbackState,`playing`);break;case`IDLE`:t===`FINISHED`?(this.params.output.endedEvent$.next(),k(this.params.desiredState.playbackState,`stopped`),this.contentId$.next(null)):k(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}}syncMediaState=e=>{if(ie(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 n=e.media?.duration;re(n)&&this.params.output.duration$.next(Math.max(0,n));let r=e.currentTime;if(re(r)){this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let t=this.params.output.isLive$.getValue();e.playerState===`PLAYING`&&!t?this.progressTicker.start(r):this.progressTicker.pause()}};syncVolumeState(e){if(ie(e))return;let{level:t,muted:n}=e,r={muted:n??!1,volume:t??0};this.lastRequestedVolume&&=(n&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!n&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),null);let i=`[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,i+=`, volume passed to state machine: ${r.volume}`),this.log({message:i}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}}import{assertNonNullable as rt,ErrorCategory as it,filter as at,Subject as ot,Subscription as st,tap as ct,ValueSubject as lt,fromEvent as ut,getWindow as dt}from"@vkontakte/videoplayer-shared";var ft=e=>({castDevice:{friendlyName:e},remotePlayer:{},remotePlayerController:{},session:{}}),pt=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));class mt{params;clientId;capabilities=[`WEB`];presentationRequest$=new lt(null);log;sessionId$=new lt(null);broadcastChannel=new BroadcastChannel(`vk_player_chromecast_events`);subscription=new st;subscriptionEvents=new st;isDestroyed=!1;sequenceNumber=0;presentationAvailable$=new lt(!1);presentationConnection$=new lt(null);message$=new lt(null);friendlyName$=new lt(null);errorEvent$=new ot;constructor(e){this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog(`ChromecastPresentationApiConnector`),this.log({message:`constructor`}),this.safeReinitPresentation(),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(),n=new PresentationRequest(t);this.presentationRequest$.next(n),this.log({message:`PresentationRequest created`}),n.getAvailability().then(e=>{let t=()=>{this.log({message:`PresentationRequest presentation availability: ${e.value}`}),this.presentationAvailable$.next(e.value)};this.subscriptionEvents.add(ut(e,`change`).subscribe(()=>{t()})),t()}).catch(()=>{this.presentationAvailable$.next(!0)}),dt().navigator.presentation.defaultRequest=n,e&&n.reconnect(`auto-join`).then(e=>{this.log({message:`PresentationRequest reconnect success`}),this.handleConnection(e)}).catch(()=>{this.log({message:`PresentationRequest reconnect failed`})})}safeReinitPresentation(e){try{this.reinitPresentation(e)}catch(e){this.errorEvent$.next({category:it.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`reinitPresentation error`,thrown:e})}}async connect(){this.log({message:`connect`});try{this.presentationRequest$.getValue()||(this.log({message:`reinitPresentation`}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();rt(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:it.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`connect error`,thrown:e});break}}}subscribe(){this.subscription.add(ut(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(ct(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),at(e=>!!e)).subscribe(e=>{let t=ut(e,`message`).subscribe(e=>{let t=JSON.parse(e.data);t.clientId===this.clientId&&(this.log({message:`[onmessage] ${e.data}`}),this.handleMessage(t),this.message$.next(t))}),n=ut(e,`connect`).subscribe(()=>{this.send(`client_connect`)}),r=ut(e,`close`).subscribe(e=>{switch(e.reason){case`error`:this.errorEvent$.next({category:it.WTF,id:`ChromecastPresentationApiConnector`,message:`Session error`,thrown:e});break;case`closed`:break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(n),this.subscriptionEvents.add(r)}))}send(e){switch(e){case`client_connect`:{let e={type:`client_connect`,message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(e));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let n={type:`v2_message`,sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(n))}}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:it.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)%(2**53-1),e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e=`__vk_player_chromecast_id`;return dt()[e]=dt()[e]||pt()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new st}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 ht,Subject as gt,map as _t,Subscription as vt,combine as yt,filterChanged as bt,assertNonNullable as xt}from"@vkontakte/videoplayer-shared";class St{subscription=new vt;log;contentId;connection$=new ht(void 0);castState$=new ht(`NOT_AVAILABLE`);errorEvent$=new gt;chromecastConnector;static isSupported(){return`chrome`in window&&`presentation`in navigator&&`BroadcastChannel`in window}constructor(e){let t=St.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 mt({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}subscribe(){xt(this.chromecastConnector,`subscribe with null chromecastConnector`),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=yt({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(bt())});this.subscription.add(e.pipe(_t(({connection:e,friendlyName:t})=>!!(e&&t)),bt()).subscribe(e=>{let t=this.chromecastConnector?.friendlyName$.getValue()??``;this.connection$.next(e?ft(t):void 0)})).add(e.subscribe(({available:e,connection:t})=>{e?t?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 Ct,Subject as wt,merge as Tt}from"@vkontakte/videoplayer-shared";var Et=(e,t)=>e===t;class Dt{comparator;state;prevState;transition;transitionStarted$=new wt;transitionEnded$=new wt;transitionUpdated$=new wt;forceChanged$=new wt;stateChangeStarted$=Tt(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=Tt(this.transitionEnded$,this.forceChanged$);constructor(e,t=Et){this.comparator=t,this.state=e,this.prevState=void 0}setState(e){let t=this.transition,n=this.state;this.transition=void 0,this.prevState=n,this.state=e,t?this.comparator(t.to,e)?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:n,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,n=this.state;this.comparator(n,e)||Ct(t)&&this.comparator(t.to,e)||(this.prevState=n,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:n,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}import{assertNever as Ot,debounce as kt,ErrorCategory as At,fromEvent as jt,map as Mt,merge as Nt,observableFrom as Pt,Subject as Ft,Subscription as It,timeout as Lt}from"@vkontakte/videoplayer-shared";var Rt=5,zt=5,Bt=500,Vt=7e3;class Ht{subscription=new It;loadMediaTimeoutSubscription=new It;videoState=new Dt(`stopped`);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`ChromecastProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(et(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 It;this.subscription.add(e),this.subscription.add(Nt(this.videoState.stateChangeStarted$.pipe(Mt(e=>`stateChangeStarted$ ${JSON.stringify(e)}`)),this.videoState.stateChangeEnded$.pipe(Mt(e=>`stateChangeEnded$ ${JSON.stringify(e)}`))).subscribe(e=>this.log({message:`[videoState] ${e}`})));let t=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let t=new Ft;e.add(t.pipe(kt(Bt)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(e=>{this.logRemoteEvent(e);let r=e.value;this.params.output.position$.next(r),(this.params.desiredState.seekState.getState().state===`applying`||Math.abs(r-n)>Rt)&&t.next(r),n=r})),e.add(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)}))}t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),e=>{this.logRemoteEvent(e);let{remotePlayer:t}=this.params.connection,n=e.value,r=this.params.output.isBuffering$.getValue(),i=n===chrome.cast.media.PlayerState.BUFFERING;switch(r!==i&&this.params.output.isBuffering$.next(i),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&t.duration-t.currentTime<zt&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:Ot(n)}}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})}),t(jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}),t(Nt(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Pt([`init`])).pipe(kt(0)),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`),k(this.params.desiredState.playbackState,`paused`)):(this.videoState.setState(`playing`),k(this.params.desiredState.playbackState,`playing`));let e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:`none`})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=he(this.params),n=this.createLoadRequest(t);this.loadMedia(n)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`paused`||e===`playing`)&&(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`playing`||e===`paused`)&&(this.videoState.setState(`playing`),k(this.params.desiredState.playbackState,`playing`))}handleRemoteReady(){this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.params.desiredState.playbackState.getTransition()?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`)}handleRemoteStop(){this.videoState.getState()!==`stopped`&&this.videoState.setState(`stopped`)}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),n={volume:e.volume??t.volume,muted:e.muted??t.muted};(n.volume!==t.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:n}=this.params.connection;t.currentTime=e,n.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let n=this.params.desiredState.seekState.getState();return n.state===`applying`||n.state===`requested`?t.currentTime=this.params.output.isLive$.getValue()?0:n.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),n=new Promise((e,t)=>{this.loadMediaTimeoutSubscription.add(Lt(Vt).subscribe(()=>t(`timeout(${Vt})`)))});Promise.race([t,n]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},e=>{let t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:`ChromecastProvider.loadMedia`,category:At.VIDEO_PIPELINE,message:t,thrown:e})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.stop());return}if(!t){if(r?.to!==`paused`&&i.state===`requested`&&e!==`stopped`){this.seek(i.position/1e3);return}switch(n){case`ready`:switch(e){case`playing`:case`paused`:case`ready`:break;case`stopped`:this.videoState.startTransitionTo(`ready`),this.prepare();break;default:Ot(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:Ot(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:Ot(e)}break;default:Ot(n)}}}}import{clearVideoElement as Ut,fromEvent as Wt,getWindow as Gt,Subscription as Kt}from"@vkontakte/videoplayer-shared";import{clearVideoElement as qt}from"@vkontakte/videoplayer-shared";var Jt=(e,t)=>{try{e.pause(),e.playbackRate=0,qt(e,t),e.remove()}catch(e){console.error(e)}},Yt=`__spvc`;class Xt{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)}}var Zt=Gt(),Qt=Zt.WeakMap?new Zt.WeakMap:new Xt,$t=Zt.WeakMap?new Zt.WeakMap:new Map,en=(e,t=20)=>{let n=0;return Wt(e,`ratechange`).subscribe(r=>{n++,n>=t&&(e.currentTime=e.currentTime,n=0)})};function tn(e){e.style.position=`fixed`,e.style.left=`100%`,e.setAttribute(`data-role`,`screen`),Gt().document.body.appendChild(e)}function nn(e,t){e.style.position=``,e.style.left=``,t.appendChild(e)}var rn=(e,{audioVideoSyncRate:t,disableYandexPiP:n,clearVideoElementInnerHTML:r,reuseOwnVideoElement:i})=>{let a,o=e.querySelector(`video`),s=!!o,c=Gt().document.querySelector(`body > video[data-role=screen]`)||void 0;i?Zt[Yt]=c:(c?.remove(),delete Zt[Yt]),o?(a=o,Ut(a,r)):c&&c===Zt[Yt]?(a=c,nn(a,e)):(a=Gt().document.createElement(`video`),e.appendChild(a),i&&(Zt[Yt]=a)),Qt.set(a,s);let l=new Kt;return l.add(en(a,t)),$t.set(a,l),a.setAttribute(`crossorigin`,`anonymous`),a.setAttribute(`playsinline`,`playsinline`),n&&a.setAttribute(`x-yandex-pip`,`false`),a.controls=!1,a.setAttribute(`poster`,`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`),a},an=e=>(e.setAttribute(`crossorigin`,`anonymous`),e.controls=!1,e),on=(e,t)=>{if(e instanceof HTMLAudioElement){Jt(e,!0);return}if(e instanceof HTMLVideoElement){sn(e,t);return}};function sn(e,{keepVideoElement:t,clearVideoElementInnerHTML:n,reuseOwnVideoElement:r}){$t.get(e)?.unsubscribe(),$t.delete(e);let i=Qt.get(e);Qt.delete(e),i||t?Ut(e,n):r?(Ut(e,n),tn(e)):Jt(e,n)}import{assertNonNullable as cn,isNonNullable as ln,isNullable as un,fromEvent as dn,merge as fn,observableFrom as pn,filterChanged as mn,map as hn,Subject as gn,Subscription as _n,ValueSubject as vn,ErrorCategory as yn}from"@vkontakte/videoplayer-shared";import{isNonNullable as bn,isNullable as xn,Subscription as Sn}from"@vkontakte/videoplayer-shared";var Cn=(e,t,n,{equal:r=(e,t)=>e===t,changed$:i,onError:a}={})=>{let o=e.getState(),s=t(),c=xn(i),l=new Sn;return i&&l.add(i.subscribe(t=>{r(t,e.getState())&&e.setState(t)},a)),r(s,o)||(n(o),c&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe(t=>{n(t.to),c&&e.setState(t.to)},a)),l},wn=(e,t,n)=>Cn(t,()=>e.loop,t=>{bn(t)&&(e.loop=t)},{onError:n}),Tn=(e,t,n,r,i)=>Cn(t,()=>({muted:e.muted,volume:e.volume}),t=>{i?.skipVideoElVolumeSync$.getValue()||bn(t)&&(e.muted=t.muted,e.volume=t.volume)},{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:n,onError:r}),En=(e,t,n,r)=>Cn(t,()=>e.playbackRate,t=>{bn(t)&&(e.playbackRate=t)},{changed$:n,onError:r}),Dn=Cn,On=e=>[`__`,e.language,e.label].join(`|`),kn=(e,t)=>{if(e.id===t)return!0;let[n,r,i]=t.split(`|`);return e.language===r&&e.label===i};class An{available$=new gn;current$=new vn(void 0);error$=new gn;video;cueSettings;subscription=new _n;externalTracks=new Map;internalTracks=new Map;baseURL;constructor(e){this.baseURL=e}connect(e,t,n){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=e=>{this.error$.next({id:`TextTracksManager`,category:yn.WTF,message:`Generic HtmlVideoTextTrackManager error`,thrown:e})};this.subscription.add(this.available$.subscribe(n.availableTextTracks$)),this.subscription.add(this.current$.subscribe(n.currentTextTrack$)),this.subscription.add(this.error$.subscribe(n.error$)),this.subscription.add(Dn(t.internalTextTracks,()=>Object.values(this.internalTracks),e=>{ln(e)&&this.setInternal(e)},{equal:(e,t)=>ln(e)&&ln(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(hn(e=>e.filter(({type:e})=>e===`internal`))),onError:r})),this.subscription.add(Dn(t.externalTextTracks,()=>Object.values(this.externalTracks),e=>{ln(e)&&this.setExternal(e)},{equal:(e,t)=>ln(e)&&ln(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(hn(e=>e.filter(({type:e})=>e===`external`))),onError:r})),this.subscription.add(Dn(t.currentTextTrack,()=>{if(this.video)return;let e=this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`);return e&&this.htmlTextTrackToITextTrack(e).id},e=>this.select(e),{changed$:this.current$,onError:r})),this.subscription.add(Dn(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)}))}subscribe(){cn(this.video);let{textTracks:e}=this.video;this.subscription.add(dn(e,`addtrack`).subscribe(()=>{let e=this.current$.getValue();e&&this.select(e)})),this.subscription.add(fn(dn(e,`addtrack`),dn(e,`removetrack`),pn([`init`])).pipe(hn(()=>this.htmlTextTracksAsArray().map(e=>this.htmlTextTrackToITextTrack(e))),mn((e,t)=>e.length===t.length&&e.every(({id:e},n)=>e===t[n].id))).subscribe(this.available$)),this.subscription.add(fn(dn(e,`change`),pn([`init`])).pipe(hn(()=>this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`)),hn(e=>e&&this.htmlTextTrackToITextTrack(e).id),mn()).subscribe(this.current$));let t=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(dn(e,`addtrack`).subscribe(e=>{e.track?.addEventListener(`cuechange`,t);let n=e=>{let t=e.target?.cues??null;t&&t.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener(`cuechange`,n))};e.track?.addEventListener(`cuechange`,n)})),this.subscription.add(dn(e,`removetrack`).subscribe(e=>{e.track?.removeEventListener(`cuechange`,t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let n of Array.from(e)){let e=n;ln(t.align)&&(e.align=t.align),ln(t.position)&&(e.position=t.position),ln(t.size)&&(e.size=t.size),ln(t.line)&&(e.line=t.line)}}htmlTextTracksAsArray(e=!1){cn(this.video);let t=[...this.video.textTracks];return e?t:t.filter(An.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:n}=e,r=e.id?e.id:On(e),i=this.externalTracks.has(r),a=(i?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes(`auto`);return i?{id:r,type:`external`,isAuto:a,language:t,label:n,url:this.externalTracks.get(r)?.url}:{id:r,type:`internal`,isAuto:a,language:t,label:n,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(([,e])=>this.detach(e)),e.filter(({id:e})=>!this.externalTracks.has(e)).forEach(e=>this.attach(e)),Array.from(this.externalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:e,language:n,isAuto:r})=>!this.internalTracks.has(e)&&!t.some(([,e])=>e.language===n&&e.isAuto===r)).forEach(e=>this.attach(e)),Array.from(this.internalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}select(e){cn(this.video);for(let e of this.htmlTextTracksAsArray(!0))e.mode=`showing`;for(let t of this.htmlTextTracksAsArray(!0))(un(e)||!kn(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){cn(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){cn(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName(`track`),t=>t.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)}}var jn=An;class Mn{pausedTime=0;streamOffset=0;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 Nn=e=>{let t=e;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t?.parentNode;return t??void 0},Pn=e=>{let t=Nn(e);return!!(t&&t.fullscreenElement&&t.fullscreenElement===e)},Fn=e=>{let t=Nn(e);return!!(t&&t.pictureInPictureElement&&t.pictureInPictureElement===e)};import{fromEvent as j,map as M,merge as In,filterChanged as Ln,isNonNullable as Rn,Subject as zn,filter as Bn,mapTo as Vn,combine as Hn,once as Un,shareReplay as N,throttle as Wn,ErrorCategory as Gn,ValueSubject as Kn,Subscription as qn}from"@vkontakte/videoplayer-shared";var Jn=3,Yn=(e,t,n=Jn)=>{let r=0,i=0;for(let a=0;a<e.length;a++){let o=e.start(a),s=e.end(a);if(o<=t&&t<=s){if(r=o,i=s,!n)return{from:r,to:i};for(let t=a-1;t>=0;t--)e.end(t)+n>=r&&(r=e.start(t));for(let t=a+1;t<e.length;t++)e.start(t)-n<=i&&(i=e.end(t))}}return{from:r,to:i}},Xn=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t},Zn=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t*1e3},Qn=e=>{let t=t=>j(e,t).pipe(Vn(void 0),N(1)),n=new qn,r=()=>n.unsubscribe(),i=In(j(e,`progress`),j(e,`timeupdate`)),a=i.pipe(M(()=>Yn(e.buffered,e.currentTime)),N(1)),o=i.pipe(M(()=>Zn(e.buffered)),N(1)),s=i.pipe(M(()=>e.buffered.length),N(1)),c=A.browser.isSafari?Hn({play:t(`play`).pipe(Un()),playing:t(`playing`)}).pipe(Vn(void 0),N(1)):t(`playing`),l=j(e,`volumechange`).pipe(M(()=>({muted:e.muted,volume:e.volume})),N(1)),u=j(e,`ratechange`).pipe(M(()=>e.playbackRate),N(1)),d=j(e,`error`).pipe(Bn(()=>!!(e.error||e.played.length)),M(()=>{let t=e.error;return{id:t?`MediaError#${t.code}`:`HtmlVideoError`,category:Gn.VIDEO_PIPELINE,message:t?t.message:`Error event from HTML video element`,thrown:e.error??void 0,origin:`mediaError`,data:t?{code:t.code}:void 0}}),N(1)),f=j(e,`timeupdate`).pipe(M(()=>e.currentTime),N(1)),p=In(j(e,`loadedmetadata`),j(e,`timeupdate`),j(e,`pause`),j(e,`seeked`),j(e,`ended`)).pipe(M(()=>Xn(e.played)),Ln(),N(1)),m=[`waiting`,`seeking`,`seeked`,`timeupdate`],h=new zn,g=.3,_;n.add(In(...m.map(t=>j(e,t))).subscribe(t=>{let n=e.currentTime;e.loop&&Rn(_)&&Rn(n)&&_>=e.duration-g&&n<=g&&h.next(_),_=n}));let v=t(`pause`).pipe(Bn(()=>!e.error&&_!==e.duration),N(1)),y=j(e,`enterpictureinpicture`).pipe(N(1)),b=j(e,`leavepictureinpicture`).pipe(N(1)),x=new Kn(Fn(e));n.add(y.subscribe(()=>x.next(!0))),n.add(b.subscribe(()=>x.next(!1)));let S=new Kn(Pn(e)),C=j(e,`fullscreenchange`).pipe(N(1));n.add(C.pipe(M(()=>Pn(e))).subscribe(S));let w=j(e,`timeupdate`).pipe(M(t=>e.duration-e.currentTime<.1),Ln(),N(1)),T=In(w.pipe(Bn(t=>!e.loop&&t)),j(e,`ended`)).pipe(Wn(1e3),Vn(void 0),N(1)),E=In(...[`waiting`,`pause`,`canplay`,`play`,`canplaythrough`,`playing`,`seeking`,`seeked`,`ended`].map(t=>j(e,t)),w.pipe(M(e=>({type:e?`ended`:`unknown`})))).pipe(M(t=>A.browser.isFirefox&&t.type===`ended`?e.readyState<2:e.readyState<3),Ln(),N(1));return{playing$:c,pause$:v,canplay$:t(`canplay`),ended$:T,looped$:h,error$:d,seeked$:t(`seeked`),seeking$:t(`seeking`),progress$:t(`progress`),loadStart$:t(`loadstart`),loadedMetadata$:t(`loadedmetadata`),loadedData$:t(`loadeddata`),timeUpdate$:f,durationChange$:j(e,`durationchange`).pipe(M(()=>e.duration),N(1)),playedTime$:p,isBuffering$:E,currentBuffer$:a,totalBufferDuration$:o,bufferRangeCount$:s,volumeState$:l,playbackRateState$:u,inPiP$:x,inFullscreen$:S,enterPip$:y,leavePip$:b,destroy:r}};import{VideoQuality as $n}from"@vkontakte/videoplayer-shared";var er=e=>{switch(e){case`mobile`:return $n.Q_144P;case`lowest`:return $n.Q_240P;case`low`:return $n.Q_360P;case`sd`:case`medium`:return $n.Q_480P;case`hd`:case`high`:return $n.Q_720P;case`fullhd`:case`full`:return $n.Q_1080P;case`quadhd`:case`quad`:return $n.Q_1440P;case`ultrahd`:case`ultra`:return $n.Q_2160P}};import{isNonNullable as P,isNullable as tr,now as nr,isHigher as rr,isHigherOrEqual as ir,isInvariantQuality as ar,isLowerOrEqual as or,videoSizeToQuality as sr,assertNotEmptyArray as cr,assertNonNullable as lr}from"@vkontakte/videoplayer-shared";var ur=!1,dr={},fr=e=>{ur=e},pr=()=>{dr={}},mr=e=>{e(dr)},hr=(e,t)=>{ur&&(dr.meta=dr.meta??{},dr.meta[e]=t)};class gr{name;constructor(e){this.name=e}next(e){if(!ur)return;dr.series=dr.series??{};let t=dr.series[this.name]??[];t.push([Date.now(),e]),dr.series[this.name]=t}}import{isHigher as _r,isLower as vr,isNonNullable as yr,isNullable as br,videoHeightToQuality as xr}from"@vkontakte/videoplayer-shared";function Sr(e,t,n){return!e.max&&e.min===t?`high_quality`:!e.min&&e.max===n?`traffic_saving`:`unknown`}function Cr(e,t,n){return br(e)||yr(e.min)&&yr(e.max)&&vr(e.max,e.min)||yr(e.min)&&yr(t)&&_r(e.min,t)||yr(e.max)&&yr(n)&&vr(e.max,n)}function wr({limits:e,highestAvailableHeight:t,lowestAvailableHeight:n}){return Cr({max:e?.max?xr(e.max):void 0,min:e?.min?xr(e.min):void 0},t?xr(t):void 0,n?xr(n):void 0)}var Tr=new gr(`best_bitrate`),Er=(e,t,n)=>(t-n)*2**(-10*e)+n,Dr=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate));class Or{last;history={};recordSelection(e){this.history[e.id]=nr()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var kr=`Assertion "ABR Tracks is empty array" failed`,Ar=new WeakMap,jr=new WeakMap,Mr=new WeakMap,Nr=(e,t,n,r)=>{let i=[...t].sort(Dr(1)),a=[...n].sort(Dr(1)),o=a.filter(t=>P(t.bitrate)&&P(e.bitrate)?e.bitrate/t.bitrate>r:!0),s=a.at(Math.round(a.length*i.indexOf(e)/(i.length+1)))??a.at(-1);return s&&o.includes(s)?s:o.length?o.at(-1):a.at(0)},Pr=(e,t,n,r)=>{let i=Ar.get(t);i||(i=[...t].sort(Dr(1)),Ar.set(t,i));let a=Ar.get(n);a||(a=[...n].sort(Dr(1)),Ar.set(n,a));let o=Mr.get(e);o||(o=a.filter(t=>P(t.bitrate)&&P(e.bitrate)?e.bitrate/t.bitrate>r:!0),Mr.set(e,o));let s=a.at(Math.round(a.length*i.indexOf(e)/(i.length+1)))??a.at(-1);return s&&o.includes(s)?s:o.length?o.at(-1):a.at(0)},Fr=e=>`quality`in e,Ir=(e,t,n,r)=>{let i=P(r?.last?.bitrate)&&P(n?.bitrate)&&r.last.bitrate<n.bitrate?e.trackCooldownIncreaseQuality:e.trackCooldownDecreaseQuality,a=n&&r&&r.history[n.id]&&nr()-r.history[n.id]<=i&&(!r.last||n.id!==r.last.id);if(n?.id&&r&&!a&&r.recordSelection(n),a&&r?.last){let e=r.last;return r?.recordSwitch(e),t({message:`
|
|
7
7
|
[last ${Fr(e)?`video`:`audio`} selected] ${Fr(e)?e.quality:e.bitrate}
|
|
8
8
|
`}),e}return r?.recordSwitch(n),n},Lr=(e,t)=>Math.log(t)/Math.log(e),Rr=({tuning:e,container:t,limits:n,panelSize:r})=>{let i=e.containerSizeFactor;if(r)return{containerSizeLimit:r,containerSizeFactor:i};if(e.usePixelRatio&&A.display.pixelRatio){let t=A.display.pixelRatio;if(e.pixelRatioMultiplier)i*=e.pixelRatioMultiplier*(t-1)+1;else{let n=e.pixelRatioLogBase,[r=0,a=0,o=0]=e.pixelRatioLogCoefficients,s=Lr(n,r*t+a)+o;Number.isFinite(s)&&(i*=s)}}return P(n?.min)&&ir(n.min,e.highQualityLimit)&&(i*=2),{containerSizeLimit:e.limitByContainer&&t&&t.width>0&&t.height>0?{width:t.width*i,height:t.height*i}:void 0,containerSizeFactor:i}},zr=new WeakMap,Br=(e,{container:t,estimatedThroughput:n,tuning:r,limits:i,reserve:a=0,forwardBufferHealth:o,playbackRate:s,current:c,failedVideoTrack:l,history:u,visible:d,droppedVideoMaxQualityLimit:f,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:h,panelSize:g})=>{cr(e,kr);let{containerSizeFactor:_,containerSizeLimit:v}=Rr({container:t,tuning:r,limits:i,panelSize:g}),y=r.considerPlaybackRate&&P(s)?s:1,b=zr.get(e);b||(b=e.filter(e=>!ar(e.quality)).sort((e,t)=>rr(e.quality,t.quality)?-1:1),zr.set(e,b));let x=b.at(-1)?.quality,S=b.at(0)?.quality,C=Cr(i,S,x),w=y*Er(o??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},E=null;for(let e of b){if(e.tvDisabled){T[e.quality]=`TvDisabled`;continue}let t=!0;if(v)if(e.size)t=e.size.width<=v.width&&e.size.height<=v.height;else{let n=v&&sr(v);t=n?or(e.quality,n):!0}if(!t){T[e.quality]=`FitsContainer`;continue}let s=m||n,u=P(s)&&isFinite(s)&&P(e.bitrate)?s-a>=e.bitrate*w:!0,h=i?.min===e.quality||P(i?.min)&&P(S)&&rr(i.min,S)&&e.quality===S;if(!u&&!h){T[e.quality]=`FitsThroughput`;continue}if(P(l)&&l.quality===e.quality){T[e.quality]=`FailedVideoTrack`;continue}if(r.lazyQualitySwitch&&P(r.minBufferToSwitchUp)&&c&&!ar(c.quality)&&(o??0)<r.minBufferToSwitchUp&&rr(e.quality,c.quality)){T[e.quality]=`Buffer`;continue}if(f&&ir(e.quality,f)&&!h){T[e.quality]=`DroppedFramesLimit`;continue}if(p&&ir(e.quality,p)&&!h){T[e.quality]=`StallsLimit`;continue}let g=C||(tr(i?.max)||or(e.quality,i.max))&&(tr(i?.min)||ir(e.quality,i.min)),_=P(d)&&!d?or(e.quality,r.backgroundVideoQualityLimit):!0;if(!g||!_){T[e.quality]=`FitsQualityLimits`;continue}E||=e}E&&E.bitrate&&Tr.next(E.bitrate);let ee=E??b.at(-1)??e[0],te=u?.last,D=Ir(r,h,ee,u);return P(u)&&D.quality!==te?.quality&&h({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
@@ -244,14 +244,14 @@ var e=`2.0.166-dev.2d0cf8810.0`,t;(e=>{e.STOPPED=`stopped`,e.READY=`ready`,e.PLA
|
|
|
244
244
|
selectedTrack: ${e.bitrate}
|
|
245
245
|
lastVideoTrackSelected: ${JSON.stringify(t)}
|
|
246
246
|
tuning.minVideoAudioRatio: ${n.autoTrackSelection.minVideoAudioRatio}
|
|
247
|
-
`}}class lc{static createRule(e,t=ps(1)){switch(e){case`throughput_rule`:return new sc(t);case`min_audio_for_video_rule`:return new cc(t)}}}var uc=ps(1),dc={},fc={},pc=(e,t)=>(t?dc:fc)[e]??uc;class mc{stallsController=new Io;videoAbrController=new ts;audioAbrController=new ts;subscription=new is;lastVideoTrackSelected$=new as(void 0);context;phaseController;allVideoRules=[];init(e){this.context={...this.context,...e},this.initVideoElementAbrContext(),this.stallsController.init({...this.context,tuning:this.context.tuning.stallsManager,lastVideoTrackSelected$:this.lastVideoTrackSelected$});let t=this.context.tuning.dash.abrVideoRules,n=[];if(this.context.tuning.dash.useAbrPhases){this.phaseController=new ms(this.context.isSeeked$);for(let e of t){let t=ac.createRule(e,pc(e,!0));this.allVideoRules.push(t)}n.push(...this.allVideoRules)}else for(let e of t)n.push(ac.createRule(e,pc(e,!1)));let r=this.context.tuning.dash.abrAudioRules.map(e=>lc.createRule(e)),i={...e};this.videoAbrController.init(n,i),this.audioAbrController.init(r,i)}updateContext(e){this.context.isAuto=e.isAuto,this.context.forwardBufferTarget=e.forwardBufferTarget,this.context.currentVideoTrack=e.currentVideoTrack,this.context.desiredVideoTrack=e.desiredVideoTrack,this.context.limits=e.limits,this.context.forwardBufferHealth=e.forwardBufferHealth,this.context.forwardBufferDuration=e.forwardBufferDuration,this.context.forwardVideoBufferRepresentations=e.forwardVideoBufferRepresentations,this.context.forwardAudioBufferRepresentations=e.forwardAudioBufferRepresentations,this.context.videoSegmentLoadProgress=e.videoSegmentLoadProgress,this.context.isLive=e.isLive,this.context.remainingDurationMs=e.remainingDurationMs,this.context.mpdSegmentDurationMs=e.mpdSegmentDurationMs,this.updateTracksIfneeded(e.videoTracks,e.audioTracks)}autoSelectTrack(e){let t=es(this.lastVideoTrackSelected$.getValue(),this.context.videoTracksAsc,this.context.audioTracksAsc??[],this.context.tuning.autoTrackSelection.minVideoAudioRatio)??this.context.audioTracksAsc?.[0],n=this.phaseController?.phase;if(this.videoAbrController.updateContext({videoTracksAsc:this.context.videoTracksAsc,videoTracksDesc:this.context.videoTracksDesc,currentVideoTrack:this.context.currentVideoTrack,tuning:this.context.tuning,abrLogger:this.context.abrLogger,forwardBufferRepresentations:this.context.forwardVideoBufferRepresentations,forwardBufferTarget:this.context.forwardBufferTarget,container:this.context.elementSizeManager?.getValue(),panelSize:this.context.panelSize,estimatedThroughput:this.context.throughput$.getValue(),limits:this.context.limits,reserve:t?.bitrate??0,forwardBufferHealth:this.context.forwardBufferHealth,forwardBufferDuration:this.context.forwardBufferDuration,visible:this.context.elementVisible$.getValue(),playbackRate:this.context.element.playbackRate,lastVideoTrackSelected:this.lastVideoTrackSelected$.getValue(),severeStallOccurred:this.stallsController.severeStallOccurred$.getValue(),lastStallDuration:this.stallsController.lastStallDuration$.getValue(),videoSegmentLoadProgress:this.context.videoSegmentLoadProgress,throughputVariance:this.context.throughputVariance$?.getValue()??0,isLive:this.context.isLive??!1,remainingDurationMs:this.context.remainingDurationMs,mpdSegmentDurationMs:this.context.mpdSegmentDurationMs,phase:n}),this.audioAbrController.updateContext({videoTracksAsc:this.context.videoTracksAsc,videoTracksDesc:this.context.videoTracksDesc,audioTracksAsc:this.context.audioTracksAsc,audioTracksDesc:this.context.audioTracksDesc,tuning:this.context.tuning,abrLogger:this.context.abrLogger,forwardBufferHealth:this.context.forwardBufferHealth,forwardBufferDuration:this.context.forwardBufferDuration,playbackRate:this.context.element.playbackRate,estimatedThroughput:this.context.throughput$.getValue(),reserve:this.lastVideoTrackSelected$.getValue()?.bitrate??0,currentVideoTrack:this.context.currentVideoTrack,lastVideoTrackSelected:this.lastVideoTrackSelected$.getValue(),throughputVariance:0}),e===`audio`)return this.audioAbrController.autoSelectTrack();let r=this.context.desiredVideoTrack;if(this.context.isAuto||rs(r))if(this.phaseController){this.phaseController.updatePhase(this.videoAbrController.context);let e=this.phaseController.phase,t=this.allVideoRules.filter(t=>t.activePhases.has(e));r=this.videoAbrController.autoSelectTrack(t)}else r=this.videoAbrController.autoSelectTrack();return this.lastVideoTrackSelected$.next(r),r}destroy(){this.subscription.unsubscribe(),this.videoAbrController.destroy(),this.audioAbrController.destroy(),this.phaseController?.destroy(),this.stallsController.destroy(),this.context.elementSizeManager?.destroy()}initVideoElementAbrContext(){let e=new as(!1);this.subscription.add(Qi(this.context.element,{threshold:this.context.tuning.autoTrackSelection.activeVideoAreaThreshold}).subscribe(e));let t=Qn(this.context.element);this.subscription.add(()=>t?.destroy());let n;this.context.element instanceof HTMLVideoElement&&(n=new wo,n.connect({video:this.context.element,observableVideo:t})),this.context={...this.context,elementVisible$:e,observableVideo:t,elementSizeManager:n}}updateTracksIfneeded(e=[],t=[]){let{videoTracksAsc:n,videoTracksDesc:r,audioTracksAsc:i,audioTracksDesc:a}=this.context;if(this.isTracksDifferent(e,n,r)){let t=[...e].filter(e=>!ns(e.quality));this.context.videoTracksAsc=[...t].sort(Yo(1)),this.context.videoTracksDesc=[...t].sort(Yo(-1))}this.isTracksDifferent(t,i,a)&&(this.audioAbrController.historyReset(),this.context.audioTracksAsc=[...t].sort(Jo(1)),this.context.audioTracksDesc=[...t].sort(Jo(-1)))}isTracksDifferent(e,t=[],n=[]){let r=!1;for(let i of e)(rs(t.find(e=>i.id===e.id))||rs(n.find(e=>i.id===e.id)))&&(r=!0);return t.length!==e.length&&n.length!==e.length||r}}import{isNonNullable as hc}from"@vkontakte/videoplayer-shared";var gc=e=>isFinite(e)&&e>0,_c=(e,t,n,r)=>e<=t?1:e>=n?r:1+(r-1)*(e-t)/(n-t),vc=(e,t,n,r)=>e<=t?r:e>=n?1:r-(r-1)*(e-t)/(n-t),yc=(e,t)=>{let{throughputKbps:n,currentBitrateKbps:r,baseTargetMs:i}=e,{maxMs:a,optimisticHeadroomLow:o,optimisticHeadroomHigh:s,weakThroughputLowKbps:c,weakThroughputHighKbps:l}=t;if(!gc(n))return i;let u=hc(r)&&r>0?_c(n/r,o,s,t.maxFactor):1,d=vc(n,c,l,t.maxFactor),f=i*Math.max(u,d);return Math.min(Math.max(f,i),Math.max(i,a))};class bc{scene3D;subscription=new Ba;volumeSubscription=new Ba;videoState=new Dt(`stopped`);allocation;observableVideo=null;player;params;tracer;textTracksManager=null;droppedFramesManager=new qi;stallsManager=new _o;elementSizeManager=new wo;abrManager=new mc;videoTracksMap=new Map;audioTracksMap=new Map;textTracksMap=new Map;videoStreamsMap=new Map;audioStreamsMap=new Map;videoTrackSwitchHistory=new Or;audioTrackSwitchHistory=new Or;constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn(e.source.url)),this.params=e,this.allocation=va(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(`DashProviderVirtual`),this.params.output.element$.next(this.allocation.video??void 0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Wr(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;Pa(this.observableVideo)&&(this.observableVideo=Qn(this.allocation.target),this.subscription.add(()=>this.observableVideo?.destroy()));let n=this.constructor.name,r=t=>{e.error$.next({id:n,category:ka.WTF,message:`${n} internal logic error`,thrown:t})};return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:(e,t)=>this.subscription.add(e.subscribe(t,r))}}subscribe(){let{output:e,desiredState:t,observableVideo:n,genericErrorListener:r,connect:i}=this.getProviderSubscriptionInfo(),a=this.allocation.video;a&&this.subscription.add(this.params.output.availableVideoTracks$.pipe(Aa(e=>!!e.length),za()).subscribe(e=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:a,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e})}));let o=this.params.desiredState.seekState.stateChangeEnded$.pipe(Fa(e=>e.to.state!==`none`),ja());this.abrManager.init({isSeeked$:o,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,throughputVariance$:this.params.dependencies.throughputEstimator.throughputVariance$,tuning:this.params.tuning,failedVideoTrack:this.params.failedVideoTrack,element:this.allocation.target,panelSize:this.params.panelSize,abrLogger:this.params.dependencies.abrLogger}),this.stallsManager.init({isSeeked$:o,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$:n.isBuffering$,looped$:n.looped$,playing$:n.playing$,duration:this.allocation.target.duration}),i(n.ended$,e.endedEvent$),i(n.looped$,e.loopedEvent$),i(n.error$,e.error$),i(n.isBuffering$,e.isBuffering$),i(n.currentBuffer$,e.currentNativeBuffer$),i(n.totalBufferDuration$,e.totalBufferDuration$),i(n.bufferRangeCount$,e.bufferRangeCount$),i(n.playing$,e.firstFrameEvent$),i(n.playedTime$,e.playedTime$),i(n.inPiP$,e.inPiP$),i(n.inFullscreen$,e.inFullscreen$),i(n.loadedMetadata$,e.loadedMetadataEvent$),i(this.player.currentBuffer$.pipe(Aa(e=>e.to>0),za(),Ia(void 0)),e.canplay$),i(this.player.error$,e.error$),i(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),i(this.player.fetcherError$,e.fetcherError$),i(this.player.updateDurationError$,e.updateDurationError$),i(this.player.videoLastDataObtainedTimestamp$,e.videoLastDataObtainedTimestamp$),i(this.player.lastConnectionType$,e.httpConnectionType$),i(this.player.lastConnectionReused$,e.httpConnectionReused$),i(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),i(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),i(this.player.isLive$,e.isLive$),i(this.player.currentBuffer$,e.currentBuffer$),i(this.player.lastRequestFirstBytes$.pipe(Aa(Na),za()),e.firstBytesEvent$),i(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),i(this.videoState.stateChangeEnded$.pipe(Fa(e=>e.to)),this.params.output.playbackState$),this.subscription.add(n.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wn(this.allocation.target,t.isLooped,r)),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),r)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,r))})),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:n}),this.subscription.add(Tn(this.allocation.target,t.volume,n.volumeState$,r,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(En(this.allocation.target,t.playbackRate,n.playbackRateState$,r)),this.allocation.video&&this.elementSizeManager.connect({video:this.allocation.video,observableVideo:n}),i(Qi(this.allocation.target,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(n.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`),this.scene3D&&this.scene3D.play()},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},r)).add(n.canplay$.subscribe(()=>{this.videoState.getState()===`playing`&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(n.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(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:e})=>{if(e===`manifest_ready`){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let e=this.player.getStreams(),t=this.player.getCodecs();if(Da(e,`Manifest not loaded or empty`),!this.params.tuning.isAudioDisabled){let t=[];for(let n of e.audio){t.push(qa(n));let e=[];for(let t of n.representations){let r=Wa(t);e.push(r),this.audioTracksMap.set(r,{stream:n,representation:t})}this.audioStreamsMap.set(n,e)}this.params.output.availableAudioStreams$.next(t)}let n=[];for(let t of e.video){n.push(Ja(t));let e=[];for(let n of t.representations){let r=Ua({...n,streamId:t.id});r&&(e.push(r),this.videoTracksMap.set(r,{stream:t,representation:n}))}this.videoStreamsMap.set(t,e)}this.params.output.availableVideoStreams$.next(n);for(let t of e.text)for(let e of t.representations){let n=Ga(t,e);this.textTracksMap.set(n,{stream:t,representation:e})}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),t?.video&&this.params.output.availableVideoCodecs$.next(t.video),t?.audio&&this.params.output.availableAudioCodecs$.next(t.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else e===`representations_ready`&&(this.videoState.setState(`ready`),this.player.initBuffer())},r));let s=La(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$,Ma(this.allocation.target,`progress`)).pipe(Aa(()=>this.videoTracksMap.size>0||this.params.tuning.audioOnly&&this.audioTracksMap.size>0)),{abrThrottle:c}=this.params.tuning.dash;c&&(s=s.pipe(Va(c))),this.subscription.add(s.subscribe(async()=>{let e=this.player.state$.getState(),n=this.player.state$.getTransition(),r=t.autoVideoTrackSwitching.getState()?`lazy`:`default`;if(e!==`manifest_ready`&&e!==`running`||n)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let i=this.selectVideoAudioRepresentations();if(!i){if(this.params.tuning.audioOnly&&this.audioStreamsMap.size){let[,[t]]=this.audioStreamsMap.entries().next().value;e===`manifest_ready`&&await this.player.initRepresentations(void 0,t.id,this.params.sourceHls)}return}let[a,o]=i,s=[...this.videoTracksMap.keys()].find(e=>this.videoTracksMap.get(e)?.representation.id===a.id);Na(s)&&(this.stallsManager.lastVideoTrackSelected=s);let c=this.params.desiredState.autoVideoTrackLimits.getTransition();c&&this.params.output.autoVideoTrackLimits$.next(c.to),e===`manifest_ready`?await this.player.initRepresentations(a.id,o?.id,this.params.sourceHls):(await this.player.switchRepresentation(`video`,a.id,r),o&&await this.player.switchRepresentation(`audio`,o.id,`default`))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:e})=>{this.scene3D&&e&&this.scene3D.pointCameraTo(e.x,e.y)})),this.subscription.add(this.elementSizeManager.subscribe(e=>{this.scene3D&&e&&this.scene3D.setViewportSize(e.width,e.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ja()).subscribe(t=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.videoStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.videoStream.setState(a.to),e.currentVideoTrack$.next(r),e.currentVideoStream$.next(Ja(i))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ja()).subscribe(t=>{let n=[...this.audioTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentAudioStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.audioStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.audioStream.setState(a.to),e.currentAudioStream$.next(qa(i))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(t=>{if(t?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(t),e.is3DVideo$.next(!0)}catch(t){e.warning$.next({id:`DashProvider`,message:`DashProvider could not initialize 3D-scene: ${t}`})}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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Fa(({to:e})=>e===`ready`),ja()),u=[l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ra([`init`])];this.params.tuning.dash.useDynamicBufferTarget&&u.push(this.params.dependencies.throughputEstimator.throughput$,e.currentVideoTrack$,n.currentBuffer$),this.subscription.add(La(...u).subscribe(()=>this.syncBufferTarget())),this.subscription.add(La(l,this.player.state$.stateChangeEnded$,Ra([`init`])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===`ready`)));let d=La(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ra([`init`])).pipe(Oa(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}syncBufferTarget(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.playbackState.getState()===`ready`,n=this.resolveBufferTargetMs(e,t);this.player.setBufferTarget(n,this.resolveAudioBufferTargetMs(e,t))}resolveAudioBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?Math.min(this.player.getVideoForwardBufferDuration()+n.audioBufferAheadOfVideoMs,n.forwardBufferTargetAuto):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}resolveBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?yc({throughputKbps:this.params.dependencies.throughputEstimator.throughput$.getValue(),currentBitrateKbps:this.getCurrentVideoBitrateKbps(),baseTargetMs:n.forwardBufferTargetAuto},n.dynamicBufferTarget):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}getCurrentVideoBitrateKbps(){let e=this.params.output.currentVideoTrack$.getValue();if(Pa(e))return null;let t=this.player.getForwardBufferRepresentations(`video`)?.get(e.id),n=Go(t);return isFinite(n)?n:e.bitrate}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pr:Nr,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Hr,n=this.params.tuning.useNewAutoSelectVideoTrack?Br:Vr,{desiredState:r,output:i}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:e})=>e===o),c=i.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:e})=>e===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let f=this.player.bufferLength$.getValue(),p;p=this.player.isActiveLive$.getValue()?this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.allocation.target.duration*1e3||1/0)-this.allocation.target.currentTime*1e3,h=Math.min(f/Math.min(p,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),_=[...this.audioStreamsMap.keys()].find(({id:e})=>e===g?.id)??this.audioStreamsMap.keys().next().value,v=0;if(_){if(s&&!a){let t=e(s,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}if(c){let t=e(c,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}}let y=this.player.isLive$.getValue(),b=this.allocation.target.duration*1e3,x=!y&&Number.isFinite(b)&&b>0?Math.max(0,b-this.allocation.target.currentTime*1e3):void 0,S=this.params.tuning.dash.useAbrPhases?{videoSegmentLoadProgress:this.player.getActiveVideoSegmentProgress(),isLive:y,remainingDurationMs:x,mpdSegmentDurationMs:this.player.getMpdVideoSegmentDuration()}:{};this.abrManager.updateContext({isAuto:a,videoTracks:d,audioTracks:_?this.audioStreamsMap.get(_)??[]:[],currentVideoTrack:c,desiredVideoTrack:s,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:h,forwardBufferDuration:f,forwardBufferTarget:p,forwardVideoBufferRepresentations:this.player.getForwardBufferRepresentations(`video`),forwardAudioBufferRepresentations:this.player.getForwardBufferRepresentations(`audio`),...S});let C=s,w;this.params.tuning.dash.useNewAbr?(C=this.abrManager.autoSelectTrack(`video`),w=_&&this.abrManager.autoSelectTrack(`audio`)):((a||!C)&&(C=n(d,{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:v,forwardBufferHealth:h,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger})),w=_&&t(C,d,this.audioStreamsMap.get(_)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,abrLogger:this.params.dependencies.abrLogger}));let T=this.videoTracksMap.get(C)?.representation,E=w&&this.audioTracksMap.get(w)?.representation;if(T&&E)return[T,E];if(T&&!E&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.allocation.target,this.params.source.url,e)}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===`requested`&&n?.to!==`paused`&&e!==`stopped`&&t!==`stopped`&&this.seek(r.position,r.forcePrecise),t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.player.stop(),this.allocation.target.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`),k(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`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`);return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):t===`playing`&&this.allocation.target.paused?this.playIfAllowed():n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return Ea(e)}}};init3DScene=e=>{if(this.scene3D)return;let t=this.params.container,n=this.allocation.video;if(!t||!n)return;this.scene3D=new eo(t,n,{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 r=this.elementSizeManager.getValue();r&&this.scene3D.setViewportSize(r.width,r.height)};destroy3DScene=()=>{this.scene3D&&=(this.scene3D.destroy(),void 0)};playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:ka.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Ra(e).subscribe(t,n)):e.then(t,n)}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.abrManager.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),on(this.allocation.target,this.params.tuning),this.tracer.end()}}import{AbortControllerPolyfilled as xc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Sc}from"@vkontakte/videoplayer-shared";var Cc=e=>{if(!e)return{id:`EmptyResponse`,category:Sc.PARSER,message:`Empty response`};if(e.length<=2&&e.match(/^\d+$/))return{id:`UVError#${e}`,category:Sc.NETWORK,message:`UV Error ${e}`};let t=e.trimStart().substring(0,100).toLowerCase();if(t.startsWith(`<!doctype`)||t.startsWith(`<html>`)||t.startsWith(`<body>`)||t.startsWith(`<head>`))return{id:`UnexpectedHTML`,category:Sc.NETWORK,message:`Received unexpected HTML, possibly a ISP block`};if(t.startsWith(`<?xml`))return new DOMParser().parseFromString(e,`text/xml`).querySelector(`parsererror`)?{id:`InvalidXML`,category:Sc.PARSER,message:`XML parsing error`}:{id:`XMLParserLogicError`,category:Sc.PARSER,message:`Response is valid XML, but parser failed`}};import{abortable as wc,assertNonNullable as Tc,ErrorCategory as Ec,filter as Dc,filterChanged as Oc,flattenObject as kc,fromEvent as Ac,getTraceSubscriptionMethod as jc,getWindow as Mc,interval as Nc,isNonNullable as Pc,isNullable as Fc,map as Ic,merge as Lc,now as Rc,Subject as zc,Subscription as Bc,SubscriptionRemovable as Vc,ValueSubject as R}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as Hc}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Uc}from"@vkontakte/videoplayer-shared";var Wc=e=>{let t=new URL(e);return t.searchParams.set(`quic`,`1`),t.toString()},Gc=e=>{let t=e.get(`X-Delivery-Type`),n=e.get(`X-Reused`);return{type:t===null?`http1`:t??void 0,reused:n===null?void 0:{1:!0,0:!1}[n]??void 0}};import{abortable as Kc,assertNever as qc,ErrorCategory as Jc,flattenObject as Yc,fromEvent as Xc,getWindow as Zc,merge as Qc,now as $c,Subject as el,Subscription as tl,suppressAbort as nl,ValueSubject as rl}from"@vkontakte/videoplayer-shared";var il=e=>{let t=new URL(e);return t.searchParams.set(`enable-subtitles`,`yes`),t.toString()};import{ErrorCategory as al}from"@vkontakte/videoplayer-shared";var ol=new Set([2,3,4,5,6,9,19]),sl=new Set([1,8,18,21]),cl=new Set([10,11,12,13,14,15,16]),ll=({txtCode:e,error$:t,recoverableError$:n,httpCode:r})=>{let i=parseInt(e);if(isNaN(i))return;let a={...ul(i),httpCode:r,UVBackendErrorCode:e};if(ol.has(i)){t.next({...a,category:al.NETWORK,origin:`segment_fetcher`});return}if(sl.has(i)){n.next({...a,category:al.FATAL,origin:`segment_fetcher`,canBeRecoverable:!0});return}if(cl.has(i)){t.next({...a,category:al.FATAL,origin:`segment_fetcher`});return}},ul=e=>{switch(e){case 1:return{id:`VideoDataLinkExpiredError`,message:`Video data links have expired`};case 5:return{id:`VideoServerError`,message:`Server error`};case 8:return{id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`};case 10:return{id:`UserAgentChange`,message:`User agent changed`};case 11:return{id:`forbiddenReferer`,message:`Forbidden referer`};case 12:case 13:case 14:case 15:case 16:return{id:`OKerror`,message:`Error #${e}`};case 18:return{id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`};case 21:return{id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`};default:return dl(e)}};function dl(e){return{id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${e})`}}import{devNull as fl,getWindow as pl}from"@vkontakte/videoplayer-shared";var ml=`vk_player_cached_fetches`,hl=[`fromCache`,`expires`,`sig`],gl=300*1e3,_l=`x-cache-expires`,vl=async e=>{let t=bl(e),n=await pl().caches.open(ml);return{get:async()=>{let e=await n.match(t);return e&&!xl(e)?(fl.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_hit`]}),e):(e&&(await n.delete(t),fl.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_missed`,`expired`]})),null)},set:async r=>{await n.put(t,Sl(r,e))}}};function yl(){return typeof caches<`u`}function bl(e){try{let t=new URL(e);return t.hostname=`cache.local`,hl.forEach(e=>t.searchParams.delete(e)),t.toString()}catch{return e}}function xl(e){let t=e.headers.get(_l);if(!t)return!0;let n=Number(t);return isNaN(n)||n<=Date.now()}function Sl(e,t){let n=e.clone();return new Response(n.body,{status:n.status,statusText:n.statusText,headers:new Headers({...Array.from(n.headers.entries()),[_l]:Cl(t).toString()})})}function Cl(e){try{let t=new URL(e).searchParams.get(`expires`);if(t&&!isNaN(Number(t)))return Number(t)}catch{return 0}return Date.now()+gl}class wl{throughputEstimator;requestQuic;tracer;manifestRequested=new el;manifestReceived=new el;firstBytesRequested=new el;firstBytesReceived=new el;lastConnectionType$=new rl(void 0);lastConnectionReused$=new rl(void 0);lastRequestFirstBytes$=new rl(void 0);lastConnectionMetrics$=new rl(void 0);lastDownloadMetrics$=new rl(void 0);recoverableError$=new el;error$=new el;abortAllController=new Hc;subscription=new tl;compatibilityMode;useEnableSubtitlesParam;useUrlCacheMechanism;measureNonSegmentRequests;startupPhase=!0;performanceObserver=null;pendingConnectionMetrics=new Map;handleExtendedNetworkErrorsSet=!1;constructor({throughputEstimator:e,requestQuic:t,tracer:n,compatibilityMode:r=!1,useEnableSubtitlesParam:i=!1,handleExtendedNetworkErrorsSet:a=!1,useUrlCacheMechanism:o=!1,measureNonSegmentRequests:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=n.createComponentTracer(`Fetcher`),this.useEnableSubtitlesParam=i,this.handleExtendedNetworkErrorsSet=a,this.measureNonSegmentRequests=s,Zc().PerformanceObserver&&this.setupPerformanceObserver(),this.useUrlCacheMechanism=o}onHeadersReceived(e){let{type:t,reused:n}=Gc(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(n)}setupPerformanceObserver(){this.performanceObserver=new(Zc()).PerformanceObserver(e=>{e.getEntriesByType(`resource`).forEach(e=>{this.processResourceTiming(e)})}),this.performanceObserver.observe({entryTypes:[`resource`]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let n=this.extractConnectionMetrics(e);n&&this.lastConnectionMetrics$.next(n)}estimateNetworkType(){if(!(`connection`in Zc().navigator))return`unknown`;let e=Zc().navigator.connection;return e.effectiveType?{"slow-2g":`2g`,"2g":`2g`,"3g":`3g`,"4g":`lte`}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?`2g`:e.downlink<5?`3g`:e.downlink<50?`lte`:`wifi`:e.rtt?e.rtt>500?`2g`:e.rtt>250?`3g`:e.rtt>50?`lte`:`wifi`:`unknown`}extractConnectionMetrics(e){let t=0,n=0,r=0,i=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(i=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,n=e.secureConnectionStart-e.connectStart):n=i),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,n),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,i),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,n]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),i=r.origin+r.pathname,a=new URL(n.url);if(i===a.origin+a.pathname&&e.startTime>=n.startTime-10&&e.startTime<=n.startTime+1e3)return t}}catch{this.recoverableError$.next({id:`VideoDataFetchError`,message:`Video data fetch error with getting download metrics`,category:Jc.WTF})}return null}trackRequestStart(e,t){let n=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(n,{url:e,startTime:t})}fetchManifest=Kc(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer(`FetchManifest`),n=e;this.requestQuic&&(n=Wc(n)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(n=il(n)),this.trackRequestStart(n,performance.now());let r=$c();this.manifestRequested.next();let i=yield this.doFetch(n,{signal:this.abortAllController.signal}).catch(nl);if(i){let a=$c();t.log(`success`,Yc({url:n,message:`Request successfully executed`})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(i.headers);let o=i.headers.get(`content-length`),s=0;o&&(s=parseInt(o,10));let c=await i.text();if((!o||isNaN(s)||s<=0)&&(s=new TextEncoder().encode(c).length),s>0){let t=a-r,n=s/(t/1e3)*8/1024,i={bytes:s,speed:n,url:e};this.lastDownloadMetrics$.next(i)}if(this.measureNonSegmentRequests&&this.startupPhase&&(this.throughputEstimator?.addRawRtt(a-r),o&&s>0)){let e=$c();this.throughputEstimator?.addRawSpeed(s,e-r)}return c}else return t.error(`error`,Yc({url:n,message:`No data in request manifest`})),t.end(),null}.bind(this));fetch=Kc(this.abortAllController.signal,async function*(e,{rangeMethod:t=+!this.compatibilityMode,range:n,onProgress:r,priority:i=`auto`,signal:a,measureThroughput:o=!0,isLowLatency:s=!1,bufferOptimisation:c=!1,urlCacheMechanismEnabled:l}={}){let u=e,d=new Headers,f=this.tracer.createComponentTracer(`Fetch`);if(n)switch(t){case 0:d.append(`Range`,`bytes=${n.from}-${n.to}`);break;case 1:{let e=new URL(u,Zc().location.href);e.searchParams.append(`bytes`,`${n.from}-${n.to}`),u=e.toString();break}default:qc(t)}this.requestQuic&&(u=Wc(u));let p=this.abortAllController.signal,m;if(a){let e=new Hc;if(m=Qc(Xc(this.abortAllController.signal,`abort`),Xc(a,`abort`)).subscribe(()=>{try{e.abort()}catch(e){nl(e)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{e.abort()}catch(e){nl(e)}p=e.signal}let h=0,g=$c();f.log(`startRequest`,Yc({url:u,priority:i,rangeMethod:t,range:n,isLowLatency:s,requestStartedAt:g})),this.trackRequestStart(u,performance.now()),this.firstBytesRequested.next();let _=yield this.doFetch(u,{priority:i,headers:d,signal:p},{urlCacheMechanismEnabled:l}).catch(nl),v=$c();if(!_)return f.error(`error`,{message:`No response in request`}),f.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-g),!_.ok||!_.body){m?.unsubscribe();let e=`Fetch error ${_.status}: ${_.statusText}`;return f.error(`error`,{message:e}),f.end(),Promise.reject(Error(`Fetch error ${_.status}: ${_.statusText}`))}if(this.onHeadersReceived(_.headers),!r&&!o){let e=yield _.arrayBuffer(),t=$c();if(this.measureNonSegmentRequests&&this.startupPhase){let e=_.headers.get(`content-length`),n=e?parseInt(e,10):NaN;Number.isFinite(n)&&n>0&&this.throughputEstimator?.addRawSpeed(n,t-g)}let n={requestStartedAt:g,requestEndedAt:t,duration:t-g};return f.log(`endRequest`,Yc(n)),f.end(),m?.unsubscribe(),e}let y=_.body;if(o){this.startupPhase=!1;let e;[y,e]=_.body.tee(),this.throughputEstimator?.trackStream(e,s)}let b=y.getReader(),x,S=parseInt(_.headers.get(`content-length`)??``,10);Number.isFinite(S)&&(x=S),!x&&n&&(x=n.to-n.from+1);let C=x?new Uint8Array(x):new Uint8Array,w=!1,T=e=>{m?.unsubscribe(),w=!0,nl(e)},E=Kc(p,async function*({done:e,value:t}){if(h===0&&(this.lastRequestFirstBytes$.next($c()-g),this.firstBytesReceived.next()),p.aborted){m?.unsubscribe();return}if(!e&&t){if(c&&x)C.set(t,h),h+=t.byteLength;else{let e=new Uint8Array(C.length+t.length);e.set(C),e.set(t,C.length),C=e,h+=t.byteLength}r?.(new DataView(C.buffer),h),yield b?.read().then(E,T)}}.bind(this));yield b?.read().then(E,T),m?.unsubscribe();let ee=$c(),te={failed:w,requestStartedAt:g,requestEndedAt:ee,duration:ee-g};if(w)return f.error(`endRequest`,Yc(te)),f.end(),null;if(h>0){let t=ee-g,n=h/(t/1e3)*8/1024,r={bytes:h,speed:n,url:e};this.lastDownloadMetrics$.next(r)}return f.log(`endRequest`,Yc(te)),f.end(),C.buffer}.bind(this));async fetchRepresentation(e,t,n,r=`auto`){let{type:i}=e;switch(i){case`byteRange`:return this.fetchByteRangeRepresentation(e,t,n,r)??null;case`template`:return this.fetchTemplateRepresentation(e,n,r)??null;default:qc(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&=(this.performanceObserver.disconnect(),null),this.pendingConnectionMetrics.clear(),this.tracer.end()}fetchByteRangeRepresentation=Kc(this.abortAllController.signal,async function*(e,t,n,r){if(e.type!==`byteRange`)return null;let{from:i,to:a}=e.initRange,o=i,s=a,c=!1,l,u;e.indexRange&&(l=e.indexRange.from,u=e.indexRange.to,c=a+1===l,c&&(o=Math.min(l,i),s=Math.max(u,a))),o=Math.min(o,0);let d=yield this.fetch(e.url,{range:{from:o,to:s},priority:r,signal:n,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!d)return null;let f=new DataView(d,i-o,a-o+1);if(!t.validateData(f))throw Error(`Invalid media file`);let p=t.parseInit(f),m=e.indexRange??t.getIndexRange(p);if(!m)throw ReferenceError(`No way to load representation index`);let h;if(c)h=new DataView(d,m.from-o,m.to-m.from+1);else{let t=yield this.fetch(e.url,{range:m,priority:r,signal:n,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!t)return null;h=new DataView(t)}let g=t.parseSegments(h,p,m).map(e=>({...e,networkStatus:`none`,bufferStatus:`none`}));return{initMetadata:p,initDataView:new DataView(d),segments:g}}.bind(this));fetchTemplateRepresentation=Kc(this.abortAllController.signal,async function*(e,t,n){if(e.type!==`template`)return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:n,signal:t,measureThroughput:!1});if(!i)return null;let a=e.segments.map(e=>({...e,networkStatus:`none`,bufferStatus:`none`,size:void 0}));return{initMetadata:null,initDataView:new DataView(i),segments:a}}.bind(this));async doFetch(e,t,n={}){let r;if(this.useUrlCacheMechanism&&n.urlCacheMechanismEnabled&&yl()){r=await vl(e);let t=await r.get();if(t)return t}let i=await Uc(e,t);if(i.ok)return await r?.set(i),i;let a=await i.text();if(this.handleExtendedNetworkErrorsSet){ll({txtCode:a,httpCode:i.status,error$:this.error$,recoverableError$:this.recoverableError$});return}let o=parseInt(a);if(!isNaN(o))switch(o){case 1:this.recoverableError$.next({id:`VideoDataLinkExpiredError`,message:`Video data links have expired`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;default:this.error$.next({id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${o})`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a})}}}var Tl=e=>{let[t,...n]=e.split(`.`);if(!t)return!1;switch(t){case`av01`:{let[e,t,r]=n;return!!(r&&parseInt(r,10)>8)}case`vp09`:{let[e,t,r]=n;return!!(e&&parseInt(e,10)>=2&&r&&parseInt(r,10)>8)}case`avc1`:{let e=n[0];if(!e||e.length!==6)return!1;let[t,r]=e.toUpperCase(),i=t+r;return[`6E`,`7A`,`F4`].includes(i)}}return!1};import{isNonNullable as El,isNullable as Dl}from"@vkontakte/videoplayer-shared";var Ol=e=>{if(e.includes(`/`)){let t=e.split(`/`);return parseInt(t[0])/parseInt(t[1])}else return parseFloat(e)},kl=e=>{try{let t=Al(),{groups:n}=e.match(t)??{};if(n){let e={};if(n.extensions){let t=n.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(t||[]).forEach(t=>{e[t[0]]=t.slice(2)})}let t=n.variants?.split(/-/).filter(e=>e!==``),r={extlang:n.extlang,langtag:n.langtag,language:n.language,privateuse:n.privateuse||n.privateuse2,region:n.region,script:n.script,extensions:e,variants:t};return Object.keys(r).forEach(e=>{let t=r[e];(t===void 0||t===``)&&delete r[e]}),r}return null}catch{return null}};function Al(){let e=`x(?:-[a-z0-9]{1,8})+`,t=`^(?:(?<langtag>${`
|
|
247
|
+
`}}class lc{static createRule(e,t=ps(1)){switch(e){case`throughput_rule`:return new sc(t);case`min_audio_for_video_rule`:return new cc(t)}}}var uc=ps(1),dc={},fc={},pc=(e,t)=>(t?dc:fc)[e]??uc;class mc{stallsController=new Io;videoAbrController=new ts;audioAbrController=new ts;subscription=new is;lastVideoTrackSelected$=new as(void 0);context;phaseController;allVideoRules=[];init(e){this.context={...this.context,...e},this.initVideoElementAbrContext(),this.stallsController.init({...this.context,tuning:this.context.tuning.stallsManager,lastVideoTrackSelected$:this.lastVideoTrackSelected$});let t=this.context.tuning.dash.abrVideoRules,n=[];if(this.context.tuning.dash.useAbrPhases){this.phaseController=new ms(this.context.isSeeked$);for(let e of t){let t=ac.createRule(e,pc(e,!0));this.allVideoRules.push(t)}n.push(...this.allVideoRules)}else for(let e of t)n.push(ac.createRule(e,pc(e,!1)));let r=this.context.tuning.dash.abrAudioRules.map(e=>lc.createRule(e)),i={...e};this.videoAbrController.init(n,i),this.audioAbrController.init(r,i)}updateContext(e){this.context.isAuto=e.isAuto,this.context.forwardBufferTarget=e.forwardBufferTarget,this.context.currentVideoTrack=e.currentVideoTrack,this.context.desiredVideoTrack=e.desiredVideoTrack,this.context.limits=e.limits,this.context.forwardBufferHealth=e.forwardBufferHealth,this.context.forwardBufferDuration=e.forwardBufferDuration,this.context.forwardVideoBufferRepresentations=e.forwardVideoBufferRepresentations,this.context.forwardAudioBufferRepresentations=e.forwardAudioBufferRepresentations,this.context.videoSegmentLoadProgress=e.videoSegmentLoadProgress,this.context.isLive=e.isLive,this.context.remainingDurationMs=e.remainingDurationMs,this.context.mpdSegmentDurationMs=e.mpdSegmentDurationMs,this.updateTracksIfneeded(e.videoTracks,e.audioTracks)}autoSelectTrack(e){let t=es(this.lastVideoTrackSelected$.getValue(),this.context.videoTracksAsc,this.context.audioTracksAsc??[],this.context.tuning.autoTrackSelection.minVideoAudioRatio)??this.context.audioTracksAsc?.[0],n=this.phaseController?.phase;if(this.videoAbrController.updateContext({videoTracksAsc:this.context.videoTracksAsc,videoTracksDesc:this.context.videoTracksDesc,currentVideoTrack:this.context.currentVideoTrack,tuning:this.context.tuning,abrLogger:this.context.abrLogger,forwardBufferRepresentations:this.context.forwardVideoBufferRepresentations,forwardBufferTarget:this.context.forwardBufferTarget,container:this.context.elementSizeManager?.getValue(),panelSize:this.context.panelSize,estimatedThroughput:this.context.throughput$.getValue(),limits:this.context.limits,reserve:t?.bitrate??0,forwardBufferHealth:this.context.forwardBufferHealth,forwardBufferDuration:this.context.forwardBufferDuration,visible:this.context.elementVisible$.getValue(),playbackRate:this.context.element.playbackRate,lastVideoTrackSelected:this.lastVideoTrackSelected$.getValue(),severeStallOccurred:this.stallsController.severeStallOccurred$.getValue(),lastStallDuration:this.stallsController.lastStallDuration$.getValue(),videoSegmentLoadProgress:this.context.videoSegmentLoadProgress,throughputVariance:this.context.throughputVariance$?.getValue()??0,isLive:this.context.isLive??!1,remainingDurationMs:this.context.remainingDurationMs,mpdSegmentDurationMs:this.context.mpdSegmentDurationMs,phase:n}),this.audioAbrController.updateContext({videoTracksAsc:this.context.videoTracksAsc,videoTracksDesc:this.context.videoTracksDesc,audioTracksAsc:this.context.audioTracksAsc,audioTracksDesc:this.context.audioTracksDesc,tuning:this.context.tuning,abrLogger:this.context.abrLogger,forwardBufferHealth:this.context.forwardBufferHealth,forwardBufferDuration:this.context.forwardBufferDuration,playbackRate:this.context.element.playbackRate,estimatedThroughput:this.context.throughput$.getValue(),reserve:this.lastVideoTrackSelected$.getValue()?.bitrate??0,currentVideoTrack:this.context.currentVideoTrack,lastVideoTrackSelected:this.lastVideoTrackSelected$.getValue(),throughputVariance:0}),e===`audio`)return this.audioAbrController.autoSelectTrack();let r=this.context.desiredVideoTrack;if(this.context.isAuto||rs(r))if(this.phaseController){this.phaseController.updatePhase(this.videoAbrController.context);let e=this.phaseController.phase,t=this.allVideoRules.filter(t=>t.activePhases.has(e));r=this.videoAbrController.autoSelectTrack(t)}else r=this.videoAbrController.autoSelectTrack();return this.lastVideoTrackSelected$.next(r),r}destroy(){this.subscription.unsubscribe(),this.videoAbrController.destroy(),this.audioAbrController.destroy(),this.phaseController?.destroy(),this.stallsController.destroy(),this.context.elementSizeManager?.destroy()}initVideoElementAbrContext(){let e=new as(!1);this.subscription.add(Qi(this.context.element,{threshold:this.context.tuning.autoTrackSelection.activeVideoAreaThreshold}).subscribe(e));let t=Qn(this.context.element);this.subscription.add(()=>t?.destroy());let n;this.context.element instanceof HTMLVideoElement&&(n=new wo,n.connect({video:this.context.element,observableVideo:t})),this.context={...this.context,elementVisible$:e,observableVideo:t,elementSizeManager:n}}updateTracksIfneeded(e=[],t=[]){let{videoTracksAsc:n,videoTracksDesc:r,audioTracksAsc:i,audioTracksDesc:a}=this.context;if(this.isTracksDifferent(e,n,r)){let t=[...e].filter(e=>!ns(e.quality));this.context.videoTracksAsc=[...t].sort(Yo(1)),this.context.videoTracksDesc=[...t].sort(Yo(-1))}this.isTracksDifferent(t,i,a)&&(this.audioAbrController.historyReset(),this.context.audioTracksAsc=[...t].sort(Jo(1)),this.context.audioTracksDesc=[...t].sort(Jo(-1)))}isTracksDifferent(e,t=[],n=[]){let r=!1;for(let i of e)(rs(t.find(e=>i.id===e.id))||rs(n.find(e=>i.id===e.id)))&&(r=!0);return t.length!==e.length&&n.length!==e.length||r}}import{isNonNullable as hc}from"@vkontakte/videoplayer-shared";var gc=e=>isFinite(e)&&e>0,_c=(e,t,n,r)=>e<=t?1:e>=n?r:1+(r-1)*(e-t)/(n-t),vc=(e,t,n,r)=>e<=t?r:e>=n?1:r-(r-1)*(e-t)/(n-t),yc=(e,t)=>{let{throughputKbps:n,currentBitrateKbps:r,baseTargetMs:i}=e,{maxMs:a,optimisticHeadroomLow:o,optimisticHeadroomHigh:s,weakThroughputLowKbps:c,weakThroughputHighKbps:l}=t;if(!gc(n))return i;let u=hc(r)&&r>0?_c(n/r,o,s,t.maxFactor):1,d=vc(n,c,l,t.maxFactor),f=i*Math.max(u,d);return Math.min(Math.max(f,i),Math.max(i,a))};class bc{scene3D;subscription=new Ba;volumeSubscription=new Ba;videoState=new Dt(`stopped`);allocation;observableVideo=null;player;params;tracer;textTracksManager=null;droppedFramesManager=new qi;stallsManager=new _o;elementSizeManager=new wo;abrManager=new mc;videoTracksMap=new Map;audioTracksMap=new Map;textTracksMap=new Map;videoStreamsMap=new Map;audioStreamsMap=new Map;videoTrackSwitchHistory=new Or;audioTrackSwitchHistory=new Or;constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn(e.source.url)),this.params=e,this.allocation=va(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(`DashProviderVirtual`),this.params.output.element$.next(this.allocation.video??void 0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Wr(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;Pa(this.observableVideo)&&(this.observableVideo=Qn(this.allocation.target),this.subscription.add(()=>this.observableVideo?.destroy()));let n=this.constructor.name,r=t=>{e.error$.next({id:n,category:ka.WTF,message:`${n} internal logic error`,thrown:t})};return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:(e,t)=>this.subscription.add(e.subscribe(t,r))}}subscribe(){let{output:e,desiredState:t,observableVideo:n,genericErrorListener:r,connect:i}=this.getProviderSubscriptionInfo(),a=this.allocation.video;a&&this.subscription.add(this.params.output.availableVideoTracks$.pipe(Aa(e=>!!e.length),za()).subscribe(e=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:a,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e})}));let o=this.params.desiredState.seekState.stateChangeEnded$.pipe(Fa(e=>e.to.state!==`none`),ja());this.abrManager.init({isSeeked$:o,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,throughputVariance$:this.params.dependencies.throughputEstimator.throughputVariance$,tuning:this.params.tuning,failedVideoTrack:this.params.failedVideoTrack,element:this.allocation.target,abrLogger:this.params.dependencies.abrLogger}),this.stallsManager.init({isSeeked$:o,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$:n.isBuffering$,looped$:n.looped$,playing$:n.playing$,duration:this.allocation.target.duration}),i(n.ended$,e.endedEvent$),i(n.looped$,e.loopedEvent$),i(n.error$,e.error$),i(n.isBuffering$,e.isBuffering$),i(n.currentBuffer$,e.currentNativeBuffer$),i(n.totalBufferDuration$,e.totalBufferDuration$),i(n.bufferRangeCount$,e.bufferRangeCount$),i(n.playing$,e.firstFrameEvent$),i(n.playedTime$,e.playedTime$),i(n.inPiP$,e.inPiP$),i(n.inFullscreen$,e.inFullscreen$),i(n.loadedMetadata$,e.loadedMetadataEvent$),i(this.player.currentBuffer$.pipe(Aa(e=>e.to>0),za(),Ia(void 0)),e.canplay$),i(this.player.error$,e.error$),i(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),i(this.player.fetcherError$,e.fetcherError$),i(this.player.updateDurationError$,e.updateDurationError$),i(this.player.videoLastDataObtainedTimestamp$,e.videoLastDataObtainedTimestamp$),i(this.player.lastConnectionType$,e.httpConnectionType$),i(this.player.lastConnectionReused$,e.httpConnectionReused$),i(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),i(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),i(this.player.isLive$,e.isLive$),i(this.player.currentBuffer$,e.currentBuffer$),i(this.player.lastRequestFirstBytes$.pipe(Aa(Na),za()),e.firstBytesEvent$),i(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),i(this.videoState.stateChangeEnded$.pipe(Fa(e=>e.to)),this.params.output.playbackState$),this.subscription.add(n.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wn(this.allocation.target,t.isLooped,r)),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),r)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,r))})),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:n}),this.subscription.add(Tn(this.allocation.target,t.volume,n.volumeState$,r,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(En(this.allocation.target,t.playbackRate,n.playbackRateState$,r)),this.allocation.video&&this.elementSizeManager.connect({video:this.allocation.video,observableVideo:n}),i(Qi(this.allocation.target,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(n.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`),this.scene3D&&this.scene3D.play()},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},r)).add(n.canplay$.subscribe(()=>{this.videoState.getState()===`playing`&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(n.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(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:e})=>{if(e===`manifest_ready`){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let e=this.player.getStreams(),t=this.player.getCodecs();if(Da(e,`Manifest not loaded or empty`),!this.params.tuning.isAudioDisabled){let t=[];for(let n of e.audio){t.push(qa(n));let e=[];for(let t of n.representations){let r=Wa(t);e.push(r),this.audioTracksMap.set(r,{stream:n,representation:t})}this.audioStreamsMap.set(n,e)}this.params.output.availableAudioStreams$.next(t)}let n=[];for(let t of e.video){n.push(Ja(t));let e=[];for(let n of t.representations){let r=Ua({...n,streamId:t.id});r&&(e.push(r),this.videoTracksMap.set(r,{stream:t,representation:n}))}this.videoStreamsMap.set(t,e)}this.params.output.availableVideoStreams$.next(n);for(let t of e.text)for(let e of t.representations){let n=Ga(t,e);this.textTracksMap.set(n,{stream:t,representation:e})}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),t?.video&&this.params.output.availableVideoCodecs$.next(t.video),t?.audio&&this.params.output.availableAudioCodecs$.next(t.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else e===`representations_ready`&&(this.videoState.setState(`ready`),this.player.initBuffer())},r));let s=La(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$,Ma(this.allocation.target,`progress`)).pipe(Aa(()=>this.videoTracksMap.size>0||this.params.tuning.audioOnly&&this.audioTracksMap.size>0)),{abrThrottle:c}=this.params.tuning.dash;c&&(s=s.pipe(Va(c))),this.subscription.add(s.subscribe(async()=>{let e=this.player.state$.getState(),n=this.player.state$.getTransition(),r=t.autoVideoTrackSwitching.getState()?`lazy`:`default`;if(e!==`manifest_ready`&&e!==`running`||n)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let i=this.selectVideoAudioRepresentations();if(!i){if(this.params.tuning.audioOnly&&this.audioStreamsMap.size){let[,[t]]=this.audioStreamsMap.entries().next().value;e===`manifest_ready`&&await this.player.initRepresentations(void 0,t.id,this.params.sourceHls)}return}let[a,o]=i,s=[...this.videoTracksMap.keys()].find(e=>this.videoTracksMap.get(e)?.representation.id===a.id);Na(s)&&(this.stallsManager.lastVideoTrackSelected=s);let c=this.params.desiredState.autoVideoTrackLimits.getTransition();c&&this.params.output.autoVideoTrackLimits$.next(c.to),e===`manifest_ready`?await this.player.initRepresentations(a.id,o?.id,this.params.sourceHls):(await this.player.switchRepresentation(`video`,a.id,r),o&&await this.player.switchRepresentation(`audio`,o.id,`default`))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:e})=>{this.scene3D&&e&&this.scene3D.pointCameraTo(e.x,e.y)})),this.subscription.add(this.elementSizeManager.subscribe(e=>{this.scene3D&&e&&this.scene3D.setViewportSize(e.width,e.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ja()).subscribe(t=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.videoStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.videoStream.setState(a.to),e.currentVideoTrack$.next(r),e.currentVideoStream$.next(Ja(i))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ja()).subscribe(t=>{let n=[...this.audioTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentAudioStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.audioStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.audioStream.setState(a.to),e.currentAudioStream$.next(qa(i))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(t=>{if(t?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(t),e.is3DVideo$.next(!0)}catch(t){e.warning$.next({id:`DashProvider`,message:`DashProvider could not initialize 3D-scene: ${t}`})}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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Fa(({to:e})=>e===`ready`),ja()),u=[l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ra([`init`])];this.params.tuning.dash.useDynamicBufferTarget&&u.push(this.params.dependencies.throughputEstimator.throughput$,e.currentVideoTrack$,n.currentBuffer$),this.subscription.add(La(...u).subscribe(()=>this.syncBufferTarget())),this.subscription.add(La(l,this.player.state$.stateChangeEnded$,Ra([`init`])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===`ready`)));let d=La(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ra([`init`])).pipe(Oa(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}syncBufferTarget(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.playbackState.getState()===`ready`,n=this.resolveBufferTargetMs(e,t);this.player.setBufferTarget(n,this.resolveAudioBufferTargetMs(e,t))}resolveAudioBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?Math.min(this.player.getVideoForwardBufferDuration()+n.audioBufferAheadOfVideoMs,n.forwardBufferTargetAuto):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}resolveBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?yc({throughputKbps:this.params.dependencies.throughputEstimator.throughput$.getValue(),currentBitrateKbps:this.getCurrentVideoBitrateKbps(),baseTargetMs:n.forwardBufferTargetAuto},n.dynamicBufferTarget):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}getCurrentVideoBitrateKbps(){let e=this.params.output.currentVideoTrack$.getValue();if(Pa(e))return null;let t=this.player.getForwardBufferRepresentations(`video`)?.get(e.id),n=Go(t);return isFinite(n)?n:e.bitrate}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pr:Nr,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Hr,n=this.params.tuning.useNewAutoSelectVideoTrack?Br:Vr,{desiredState:r,output:i}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:e})=>e===o),c=i.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:e})=>e===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let f=this.player.bufferLength$.getValue(),p;p=this.player.isActiveLive$.getValue()?this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.allocation.target.duration*1e3||1/0)-this.allocation.target.currentTime*1e3,h=Math.min(f/Math.min(p,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),_=[...this.audioStreamsMap.keys()].find(({id:e})=>e===g?.id)??this.audioStreamsMap.keys().next().value,v=0;if(_){if(s&&!a){let t=e(s,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}if(c){let t=e(c,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}}let y=this.player.isLive$.getValue(),b=this.allocation.target.duration*1e3,x=!y&&Number.isFinite(b)&&b>0?Math.max(0,b-this.allocation.target.currentTime*1e3):void 0,S=this.params.tuning.dash.useAbrPhases?{videoSegmentLoadProgress:this.player.getActiveVideoSegmentProgress(),isLive:y,remainingDurationMs:x,mpdSegmentDurationMs:this.player.getMpdVideoSegmentDuration()}:{};this.abrManager.updateContext({isAuto:a,videoTracks:d,audioTracks:_?this.audioStreamsMap.get(_)??[]:[],currentVideoTrack:c,desiredVideoTrack:s,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:h,forwardBufferDuration:f,forwardBufferTarget:p,forwardVideoBufferRepresentations:this.player.getForwardBufferRepresentations(`video`),forwardAudioBufferRepresentations:this.player.getForwardBufferRepresentations(`audio`),...S});let C=s,w;this.params.tuning.dash.useNewAbr?(C=this.abrManager.autoSelectTrack(`video`),w=_&&this.abrManager.autoSelectTrack(`audio`)):((a||!C)&&(C=n(d,{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:v,forwardBufferHealth:h,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger})),w=_&&t(C,d,this.audioStreamsMap.get(_)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,abrLogger:this.params.dependencies.abrLogger}));let T=this.videoTracksMap.get(C)?.representation,E=w&&this.audioTracksMap.get(w)?.representation;if(T&&E)return[T,E];if(T&&!E&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.allocation.target,this.params.source.url,e)}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===`requested`&&n?.to!==`paused`&&e!==`stopped`&&t!==`stopped`&&this.seek(r.position,r.forcePrecise),t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.player.stop(),this.allocation.target.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`),k(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`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`);return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):t===`playing`&&this.allocation.target.paused?this.playIfAllowed():n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return Ea(e)}}};init3DScene=e=>{if(this.scene3D)return;let t=this.params.container,n=this.allocation.video;if(!t||!n)return;this.scene3D=new eo(t,n,{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 r=this.elementSizeManager.getValue();r&&this.scene3D.setViewportSize(r.width,r.height)};destroy3DScene=()=>{this.scene3D&&=(this.scene3D.destroy(),void 0)};playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:ka.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Ra(e).subscribe(t,n)):e.then(t,n)}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.abrManager.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),on(this.allocation.target,this.params.tuning),this.tracer.end()}}import{AbortControllerPolyfilled as xc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Sc}from"@vkontakte/videoplayer-shared";var Cc=e=>{if(!e)return{id:`EmptyResponse`,category:Sc.PARSER,message:`Empty response`};if(e.length<=2&&e.match(/^\d+$/))return{id:`UVError#${e}`,category:Sc.NETWORK,message:`UV Error ${e}`};let t=e.trimStart().substring(0,100).toLowerCase();if(t.startsWith(`<!doctype`)||t.startsWith(`<html>`)||t.startsWith(`<body>`)||t.startsWith(`<head>`))return{id:`UnexpectedHTML`,category:Sc.NETWORK,message:`Received unexpected HTML, possibly a ISP block`};if(t.startsWith(`<?xml`))return new DOMParser().parseFromString(e,`text/xml`).querySelector(`parsererror`)?{id:`InvalidXML`,category:Sc.PARSER,message:`XML parsing error`}:{id:`XMLParserLogicError`,category:Sc.PARSER,message:`Response is valid XML, but parser failed`}};import{abortable as wc,assertNonNullable as Tc,ErrorCategory as Ec,filter as Dc,filterChanged as Oc,flattenObject as kc,fromEvent as Ac,getTraceSubscriptionMethod as jc,getWindow as Mc,interval as Nc,isNonNullable as Pc,isNullable as Fc,map as Ic,merge as Lc,now as Rc,Subject as zc,Subscription as Bc,SubscriptionRemovable as Vc,ValueSubject as R}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as Hc}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Uc}from"@vkontakte/videoplayer-shared";var Wc=e=>{let t=new URL(e);return t.searchParams.set(`quic`,`1`),t.toString()},Gc=e=>{let t=e.get(`X-Delivery-Type`),n=e.get(`X-Reused`);return{type:t===null?`http1`:t??void 0,reused:n===null?void 0:{1:!0,0:!1}[n]??void 0}};import{abortable as Kc,assertNever as qc,ErrorCategory as Jc,flattenObject as Yc,fromEvent as Xc,getWindow as Zc,merge as Qc,now as $c,Subject as el,Subscription as tl,suppressAbort as nl,ValueSubject as rl}from"@vkontakte/videoplayer-shared";var il=e=>{let t=new URL(e);return t.searchParams.set(`enable-subtitles`,`yes`),t.toString()};import{ErrorCategory as al}from"@vkontakte/videoplayer-shared";var ol=new Set([2,3,4,5,6,9,19]),sl=new Set([1,8,18,21]),cl=new Set([10,11,12,13,14,15,16]),ll=({txtCode:e,error$:t,recoverableError$:n,httpCode:r})=>{let i=parseInt(e);if(isNaN(i))return;let a={...ul(i),httpCode:r,UVBackendErrorCode:e};if(ol.has(i)){t.next({...a,category:al.NETWORK,origin:`segment_fetcher`});return}if(sl.has(i)){n.next({...a,category:al.FATAL,origin:`segment_fetcher`,canBeRecoverable:!0});return}if(cl.has(i)){t.next({...a,category:al.FATAL,origin:`segment_fetcher`});return}},ul=e=>{switch(e){case 1:return{id:`VideoDataLinkExpiredError`,message:`Video data links have expired`};case 5:return{id:`VideoServerError`,message:`Server error`};case 8:return{id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`};case 10:return{id:`UserAgentChange`,message:`User agent changed`};case 11:return{id:`forbiddenReferer`,message:`Forbidden referer`};case 12:case 13:case 14:case 15:case 16:return{id:`OKerror`,message:`Error #${e}`};case 18:return{id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`};case 21:return{id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`};default:return dl(e)}};function dl(e){return{id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${e})`}}import{devNull as fl,getWindow as pl}from"@vkontakte/videoplayer-shared";var ml=`vk_player_cached_fetches`,hl=[`fromCache`,`expires`,`sig`],gl=300*1e3,_l=`x-cache-expires`,vl=async e=>{let t=bl(e),n=await pl().caches.open(ml);return{get:async()=>{let e=await n.match(t);return e&&!xl(e)?(fl.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_hit`]}),e):(e&&(await n.delete(t),fl.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_missed`,`expired`]})),null)},set:async r=>{await n.put(t,Sl(r,e))}}};function yl(){return typeof caches<`u`}function bl(e){try{let t=new URL(e);return t.hostname=`cache.local`,hl.forEach(e=>t.searchParams.delete(e)),t.toString()}catch{return e}}function xl(e){let t=e.headers.get(_l);if(!t)return!0;let n=Number(t);return isNaN(n)||n<=Date.now()}function Sl(e,t){let n=e.clone();return new Response(n.body,{status:n.status,statusText:n.statusText,headers:new Headers({...Array.from(n.headers.entries()),[_l]:Cl(t).toString()})})}function Cl(e){try{let t=new URL(e).searchParams.get(`expires`);if(t&&!isNaN(Number(t)))return Number(t)}catch{return 0}return Date.now()+gl}class wl{throughputEstimator;requestQuic;tracer;manifestRequested=new el;manifestReceived=new el;firstBytesRequested=new el;firstBytesReceived=new el;lastConnectionType$=new rl(void 0);lastConnectionReused$=new rl(void 0);lastRequestFirstBytes$=new rl(void 0);lastConnectionMetrics$=new rl(void 0);lastDownloadMetrics$=new rl(void 0);recoverableError$=new el;error$=new el;abortAllController=new Hc;subscription=new tl;compatibilityMode;useEnableSubtitlesParam;useUrlCacheMechanism;measureNonSegmentRequests;startupPhase=!0;performanceObserver=null;pendingConnectionMetrics=new Map;handleExtendedNetworkErrorsSet=!1;constructor({throughputEstimator:e,requestQuic:t,tracer:n,compatibilityMode:r=!1,useEnableSubtitlesParam:i=!1,handleExtendedNetworkErrorsSet:a=!1,useUrlCacheMechanism:o=!1,measureNonSegmentRequests:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=n.createComponentTracer(`Fetcher`),this.useEnableSubtitlesParam=i,this.handleExtendedNetworkErrorsSet=a,this.measureNonSegmentRequests=s,Zc().PerformanceObserver&&this.setupPerformanceObserver(),this.useUrlCacheMechanism=o}onHeadersReceived(e){let{type:t,reused:n}=Gc(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(n)}setupPerformanceObserver(){this.performanceObserver=new(Zc()).PerformanceObserver(e=>{e.getEntriesByType(`resource`).forEach(e=>{this.processResourceTiming(e)})}),this.performanceObserver.observe({entryTypes:[`resource`]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let n=this.extractConnectionMetrics(e);n&&this.lastConnectionMetrics$.next(n)}estimateNetworkType(){if(!(`connection`in Zc().navigator))return`unknown`;let e=Zc().navigator.connection;return e.effectiveType?{"slow-2g":`2g`,"2g":`2g`,"3g":`3g`,"4g":`lte`}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?`2g`:e.downlink<5?`3g`:e.downlink<50?`lte`:`wifi`:e.rtt?e.rtt>500?`2g`:e.rtt>250?`3g`:e.rtt>50?`lte`:`wifi`:`unknown`}extractConnectionMetrics(e){let t=0,n=0,r=0,i=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(i=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,n=e.secureConnectionStart-e.connectStart):n=i),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,n),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,i),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,n]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),i=r.origin+r.pathname,a=new URL(n.url);if(i===a.origin+a.pathname&&e.startTime>=n.startTime-10&&e.startTime<=n.startTime+1e3)return t}}catch{this.recoverableError$.next({id:`VideoDataFetchError`,message:`Video data fetch error with getting download metrics`,category:Jc.WTF})}return null}trackRequestStart(e,t){let n=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(n,{url:e,startTime:t})}fetchManifest=Kc(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer(`FetchManifest`),n=e;this.requestQuic&&(n=Wc(n)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(n=il(n)),this.trackRequestStart(n,performance.now());let r=$c();this.manifestRequested.next();let i=yield this.doFetch(n,{signal:this.abortAllController.signal}).catch(nl);if(i){let a=$c();t.log(`success`,Yc({url:n,message:`Request successfully executed`})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(i.headers);let o=i.headers.get(`content-length`),s=0;o&&(s=parseInt(o,10));let c=await i.text();if((!o||isNaN(s)||s<=0)&&(s=new TextEncoder().encode(c).length),s>0){let t=a-r,n=s/(t/1e3)*8/1024,i={bytes:s,speed:n,url:e};this.lastDownloadMetrics$.next(i)}if(this.measureNonSegmentRequests&&this.startupPhase&&(this.throughputEstimator?.addRawRtt(a-r),o&&s>0)){let e=$c();this.throughputEstimator?.addRawSpeed(s,e-r)}return c}else return t.error(`error`,Yc({url:n,message:`No data in request manifest`})),t.end(),null}.bind(this));fetch=Kc(this.abortAllController.signal,async function*(e,{rangeMethod:t=+!this.compatibilityMode,range:n,onProgress:r,priority:i=`auto`,signal:a,measureThroughput:o=!0,isLowLatency:s=!1,bufferOptimisation:c=!1,urlCacheMechanismEnabled:l}={}){let u=e,d=new Headers,f=this.tracer.createComponentTracer(`Fetch`);if(n)switch(t){case 0:d.append(`Range`,`bytes=${n.from}-${n.to}`);break;case 1:{let e=new URL(u,Zc().location.href);e.searchParams.append(`bytes`,`${n.from}-${n.to}`),u=e.toString();break}default:qc(t)}this.requestQuic&&(u=Wc(u));let p=this.abortAllController.signal,m;if(a){let e=new Hc;if(m=Qc(Xc(this.abortAllController.signal,`abort`),Xc(a,`abort`)).subscribe(()=>{try{e.abort()}catch(e){nl(e)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{e.abort()}catch(e){nl(e)}p=e.signal}let h=0,g=$c();f.log(`startRequest`,Yc({url:u,priority:i,rangeMethod:t,range:n,isLowLatency:s,requestStartedAt:g})),this.trackRequestStart(u,performance.now()),this.firstBytesRequested.next();let _=yield this.doFetch(u,{priority:i,headers:d,signal:p},{urlCacheMechanismEnabled:l}).catch(nl),v=$c();if(!_)return f.error(`error`,{message:`No response in request`}),f.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-g),!_.ok||!_.body){m?.unsubscribe();let e=`Fetch error ${_.status}: ${_.statusText}`;return f.error(`error`,{message:e}),f.end(),Promise.reject(Error(`Fetch error ${_.status}: ${_.statusText}`))}if(this.onHeadersReceived(_.headers),!r&&!o){let e=yield _.arrayBuffer(),t=$c();if(this.measureNonSegmentRequests&&this.startupPhase){let e=_.headers.get(`content-length`),n=e?parseInt(e,10):NaN;Number.isFinite(n)&&n>0&&this.throughputEstimator?.addRawSpeed(n,t-g)}let n={requestStartedAt:g,requestEndedAt:t,duration:t-g};return f.log(`endRequest`,Yc(n)),f.end(),m?.unsubscribe(),e}let y=_.body;if(o){this.startupPhase=!1;let e;[y,e]=_.body.tee(),this.throughputEstimator?.trackStream(e,s)}let b=y.getReader(),x,S=parseInt(_.headers.get(`content-length`)??``,10);Number.isFinite(S)&&(x=S),!x&&n&&(x=n.to-n.from+1);let C=x?new Uint8Array(x):new Uint8Array,w=!1,T=e=>{m?.unsubscribe(),w=!0,nl(e)},E=Kc(p,async function*({done:e,value:t}){if(h===0&&(this.lastRequestFirstBytes$.next($c()-g),this.firstBytesReceived.next()),p.aborted){m?.unsubscribe();return}if(!e&&t){if(c&&x)C.set(t,h),h+=t.byteLength;else{let e=new Uint8Array(C.length+t.length);e.set(C),e.set(t,C.length),C=e,h+=t.byteLength}r?.(new DataView(C.buffer),h),yield b?.read().then(E,T)}}.bind(this));yield b?.read().then(E,T),m?.unsubscribe();let ee=$c(),te={failed:w,requestStartedAt:g,requestEndedAt:ee,duration:ee-g};if(w)return f.error(`endRequest`,Yc(te)),f.end(),null;if(h>0){let t=ee-g,n=h/(t/1e3)*8/1024,r={bytes:h,speed:n,url:e};this.lastDownloadMetrics$.next(r)}return f.log(`endRequest`,Yc(te)),f.end(),C.buffer}.bind(this));async fetchRepresentation(e,t,n,r=`auto`){let{type:i}=e;switch(i){case`byteRange`:return this.fetchByteRangeRepresentation(e,t,n,r)??null;case`template`:return this.fetchTemplateRepresentation(e,n,r)??null;default:qc(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&=(this.performanceObserver.disconnect(),null),this.pendingConnectionMetrics.clear(),this.tracer.end()}fetchByteRangeRepresentation=Kc(this.abortAllController.signal,async function*(e,t,n,r){if(e.type!==`byteRange`)return null;let{from:i,to:a}=e.initRange,o=i,s=a,c=!1,l,u;e.indexRange&&(l=e.indexRange.from,u=e.indexRange.to,c=a+1===l,c&&(o=Math.min(l,i),s=Math.max(u,a))),o=Math.min(o,0);let d=yield this.fetch(e.url,{range:{from:o,to:s},priority:r,signal:n,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!d)return null;let f=new DataView(d,i-o,a-o+1);if(!t.validateData(f))throw Error(`Invalid media file`);let p=t.parseInit(f),m=e.indexRange??t.getIndexRange(p);if(!m)throw ReferenceError(`No way to load representation index`);let h;if(c)h=new DataView(d,m.from-o,m.to-m.from+1);else{let t=yield this.fetch(e.url,{range:m,priority:r,signal:n,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!t)return null;h=new DataView(t)}let g=t.parseSegments(h,p,m).map(e=>({...e,networkStatus:`none`,bufferStatus:`none`}));return{initMetadata:p,initDataView:new DataView(d),segments:g}}.bind(this));fetchTemplateRepresentation=Kc(this.abortAllController.signal,async function*(e,t,n){if(e.type!==`template`)return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:n,signal:t,measureThroughput:!1});if(!i)return null;let a=e.segments.map(e=>({...e,networkStatus:`none`,bufferStatus:`none`,size:void 0}));return{initMetadata:null,initDataView:new DataView(i),segments:a}}.bind(this));async doFetch(e,t,n={}){let r;if(this.useUrlCacheMechanism&&n.urlCacheMechanismEnabled&&yl()){r=await vl(e);let t=await r.get();if(t)return t}let i=await Uc(e,t);if(i.ok)return await r?.set(i),i;let a=await i.text();if(this.handleExtendedNetworkErrorsSet){ll({txtCode:a,httpCode:i.status,error$:this.error$,recoverableError$:this.recoverableError$});return}let o=parseInt(a);if(!isNaN(o))switch(o){case 1:this.recoverableError$.next({id:`VideoDataLinkExpiredError`,message:`Video data links have expired`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;default:this.error$.next({id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${o})`,category:Jc.FATAL,httpCode:i.status,UVBackendErrorCode:a})}}}var Tl=e=>{let[t,...n]=e.split(`.`);if(!t)return!1;switch(t){case`av01`:{let[e,t,r]=n;return!!(r&&parseInt(r,10)>8)}case`vp09`:{let[e,t,r]=n;return!!(e&&parseInt(e,10)>=2&&r&&parseInt(r,10)>8)}case`avc1`:{let e=n[0];if(!e||e.length!==6)return!1;let[t,r]=e.toUpperCase(),i=t+r;return[`6E`,`7A`,`F4`].includes(i)}}return!1};import{isNonNullable as El,isNullable as Dl}from"@vkontakte/videoplayer-shared";var Ol=e=>{if(e.includes(`/`)){let t=e.split(`/`);return parseInt(t[0])/parseInt(t[1])}else return parseFloat(e)},kl=e=>{try{let t=Al(),{groups:n}=e.match(t)??{};if(n){let e={};if(n.extensions){let t=n.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(t||[]).forEach(t=>{e[t[0]]=t.slice(2)})}let t=n.variants?.split(/-/).filter(e=>e!==``),r={extlang:n.extlang,langtag:n.langtag,language:n.language,privateuse:n.privateuse||n.privateuse2,region:n.region,script:n.script,extensions:e,variants:t};return Object.keys(r).forEach(e=>{let t=r[e];(t===void 0||t===``)&&delete r[e]}),r}return null}catch{return null}};function Al(){let e=`x(?:-[a-z0-9]{1,8})+`,t=`^(?:(?<langtag>${`
|
|
248
248
|
(?<language>(?:[a-z]{2,3}(?:-(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2})))?|[a-z]{4}|[a-z]{5,8}))
|
|
249
249
|
(-(?<script>[a-z]{4}))?
|
|
250
250
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
251
251
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
252
252
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
253
253
|
(?:-(?<privateuse>(?:${e})))?
|
|
254
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,``);return new RegExp(t,`i`)}var jl=e=>{if(!e?.startsWith(`P`))return;let t=(e,t)=>{let n=e?parseFloat(e.replace(`,`,`.`)):NaN;return(isNaN(n)?0:n)*t},n=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(e),r=n?.[1]===`-`?-1:1,i={days:t(n?.[5],r),hours:t(n?.[6],r),minutes:t(n?.[7],r),seconds:t(n?.[8],r)};return i.days*24*60*60*1e3+i.hours*60*60*1e3+i.minutes*60*1e3+i.seconds*1e3},Ml=(e,t)=>{let n=e;n=n.replaceAll(`$$`,`$`);let r={RepresentationID:t.representationId,Number:t.segmentNumber,Bandwidth:t.bandwidth,Time:t.segmentTime};for(let[e,t]of Object.entries(r)){let r=RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,`g`);n=n.replaceAll(r,(e,n)=>Dl(t)?e:Dl(n)?t:t.padStart(parseInt(n,10),`0`))}return n},Nl=(e,t)=>{let n=new DOMParser().parseFromString(e,`application/xml`),r={video:[],audio:[],text:[]},i=n.children[0],a=Array.from(i.querySelectorAll(`MPD > BaseURL`).values()).map(e=>e.textContent?.trim()??``),o=a.at(0)??``,s=i.getAttribute(`type`)===`dynamic`,c=i.getAttribute(`availabilityStartTime`),l=i.getAttribute(`publishTime`),u=i.getElementsByTagName(`vk:Attrs`)[0],d=u?.getElementsByTagName(`vk:XLatestSegmentPublishTime`)[0].textContent,f=u?.getElementsByTagName(`vk:XStreamIsLive`)[0].textContent,p=u?.getElementsByTagName(`vk:XStreamIsUnpublished`)[0].textContent,m=u?.getElementsByTagName(`vk:XPlaybackDuration`)[0].textContent,h;s&&(h={availabilityStartTime:c?new Date(c).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:f===`yes`,streamIsUnpublished:p===`yes`});let g,_=i.getAttribute(`mediaPresentationDuration`),v=[...i.getElementsByTagName(`Period`)],y=v.reduce((e,t)=>({...e,[t.id]:t.children}),{}),b=v.reduce((e,t)=>({...e,[t.id]:t.getAttribute(`duration`)}),{});_?g=jl(_):Object.values(b).filter(e=>e).length&&!s?g=Object.values(b).reduce((e,t)=>e+(jl(t)??0),0):m&&(g=parseInt(m,10));let x=0,S=i.getAttribute(`profiles`)?.split(`,`)??[];for(let e of v.map(e=>e.id))for(let n of y[e]){let e=n.getAttribute(`id`)??`id`+(x++).toString(10),i=n.getAttribute(`mimeType`)??``,a=n.getAttribute(`codecs`)??``,s=n.getAttribute(`contentType`)??i?.split(`/`)[0],c=n.getAttribute(`profiles`)?.split(`,`)??[],l=kl(n.getAttribute(`lang`)??``)??{},u=n.querySelector(`Label`)?.textContent?.trim()??void 0,d=n.querySelectorAll(`Representation`),f=n.querySelector(`SegmentTemplate`),p=n.querySelector(`Role`)?.getAttribute(`value`)??void 0,m=n.querySelector(`AudioChannelConfiguration`)?.getAttribute(`value`),h=El(m)?parseInt(m,10):void 0,_=s,v={id:e,language:l.language,isDefault:p===`main`,label:u,codecs:a,hdr:_===`video`&&Tl(a),mime:i,channels:h,representations:[]};for(let e of d){let r=e.getAttribute(`lang`)??void 0,d=u??n.getAttribute(`label`)??e.getAttribute(`label`)??void 0,p=e.querySelector(`BaseURL`)?.textContent?.trim()??``,m=new URL(p||o,t).toString(),h=e.getAttribute(`mimeType`)??i,y=e.getAttribute(`codecs`)??a??``,b;if(s===`text`){let t=e.getAttribute(`id`)||``,n=l.privateuse?.includes(`x-auto`)||t.includes(`_auto`),r=e.querySelector(`SegmentTemplate`);if(r){let i={representationId:e.getAttribute(`id`)??void 0,bandwidth:e.getAttribute(`bandwidth`)??void 0},a=parseInt(e.getAttribute(`bandwidth`)??``,10)/1e3,o=parseInt(r.getAttribute(`startNumber`)??``,10)??1,s=parseInt(r.getAttribute(`timescale`)??``,10),c=r.querySelectorAll(`SegmentTimeline S`)??[],l=r.getAttribute(`media`);if(!l)continue;let u=[],d=0,f=``,p=0,h=o,_=0;for(let e of c){let t=parseInt(e.getAttribute(`d`)??``,10),n=parseInt(e.getAttribute(`r`)??``,10)||0,r=parseInt(e.getAttribute(`t`)??``,10);_=Number.isFinite(r)?r:_;let a=t/s*1e3,o=_/s*1e3;for(let e=0;e<n+1;e++){let n=Ml(l,{...i,segmentNumber:h.toString(10),segmentTime:(_+e*t).toString(10)}),r=(o??0)+e*a,s=r+a;h++,u.push({time:{from:r,to:s},url:n})}_+=(n+1)*t,d+=(n+1)*a}p=_/s*1e3,f=Ml(l,{...i,segmentNumber:h.toString(10),segmentTime:_.toString(10)}),b={id:t,kind:`text`,segmentReference:{type:`template`,baseUrl:m,segmentTemplateUrl:l,initUrl:``,totalSegmentsDurationMs:d,segments:u,nextSegmentBeyondManifest:{time:{from:p,to:1/0},url:f},timescale:s},profiles:[],duration:g,bitrate:a,mime:``,codecs:``,width:0,height:0,isAuto:n}}else b={id:t,isAuto:n,kind:`text`,url:m}}else{let t=e.getAttribute(`contentType`)??h?.split(`/`)[0]??s,r=n.getAttribute(`profiles`)?.split(`,`)??[],i=parseInt(e.getAttribute(`width`)??``,10),a=parseInt(e.getAttribute(`height`)??``,10),o=parseInt(e.getAttribute(`bandwidth`)??``,10)/1e3,l=e.getAttribute(`frameRate`)??``,u=e.getAttribute(`quality`)??void 0,d=l?Ol(l):void 0,p=`${e.getAttribute(`id`)??`id`+(x++).toString(10)}@${t===`video`?`${a}p`:t===`audio`?`${o}Kbps`:y}`,v=[...S,...c,...r],C,w=e.querySelector(`SegmentBase`),T=e.querySelector(`SegmentTemplate`)??f;if(w){let[t,n]=(e.querySelector(`SegmentBase Initialization`)?.getAttribute(`range`)??``).split(`-`).map(e=>parseInt(e,10)),r={from:t,to:n},i=e.querySelector(`SegmentBase`)?.getAttribute(`indexRange`),[a,o]=i?i.split(`-`).map(e=>parseInt(e,10)):[];C={type:`byteRange`,url:m,initRange:r,indexRange:i?{from:a,to:o}:void 0}}else if(T){let t={representationId:e.getAttribute(`id`)??void 0,bandwidth:e.getAttribute(`bandwidth`)??void 0},n=parseInt(T.getAttribute(`timescale`)??``,10),r=T.getAttribute(`initialization`)??``,i=T.getAttribute(`media`),a=parseInt(T.getAttribute(`startNumber`)??``,10)??1,o=Ml(r,t);if(!i)throw ReferenceError(`No media attribute in SegmentTemplate`);let s=T.querySelectorAll(`SegmentTimeline S`)??[],c=[],l=0,u=``,d=0;if(s.length){let e=a,r=0;for(let a of s){let o=parseInt(a.getAttribute(`d`)??``,10),s=parseInt(a.getAttribute(`r`)??``,10)||0,u=parseInt(a.getAttribute(`t`)??``,10);r=Number.isFinite(u)?u:r;let d=o/n*1e3,f=r/n*1e3;for(let n=0;n<s+1;n++){let a=Ml(i,{...t,segmentNumber:e.toString(10),segmentTime:(r+n*o).toString(10)}),s=(f??0)+n*d,l=s+d;e++,c.push({time:{from:s,to:l},url:a})}r+=(s+1)*o,l+=(s+1)*d}d=r/n*1e3,u=Ml(i,{...t,segmentNumber:e.toString(10),segmentTime:r.toString(10)})}else if(El(g)){let e=parseInt(T.getAttribute(`duration`)??``,10)/n*1e3,r=Math.ceil(g/e),a=0;for(let n=1;n<r;n++){let r=Ml(i,{...t,segmentNumber:n.toString(10),segmentTime:a.toString(10)});c.push({time:{from:a,to:a+e},url:r}),a+=e}d=a,u=Ml(i,{...t,segmentNumber:r.toString(10),segmentTime:a.toString(10)})}C={type:`template`,baseUrl:m,segmentTemplateUrl:i,initUrl:o,totalSegmentsDurationMs:l,segments:c,nextSegmentBeyondManifest:{time:{from:d,to:1/0},url:u},timescale:n}}else throw ReferenceError(`Unknown MPD segment referencing type`);if(!t||!h)continue;let E={video:`video`,audio:`audio`,text:`text`}[t];if(!E)continue;_||=E,b={id:p,kind:E,segmentReference:C,profiles:v,duration:g,bitrate:o,mime:h,codecs:y,width:i,height:a,fps:d,quality:u}}v.language||=r,v.label||=d,v.mime||=h,v.codecs||=y,v.hdr||=_===`video`&&Tl(y),v.representations.push(b)}if(_){let e=r[_].find(e=>e.id===v.id);if(e&&v.representations.every(e=>e.segmentReference.type===`template`))for(let t of e.representations){let e=v.representations.find(e=>e.id===t.id);if(!e)continue;let n=e.segmentReference,r=t.segmentReference;r.segments.push(...n.segments),r.nextSegmentBeyondManifest=n.nextSegmentBeyondManifest}else r[_].push(v)}}return{duration:g,streams:r,baseUrls:a,live:h}};import{AbortControllerPolyfilled as Pl}from"@vkontakte/videoplayer-shared";import{requestIdleCallbackPolyfilled as Fl}from"@vkontakte/videoplayer-shared";import{abortable as Il,assertNonNullable as Ll,ErrorCategory as Rl,flattenObject as z,fromEvent as zl,getExponentialDelay as Bl,getWindow as Vl,isAbortError as Hl,isHigher as Ul,isNonNullable as B,isNullable as V,once as Wl,Subject as Gl,Subscription as Kl,ValueSubject as ql}from"@vkontakte/videoplayer-shared";var Jl=e=>e.valid;class H{source;boxParser;type;size;content;valid;children;cursor=0;get id(){return this.type}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];let n=this.readUint32();this.type=this.readString(4),n===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,i;n===0||n===1?(this.size=void 0,this.valid=!1,i=void 0):n>e.byteLength?(this.size=n,this.valid=!1,i=Math.min(n-this.cursor,e.byteLength-this.cursor)):(this.size=n,this.valid=!0,i=n-this.cursor),this.content=new DataView(e.buffer,r,i)}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t=`ascii`){let n=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,n}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}}class Yl extends H{}import{assertNever as Xl}from"@vkontakte/videoplayer-shared";class Zl extends H{userData;constructor(e,t){if(super(e,t),!this.valid)return;let n=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(n,r)}parseData(e,t){switch(e){case`ondemandlivejson`:{let e=new TextDecoder(`ascii`).decode(t),n=JSON.parse(e);return{received:n[`t-in`],prepared:n[`t-out`]}}default:Xl(e)}}}class Ql extends H{majorBrand;minorVersion;compatibleBrands;constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let n=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let e=0;e<n.byteLength;e+=4){let e=this.readString(4);this.compatibleBrands.push(e)}}}class $l extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class eu extends H{version;flags;constructor(e,t){if(super(e,t),!this.valid)return;let n=this.readUint32();this.version=n>>>24,this.flags=n&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}}class tu extends eu{creationTime;modificationTime;timescale;duration;rate;volume;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())}}class nu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class ru extends H{data;constructor(e,t){super(e,t),this.data=this.content}}class iu extends eu{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;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 e=0;e<this.referenceCount;e++){let e=this.readUint32(),t=e>>>31,n=e<<1>>>1,r=this.readUint32();e=this.readUint32();let i=e>>>28,a=e<<3>>>3;this.segments.push({referenceType:t,referencedSize:n,subsegmentDuration:r,SAPType:i,SAPDeltaTime:a})}}}}class au extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class ou extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class su extends eu{stereoMode;constructor(e,t){if(super(e,t),this.valid){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}}}class cu extends eu{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}}class lu extends eu{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}}class uu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class du extends eu{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;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()}}class fu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class pu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class mu extends eu{sequenceNumber;constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}}class hu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class gu extends eu{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;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())}}class _u extends eu{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class vu extends eu{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let e=0;e<this.sampleCount;e++)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())}}class yu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class bu extends eu{entryCount;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)))}}class xu extends H{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 Su={ftyp:Ql,moov:$l,mvhd:tu,moof:nu,mdat:ru,sidx:iu,trak:au,mdia:uu,mfhd:mu,tkhd:du,traf:hu,tfhd:gu,tfdt:_u,trun:vu,minf:fu,sv3d:ou,st3d:su,prhd:cu,proj:pu,equi:lu,uuid:Zl,stbl:yu,stsd:bu,avc1:xu,unknown:Yl};class Cu{options;constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],n=this.options.offset;for(;n<e.byteLength;){let r=new TextDecoder(`ascii`).decode(new DataView(e.buffer,e.byteOffset+n+4,4)),i;try{i=this.createBox(r,new DataView(e.buffer,e.byteOffset+n,e.byteLength-n))}catch(e){if(!(e instanceof RangeError))throw e}if(!i||!Jl(i))break;t.push(i),n+=i.size}return t}createBox(e,t){let n=Su[e];return n?new n(t,new Cu):new Yl(t,new Cu)}}class wu{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(e=>{Jl(e)&&(this.index[e.type]??=[],this.index[e.type].push(e),e.children.length>0&&this.indexBoxLevel(e.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}var Tu=new TextDecoder(`ascii`),Eu={validateData:e=>Tu.decode(new DataView(e.buffer,e.byteOffset+4,4))===`ftyp`,parseInit:e=>{let t={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},n=new wu(new Cu().parse(e));if(n.find(`sv3d`)){t.is3dVideo=!0;let e=n.find(`st3d`);e&&(t.stereoMode=e.stereoMode);let r=n.find(`prhd`);r&&(t.projectionData.pose.yaw=r.poseYawDegrees,t.projectionData.pose.pitch=r.posePitchDegrees,t.projectionData.pose.roll=r.poseRollDegrees);let i=n.find(`equi`);i&&(t.projectionData.bounds.top=i.projectionBoundsTop,t.projectionData.bounds.right=i.projectionBoundsRight,t.projectionData.bounds.bottom=i.projectionBoundsBottom,t.projectionData.bounds.left=i.projectionBoundsLeft)}return t},getIndexRange:()=>{},parseSegments:e=>{let t=new iu(e,new Cu),n=t.earliestPresentationTime/t.timescale*1e3,r=e.byteOffset+e.byteLength+t.firstOffset;return t.segments.map(e=>{if(e.referenceType!==0)throw Error(`Unsupported multilevel sidx`);let i=r,a=r+e.referencedSize-1,o=e.subsegmentDuration/t.timescale*1e3,s={status:`none`,time:{from:n,to:n+o},byte:{from:i,to:a},size:a-i+1};return n+=o,r+=e.referencedSize,s})},parseFeedableSegmentChunk:(e,t)=>{let n=new wu(new Cu().parse(e)),r=n.findAll(`moof`),i=t?n.findAll(`uuid`):n.findAll(`mdat`);if(!(i.length&&r.length))return null;let a=r[0],o=i[i.length-1],s=a.source.byteOffset,c=o.source.byteOffset-a.source.byteOffset+o.size;return new DataView(e.buffer,s,c)},getChunkEndTime:(e,t)=>{let n=new wu(new Cu().parse(e)).findAll(`traf`),r=n[n.length-1].children.find(e=>e.type===`tfhd`),i=n[n.length-1].children.find(e=>e.type===`tfdt`),a=n[n.length-1].children.find(e=>e.type===`trun`),o=0;return o=a.sampleDuration.length?a.sampleDuration.reduce((e,t)=>e+t,0):r.defaultSampleDuration*a.sampleCount,(Number(i.baseMediaDecodeTime)+o)/t*1e3},getServerLatencyTimestamps:e=>{let t=new wu(new Cu().parse(e)),n={},r=t.findAll(`uuid`).at(-1);return r?{serverDataReceivedTimestamp:r.userData.received,serverDataPreparedTime:r.userData.received}:n},getTimescaleFromIndex:e=>new wu(new Cu().parse(e)).find(`sidx`)?.timescale};import{assertNonNullable as Du,isNonNullable as Ou,isNullable as ku}from"@vkontakte/videoplayer-shared";import{assertNever as Au}from"@vkontakte/videoplayer-shared";var ju={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`}},Mu=e=>{let t=e.getUint8(0),n=0;t&128?n=1:t&64?n=2:t&32?n=3:t&16&&(n=4);let r=Nu(e,n),i=r in ju,a=i?ju[r].type:`binary`,o=e.getUint8(n),s=0;o&128?s=1:o&64?s=2:o&32?s=3:o&16?s=4:o&8?s=5:o&4?s=6:o&2?s=7:o&1&&(s=8);let c=new DataView(e.buffer,e.byteOffset+n+1,s-1),l=o&255>>s,u=Nu(c),d=l*2**((s-1)*8)+u,f=n+s,p;return p=f+d>e.byteLength?new DataView(e.buffer,e.byteOffset+f):new DataView(e.buffer,e.byteOffset+f,d),{tag:i?r:`0x`+r.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},Nu=(e,t=e.byteLength)=>{switch(t){case 1:return e.getUint8(0);case 2:return e.getUint16(0);case 3:return e.getUint8(0)*2**16+e.getUint16(1);case 4:return e.getUint32(0);case 5:return e.getUint8(0)*2**32+e.getUint32(1);case 6:return e.getUint16(0)*2**32+e.getUint32(2);case 7:{let t=e.getUint8(0)*2**48+e.getUint16(1)*2**32+e.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw ReferenceError(`Int64 is not supported`)}return 0},Pu=(e,t)=>{switch(t){case`int`:return e.getInt8(0);case`uint`:return Nu(e);case`float`:return e.byteLength===4?e.getFloat32(0):e.getFloat64(0);case`string`:return new TextDecoder(`ascii`).decode(e);case`utf8`:return new TextDecoder(`utf-8`).decode(e);case`date`:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case`master`:return e;case`binary`:return e;default:Au(t)}},Fu=(e,t)=>{let n=0;for(;n<e.byteLength;){let r=Mu(new DataView(e.buffer,e.byteOffset+n));if(!t(r))return;r.type===`master`&&Fu(r.value,t),n=r.value.byteOffset-e.byteOffset+r.valueSize}},Iu=e=>{if(e.getUint32(0)!==440786851)return!1;let t,n,r;return Fu(Mu(e).value,({tag:e,type:i,value:a})=>(e===17143?t=Pu(a,i):e===17026?n=Pu(a,i):e===17029&&(r=Pu(a,i)),!0)),(t===void 0||t<=1)&&n!==void 0&&n===`webm`&&(r===void 0||r<=2)},Lu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ru=[231,22612,22743,167,171,163,160,175],zu={validateData:Iu,parseInit:e=>{let t,n,r,i,a=!1,o=!1,s=!1,c,l,u=!1;return Fu(e,({tag:e,type:d,value:f,valueSize:p})=>(e===21419?l=Nu(Pu(f,d)):e!==21420&&(l=void 0),e===408125543?(t=f.byteOffset,n=f.byteOffset+p):e===357149030?a=!0:e===290298740?o=!0:e===2807729?r=Pu(f,d):e===17545?i=Pu(f,d):e===21420&&l===475249515?c=Pu(f,d):e===374648427?Fu(f,({tag:e,type:t,value:n})=>e===30321?(u=Pu(n,t)===1,!1):!0):a&&o&&Lu.includes(e)&&(s=!0),!s)),Du(t,`Failed to parse webm Segment start`),Du(n,`Failed to parse webm Segment end`),Du(i,`Failed to parse webm Segment duration`),r??=1e6,{segmentStart:Math.round(t/1e9*r*1e3),segmentEnd:Math.round(n/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:u,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},getIndexRange:e=>{if(ku(e.cuesSeekPosition))return;let t=e.segmentStart+e.cuesSeekPosition;return{from:t,to:t+1048576}},parseSegments:(e,t)=>{let n=!1,r=!1,i=e=>Ou(e.time)&&Ou(e.position),a=[],o;return Fu(e,({tag:e,type:t,value:s})=>{switch(e){case 475249515:n=!0;break;case 187:o&&i(o)&&a.push(o),o={};break;case 179:o&&(o.time=Pu(s,t));break;case 183:break;case 241:o&&(o.position=Pu(s,t));break;default:n&&Lu.includes(e)&&(r=!0)}return!(n&&r)}),o&&i(o)&&a.push(o),a.map((e,n)=>{let{time:r,position:i}=e,o=a[n+1],s=t.segmentStart+i,c=o?t.segmentStart+o.position-1:t.segmentEnd-1;return{status:`none`,time:{from:r,to:o?o.time:t.segmentDuration},byte:{from:s,to:c},size:c-s+1}})},parseFeedableSegmentChunk:e=>{let t=0,n=!1;try{Fu(e,r=>r.tag===524531317?r.tagSize<=e.byteLength?(t=r.tagSize,!1):(t+=r.tagHeaderSize,!0):Ru.includes(r.tag)?(t+r.tagSize<=e.byteLength&&(t+=r.tagSize,n||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return t>0&&t<=e.byteLength&&n?new DataView(e.buffer,e.byteOffset,t):null}},Bu=e=>{let t=/^(.+)\/([^;]+)(?:;.*)?$/.exec(e);if(t){let[,e,n]=t;if(e===`audio`||e===`video`)switch(n){case`webm`:return zu;case`mp4`:return Eu}}throw ReferenceError(`Unsupported mime type ${e}`)};import{videoSizeToQuality as Vu}from"@vkontakte/videoplayer-shared";var Hu=({id:e,width:t,height:n,bitrate:r,fps:i,quality:a,streamId:o,tvDisabled:s})=>{let c=(a?er(a):void 0)??Vu({width:t,height:n});return c&&{id:e,quality:c,bitrate:r,size:{width:t,height:n},fps:i,streamId:o,tvDisabled:s}},Uu=({id:e,bitrate:t})=>({id:e,bitrate:t}),Wu=({language:e,label:t},{id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Gu=({language:e,label:t,id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Ku=({id:e,language:t,label:n,codecs:r,isDefault:i,channels:a})=>({id:e,language:t,label:n,codec:r.split(`.`).at(0),isDefault:i,channels:a}),qu=({id:e,language:t,label:n,hdr:r,codecs:i})=>({id:e,language:t,hdr:r,label:n,codec:i.split(`.`).at(0)}),Ju=e=>`url`in e,Yu=e=>e.type===`template`;class Xu{error$=new Gl;playingRepresentation$=new ql(void 0);playingRepresentationInit$=new ql(void 0);currentSegmentLength$=new ql(0);onLastSegment$=new ql(!1);fullyBuffered$=new ql(!1);kind;nativeBufferManager;fetcher;tracer;tuning;representations;playingRepresentationId;downloadingRepresentationId;switchingRepresentationId;initData=new Map;initDataPromises=new Map;idleCallbacks=new Map;parsedInitData=new Map;forwardBufferRepresentations=new Map;segments=new Map;containerParser;bufferPlaybackQueue=[];downloadingBufferItems=[];preloadOnly=!1;forwardBufferTarget;failedDownloads=0;lastDataObtainedTimestampMs=0;loadByteRangeSegmentsTimeoutId=0;currentVirtualBufferSize=0;baseUrls=[];baseUrlsIndex=0;maintainPlaybackBufferMutex=!1;maintainNativeBufferMutex=!1;bufferClearingMutex=!1;abortNativeBufferMutex=!1;switchMutex=!1;seekMutex=!1;destroyAbortController=new Pl;switchAbortController=new Pl;downloadAbortController=new Pl;subscription=new Kl;getCurrentPosition;getCurrentStallDuration;constructor(e,t,n,{fetcher:r,tracer:i,tuning:a,getCurrentPosition:o,getCurrentStallDuration:s,manifest:c}){this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tracer=i.createComponentTracer(`${this.kind} virtualBuffer`),this.tuning=a,this.getCurrentPosition=o,this.getCurrentStallDuration=s,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=c?.baseUrls??[],this.representations=new Map(n.map(e=>[e.id,e]))}startWith=Il(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ll(t,`Cannot find representation ${e}`);let n=this.tracer.createComponentTracer(`startWith`);n.log(`start representation`,z({id:e})),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Bu(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),n.log(`started loadInitIfNeeded`),yield this.loadInitIfNeeded(t,`high`),n.log(`ended loadInitIfNeeded`);let r=this.initData.get(t.id),i=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Ll(r,`No init buffer for starting representation`),Ll(i,`No segments for starting representation`),n.log(`started native buffer init segment append`),yield this.nativeBufferManager.addInitSegment(r),n.log(`ended native buffer init segment append`),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a),n.end()}.bind(this));async switchTo(e,t=`default`){if(e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;let n=this.tracer.createComponentTracer(`switchTo ${t} ${this.getCurrentPosition()}`);return n.log(`abort previous switchTo`),this.switchAbortController.abort(),this.switchMutex=!1,n.log(`switchMutex released`),this.switchAbortController=new Pl,this.getSwitchWithAbort(n)(e,t)}getSwitchWithAbort(e){return Il(this.switchAbortController.signal,async function*(t,n){if(!V(this.downloadingRepresentationId)){this.switchMutex=!0,e.log(`switchMutex captured`);try{e.log(`start`,z({newRepresentationId:t,playingRepresentationId:this.playingRepresentationId,downloadingRepresentationId:this.downloadingRepresentationId,mode:n})),this.switchingRepresentationId=t;let r=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(t);Ll(i,`No such representation ${t}`),Ll(r,`No such representation ${this.downloadingRepresentationId}`),e.log(`abortDownload`),yield this.abortDownload(),e.log(`start loadInitIfNeeded`),yield this.loadInitIfNeeded(i,`high`),e.log(`ended loadInitIfNeeded`);let a=this.initData.get(i.id),o=this.segments.get(i.id);if(V(a)||V(o))return;let s=e=>e.segment.bufferStatus!==`fed`,c=e=>{let t=this.representations.get(e.representationId);return Ll(t,`No itemRepresentation for previous track before switch`),e.segment.networkStatus!==`downloaded`||this.forceSwitchCondition(t,i)},l=e=>{switch(n){case`lazy`:return s(e)&&c(e);case`force`:return!0;default:return s(e)}};e.log(`bufferPlaybackQueue before`,z(this.bufferPlaybackQueue)),this.bufferPlaybackQueue.filter(l).forEach(e=>e.segment.bufferStatus=`none`),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(e=>!l(e)),e.log(`bufferPlaybackQueue after`,z(this.bufferPlaybackQueue)),this.downloadingRepresentationId=t,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(e.log(`switchTo with maintain`),yield this.maintain()):(e.log(`switchTo with seek`),yield this.prepareSeek(),yield this.seek(this.getCurrentPosition()))}finally{this.switchMutex=!1,e.log(`switchMutex released`),e.end()}}}.bind(this))}async prepareSeek(){let e=this.tracer.createComponentTracer(`prepareSeek`);this.seekMutex=!0,e.log(`seekMutex captured`);try{e.log(`started abort`),await this.abort(),e.log(`started clearBuffer`),await this.clearBuffer(),e.log(`ended clearBuffer`)}catch{e.error(`seekMutex released`),this.seekMutex=!1}e.end()}async seek(e){let t=this.tracer.createComponentTracer(`seek ${e}`);this.seekMutex=!1,t.log(`seekMutex released`),t.log(`maintain started`),await this.maintain(e),t.log(`maintain ended`),t.end()}async maintain(e=this.getCurrentPosition()){V(e)||(await this.verifyBufferPlaybackQueue(e),await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardBufferRepresentations(e=this.getCurrentPosition()){if(this.forwardBufferRepresentations.clear(),B(e))for(let[t,n]of this.segments.entries())this.forwardBufferRepresentations.set(t,n.filter(t=>t.time.from>=e&&t.time.to<=e+this.forwardBufferTarget));return this.forwardBufferRepresentations}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(e=>e.segment.networkStatus===`downloaded`),n=t[t.length-1],r=B(e)&&B(n)?n.segment.time.to-e:0;return Math.max(r,0)}getPlaybackBufferState(){return this.bufferPlaybackQueue.length?{from:this.bufferPlaybackQueue[0].segment.time.from,to:this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to}:null}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??``;return(this.segments.get(t)?.find(t=>t.time.from<=e&&t.time.to>=e))?.time.from}getRepresentationInitialTime(){return V(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}getMutexInfo(){let e=``;return this.seekMutex&&(e+=`seek `),this.abortNativeBufferMutex&&(e+=`abort `),this.maintainNativeBufferMutex&&(e+=`maintainNative `),this.maintainPlaybackBufferMutex&&(e+=`maintainPlayback `),this.bufferClearingMutex&&(e+=`bufferClear `),this.switchMutex&&(e+=`switch `),e}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}getActiveSegmentProgress(){let e;for(let t of this.downloadingBufferItems)t.segment.networkStatus!==`downloading`||V(t.startedAtMs)||(!e||t.segment.time.from<e.segment.time.from)&&(e=t);if(!(!e||V(e.startedAtMs)))return{startedAtMs:e.startedAtMs,loadedBytes:e.segment.loadedBytes??0,totalBytes:B(e.segment.size)&&Number.isFinite(e.segment.size)?e.segment.size:void 0,segmentDurationMs:e.segment.time.to-e.segment.time.from}}getMpdSegmentDuration(){for(let e of this.segments.values()){let t=e[0];if(t&&t.time.to>t.time.from)return t.time.to-t.time.from}}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=Vl();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.cancelIdleCallback)for(let t of this.idleCallbacks.values())e.cancelIdleCallback(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId),this.tracer.log(`destroy`),this.tracer.end()}async verifyBufferPlaybackQueue(e){let t=this.getPlaybackBufferState();if(!this.tuning.dash.useBufferQueueVerification||!this.bufferPlaybackQueue.length||V(t)||this.withinInterval(e,t))return;let n=this.tracer.createComponentTracer(`verifyBufferPlaybackQueue `+e);this.tuning.dash.useVirtualBufferImplicitSeek?(n.log(`prepare seek `),await this.prepareSeek(),n.log(`seek `+e),await this.seek(e)):(n.log(`reset bufferPlaybackQueue`),this.bufferPlaybackQueue=[]),n.end()}forceSwitchCondition(e,t){let n=!0;if(this.kind===`video`){let r=Hu(e),i=Hu(t);n=B(r)&&B(i)&&Ul(i.quality,r.quality)}else if(this.kind===`audio`){let r=Uu(e),i=Uu(t);n=B(r?.bitrate)&&B(i?.bitrate)&&i.bitrate>r.bitrate}return n}async clearBuffer(){let e=this.tracer.createComponentTracer(`clearBuffer`);this.bufferClearingMutex=!0,e.log(`bufferClearingMutex captured`);try{e.log(`clearBuffer`,z({queue:this.bufferPlaybackQueue.slice(0,5)})),await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus=`none`),this.bufferPlaybackQueue=[]}finally{this.bufferClearingMutex=!1,e.log(`bufferClearingMutex released`),e.end()}}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new Pl,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus===`downloading`&&(e.segment.networkStatus=`none`,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null,e.startedAtMs=void 0);this.downloadingBufferItems=[]}async abortNativeBuffer(){let e=this.tracer.createComponentTracer(`abortNativeBuffer`);e.log(`abortNativeBufferMutex captured`),this.abortNativeBufferMutex=!0;try{e.log(`abortNativeBuffer`,z({bufferState:this.nativeBufferManager.getBufferState()}));let t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),n=t instanceof ArrayBuffer?t:void 0;return await this.nativeBufferManager.abortBuffer(n)}finally{this.abortNativeBufferMutex=!1,e.log(`abortNativeBufferMutex released`),this.tuning.dash.useAbortResetNativeBufferMutex&&(this.maintainNativeBufferMutex=!1),e.end()}}async loadInits(){for(let[e,t]of this.representations)this.idleCallbacks.set(t.id,Fl(async e=>await this.loadInitIfNeeded(t,`low`,!1)))}async loadInitIfNeeded(e,t=`auto`,n=!1){let r=this.initDataPromises.get(e.id),i;i=this.initData.has(e.id)&&this.segments.has(e.id)?Promise.resolve():B(r)?r:this.loadInit(e,t,n),await i}async loadInit(e,t=`auto`,n=!1){try{let n=this.tuning.dash.useFetchPriorityHints?t:`auto`,r=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,this.downloadAbortController.signal,n);this.initDataPromises.set(e.id,r);let{initMetadata:i,initDataView:a,segments:o}=await r??{};if(this.initDataPromises.delete(e.id),V(a)||V(o))return;i&&this.parsedInitData.set(e.id,i);let s=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e.id,s),this.segments.set(e.id,o),this.failedDownloads=0}catch(e){n&&!Hl(e)&&this.error$.next({id:`LoadInits`,category:Rl.WTF,message:`loadInit threw`,thrown:e})}}async maintainNativeBuffer(){let e=this.getCurrentPosition(),t=this.segments.get(this.downloadingRepresentationId??``),n=t?.[t?.length-1];if(V(e)||V(n)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.seekMutex||this.preloadOnly)return;let r;this.maintainNativeBufferMutex=!0;try{let t=this.bufferPlaybackQueue.find(t=>this.withinInterval(e,t.segment.time)),i=this.bufferPlaybackQueue.find(e=>e.segment.bufferStatus!==`fed`),a=this.initData.get(i?.representationId??``),o=this.bufferPlaybackQueue[0],s=this.destroyAbortController.signal,c=(this.getCurrentStallDuration()??0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&(c&&=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,n.time.to-e),u=c?this.getForwardPlaybackBufferDuration()>=l:!0;B(a)&&B(i)&&B(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus===`fed`)&&(r??=this.tracer.createComponentTracer(`native init ${e}`),r.log(`abortNativeBuffer`),await this.abortNativeBuffer(),r.log(`start addInitSegment`),await this.nativeBufferManager.addInitSegment(a,s),r.log(`end addInitSegment`),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId),r.log(`playingRepresentationId`,z({id:i.representationId}))),B(i)&&this.withinAppendInterval(e,i.segment.time)&&u&&(r??=this.tracer.createComponentTracer(`native append ${e}`),i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus===`none`?(r.log(`started appendSegmentFully`),await this.appendSegmentFully(i,s),r.log(`ended appendSegmentFully`)):(r.log(`started appendSegmentPartially`),await this.appendSegmentPartially(i,s),r.log(`ended appendSegmentPartially`))),B(o)&&B(t)&&this.withinRemoveInterval(e,o.segment.time)&&o.segment.time.to<t.segment.time.from+1&&(r??=this.tracer.createComponentTracer(`native remove ${e}`),r.log(`started removeSegment`),await this.removeSegment(o,s),r.log(`ended removeSegment`)),r?.log(`currentPosition`,z({currentPosition:e})),r?.log(`currentPlayingItem`,z(t)),r?.log(`nextPlayingItem`,z(i)),r?.log(`nextRemoveItem`,z(o)),r?.log(`queue`,z(this.bufferPlaybackQueue.slice(0,5))),r?.log(`buffer`,z(this.nativeBufferManager.getBufferState()??{})),this.pruneVirtualBuffer(e)}finally{this.maintainNativeBufferMutex=!1,r?.log(`maintainNativeBufferMutex released`),r?.end()}}async maintainPlaybackBuffer(e){Ll(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),n=this.representations.get(this.downloadingRepresentationId);if(V(t)||V(n)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.seekMutex)return;let r;this.maintainPlaybackBufferMutex=!0;try{let i=t.find(t=>e>=t.time.from&&e<t.time.to);B(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next(i?.time.to-i.time.from),this.downloadingBufferItems.length?r=this.tracer.createComponentTracer(`playbackMaintain ${e}`):this.downloadingBufferItems=this.selectDownloadingItems(e,t),r?.log(`maintainPlaybackBufferMutex captured`),r?.log(`currentSegment`,z(i)),r?.log(`downloadingBufferItems`,z(this.downloadingBufferItems)),r?.log(`processCachedItems`),await this.processCachedItems();let a=this.selectItemsToLoad();r?.log(`itemsToLoad`,z(a)),await this.loadItems(a,n),r?.log(`items downloaded`,z(a))}finally{this.maintainPlaybackBufferMutex=!1,r?.log(`maintainPlaybackBufferMutex released`),r?.end()}}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??``);if(V(t)||t.length===0)return;let n=t[t?.length-1];V(n)||(this.fullyBuffered$.next(n.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-n.time.from>0))}selectDownloadingItems(e,t){Ll(this.downloadingRepresentationId);let n=this.getPlaybackBufferState(),r,i;if(B(n)&&this.withinInterval(e,n)){i=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e);let n=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1];r=t.findIndex(e=>e.time.from>n.segment.time.from+this.tuning.dash.bufferTolerance)}else i=this.forwardBufferTarget,r=t.findIndex(t=>this.withinInterval(e,t.time));r=r===-1?0:r;let a=[];for(;r<t.length&&i>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:e,to:n}=t[r].time;i-=n-e,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:n},r=this.tuning.dash.bufferTolerance,i=0){return B(e)?e+r>=t&&e-i<n:!1}withinAppendInterval(e,{from:t,to:n}){let{minNativeBufferSize:r,removeTimeShiftFromSegment:i}=this.tuning.dash;return this.withinInterval(e,{from:t,to:n},r,i)}withinRemoveInterval(e,{to:t}){let{removeTimeShiftFromSegment:n}=this.tuning.dash;return B(e)?e-n>t:!1}getExponentialDownloadDelay(){return Il(this.downloadAbortController.signal,async function*(){let e=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let n=Vl();this.loadByteRangeSegmentsTimeoutId=n.setTimeout(t,e),this.subscription.add(zl(n,`online`).pipe(Wl()).subscribe(()=>{t(),n.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this))}async waitExponentialDownloadDelay(){await this.getExponentialDownloadDelay()()}async appendSegmentFully(e,t){V(e.segment.data)||(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(V(e.segment.data)||V(e.segment.loadedBytes)||V(e.segment.feedingBytes)||V(e.segment.fedBytes)||V(e.segment.size))return;let n=e.segment.data,r=new DataView(n.buffer,n.byteOffset+e.segment.feedingBytes,n.byteLength-e.segment.feedingBytes),i=e.segment.loadedBytes===e.segment.size?r:this.parseFeedableSegmentChunk(r);i?.byteLength&&(e.segment.bufferStatus=`partially_fed`,e.segment.feedingBytes+=i.byteLength,await this.nativeBufferManager.append(i,t)&&(e.segment.fedBytes+=i.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:n,to:r}=e.segment.time,i=(r-n)/4;await this.nativeBufferManager.remove(0,r-i,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus=`none`,this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(t=>t===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(t=>t!==e||t.segment.networkStatus!==`downloaded`),(this.preloadOnly||B(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(t=>t===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:n,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let i,a=this.currentVirtualBufferSize-t+n;for(let t of this.segments.values())for(let n of t)B(n.size)&&a>0&&n.time.to<=e-r&&n.bufferStatus===`none`&&n.networkStatus===`downloaded`&&(i??=this.tracer.createComponentTracer(`prune before ${e}`),i.log(`bytesToPrune`,{bytesToPrune:a}),i.log(`prune segment`,z(n)),n.data=null,n.networkStatus=`none`,this.currentVirtualBufferSize-=n.size,a-=n.size);for(let t of this.segments.values())for(let n of[...t].reverse())B(n.size)&&a>0&&n.time.from>=e+r&&n.bufferStatus===`none`&&n.networkStatus===`downloaded`&&!this.bufferPlaybackQueue.find(e=>e.segment===n)&&!this.downloadingBufferItems.find(e=>e.segment===n)&&(i??=this.tracer.createComponentTracer(`prune after ${e}`),i.log(`bytesToPrune`,{bytesToPrune:a}),i.log(`prune segment`,z(n)),n.data=null,n.networkStatus=`none`,this.currentVirtualBufferSize-=n.size,a-=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 Zu,getWindow as Qu,isNonNullable as $u,isNullable as ed,now as td,isAbortError as nd}from"@vkontakte/videoplayer-shared";class rd extends Xu{constructor(e,t,n,r){super(e,t,n,r)}async loadItems(e,t,n=`auto`){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:i,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),r.aborted)return;let o=Qu().performance.now();for(let t of e)t.startedAtMs=o;try{await this.fetcher.fetch(i,{...a,priority:n,urlCacheMechanismEnabled:!0}),this.lastDataObtainedTimestampMs=td(),this.failedDownloads=0}catch(e){this.abortDownloadingItems(),nd(e)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,n=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,i=this.preloadOnly?this.forwardBufferTarget:0,a=0;for(;a<this.downloadingBufferItems.length&&this.downloadingBufferItems[a].segment.networkStatus===`none`&&(e<=r||t<=i);){let r=this.downloadingBufferItems[a],i=r.segment;i.networkStatus=`downloading`,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,n.push(r),e+=i.byte.to+1-i.byte.from,t+=i.time.to+1-i.time.from,a++}return n}prepareFetchParams(e,t){if(Ya(t.segmentReference))throw Error(`Representation is not byte range type`);let{signal:n}=this.downloadAbortController,r=t.segmentReference.url,i={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:i,onProgress:async(r,a)=>{if(!n.aborted)try{this.lastDataObtainedTimestampMs=td(),await this.onSomeDataLoaded({downloadingItems:e,dataView:r,loaded:a,signal:n,globalFrom:i?i.from:0,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:Zu.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}},signal:n,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:n,globalFrom:r,loaded:i,signal:a}){let o=this.representations.get(n);if(!(!this.downloadingBufferItems.length||ed(o)||ed(r)||a.aborted))for(let n of e){let{segment:e}=n,a=e.byte.from-r,o=e.byte.to-r,s=a<i,c=o<=i;!s||ed(e.size)||(e.networkStatus===`downloading`&&e.bufferStatus===`none`&&c?(e.data=new DataView(t.buffer,t.byteOffset+a,e.size),this.currentVirtualBufferSize+=e.size,this.onItemFullyDownloaded(n),e.loadedBytes=Math.min(e.size,i-a),await this.onDownloadItem(n)):$u(e.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&e.networkStatus===`downloading`&&(e.loadedBytes=Math.min(e.size,i-a),c&&(this.currentVirtualBufferSize+=e.size,this.onItemFullyDownloaded(n)),e.loadedBytes>e.feedingBytes&&(e.data=new DataView(t.buffer,t.byteOffset+a,e.loadedBytes),await this.onDownloadItem(n))))}}updateRepresentationBaseUrl(e,t){if(Ya(e.segmentReference))throw Error(`Representation is not byte range type`);e.segmentReference.url=t}}import{ErrorCategory as id,getWindow as ad,isAbortError as od,isNullable as sd,now as cd}from"@vkontakte/videoplayer-shared";class ld extends Xu{constructor(e,t,n,r){super(e,t,n,r)}async loadItems(e,t,n=`auto`){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:i,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),r.aborted)return;let o=ad().performance.now();for(let t of e)t.startedAtMs=o;try{let t=await this.fetcher.fetch(i,{...a,priority:n});if(this.lastDataObtainedTimestampMs=cd(),sd(t))return;let r=e[0],o=new DataView(t);r.segment.size=o.byteLength,r.segment.loadedBytes=o.byteLength,r.segment.data=o,this.onItemFullyDownloaded(r),await this.onDownloadItem(r),this.failedDownloads=0}catch(e){this.abortDownloadingItems(),od(e)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let n=t.segment;n.networkStatus=`downloading`,n.size=1/0,n.loadedBytes=0,n.feedingBytes=0,n.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let n=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:n,onProgress:async(n,i)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=cd(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:i,signal:r,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:id.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ya(t.segmentReference))throw Error(`Representation is not template type`);return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:n,loaded:r,signal:i}){let a=e[0],{segment:o}=a,s=this.representations.get(n);!this.downloadingBufferItems.length||sd(s)||sd(o.feedingBytes)||o.networkStatus!==`downloading`||i.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(a)))}updateRepresentationBaseUrl(e,t){if(!Ya(e.segmentReference))throw Error(`Representation is not template type`);e.segmentReference.baseUrl=t}}import{assertNonNullable as ud,ErrorCategory as dd,isNullable as fd,ValueSubject as pd}from"@vkontakte/videoplayer-shared";class md extends ld{currentLiveSegmentServerLatency$=new pd(0);currentLowLatencySegmentLength$=new pd(0);liveInitialAdditionalOffset=0;isSeekingLive=!1;isActiveLowLatency;constructor(e,t,n,r){super(e,t,n,r),this.isActiveLowLatency=r.isActiveLowLatency}updateManifest(e){if(!e||[...this.segments.values()].every(e=>!e.length))return;let t=e.streams[this.kind].flatMap(e=>e.representations);for(let e of t){if(fd(e)||!Ya(e.segmentReference))return;let t=e.segmentReference.segments.map(e=>({...e,networkStatus:`none`,bufferStatus:`none`,size:void 0})),n=this.segments.get(e.id)??[],r=n.at(-1)?.time.to??0,i=t?.findIndex(e=>r>=e.time.from+100&&r<=e.time.to+100);if(i===-1){let t=this.getActualLiveStartingSegments(e.segmentReference);this.segments.set(e.id,t)}else{let r=t.slice(i+1);this.segments.set(e.id,[...n,...r])}this.representations.set(e.id,e)}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ud(e);let t=this.segments.get(e);if(t?.length){let n={representationId:e,segmentIndex:t.length-1,segment:t[t.length-1]};this.updateLowLatencyLive(n)}}getLiveSegmentsToLoadState(e){let t=(e?.streams[this.kind])?.flatMap(e=>e.representations).find(e=>e.id===this.downloadingRepresentationId);if(fd(t))return;let n=this.segments.get(t.id);if(n?.length)return{from:n[0].time.from,to:n[n.length-1].time.to}}getRepresentationInitialTime(){if(fd(this.playingRepresentationId))return 0;let e=this.representations.get(this.playingRepresentationId)?.segmentReference;return fd(e)||!Ya(e)?0:this.getActualLiveStartingSegments(e)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(e,t){return{...super.prepareFetchParams(e,t),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:e,...t}){await super.onSomeDataLoaded({downloadingItems:e,...t}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(e[0])}onItemFullyDownloaded(e){if(super.onItemFullyDownloaded(e),fd(e.segment.data)||!this.isActiveLowLatency())return;let t=e.segment.data,{serverDataReceivedTimestamp:n,serverDataPreparedTime:r}=this.containerParser.getServerLatencyTimestamps(t);n&&r&&this.currentLiveSegmentServerLatency$.next(r-n),this.updateLowLatencyItemTime(e),this.updateLowLatencyLive(e)}updateLowLatencyItemTime(e){let t=e.segment.data,n=this.representations.get(e.representationId)?.segmentReference;if(fd(e.segment.data)||fd(n)||!Ya(n))return;let r=this.containerParser;if(e.segment.isCurrentLowLatency){let{timescale:i}=n;e.segment.time.to=r.getChunkEndTime(t,i)}}updateLowLatencyLive(e){let t=0;for(let n of this.representations.values()){let r=n.segmentReference;if(!Ya(r))return;let i=this.segments.get(n.id)??[],a=i.find(t=>Math.floor(t.time.from)===Math.floor(e.segment.time.from));if(a?.isCurrentLowLatency&&(a.time.to=e.segment.time.to,t=a.time.to-a.time.from,a.isCurrentLowLatency=!1),!i.find(t=>Math.floor(t.time.from)===Math.floor(e.segment.time.to))&&this.isActiveLowLatency()){let t=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Ml(r.segmentTemplateUrl,{segmentTime:t});i.push({networkStatus:`none`,bufferStatus:`none`,time:{from:e.segment.time.to,to:e.segment.time.to+this.tuning.dash.bufferTolerance},url:n,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(t)}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!0)}getFetchUrl(e,t){let n=super.getFetchUrl(e,t);return this.isActiveLowLatency()&&n.searchParams.set(`low-latency`,`yes`),n}async loadInit(e,t=`auto`,n=!1){try{let n=this.tuning.dash.useFetchPriorityHints?t:`auto`,r=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,this.downloadAbortController.signal,n);this.initDataPromises.set(e.id,r);let{initMetadata:i,initDataView:a,segments:o}=await r??{};if(this.initDataPromises.delete(e.id),fd(a)||fd(o))return;i&&this.parsedInitData.set(e.id,i);let s=this.getActualLiveStartingSegments(e.segmentReference);this.segments.has(e.id)||this.segments.set(e.id,s);let c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e.id,c),this.failedDownloads=0}catch(e){n&&this.error$.next({id:`LoadInits`,category:dd.WTF,message:`loadInit threw`,thrown:e})}}getActualLiveStartingSegments(e){let t=e.segments,n=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],i=0,a=t.length-1;do r.unshift(t[a]),i+=t[a].time.to-t[a].time.from,a--;while(i<n&&a>=0);return this.liveInitialAdditionalOffset=i-n,this.isActiveLowLatency()?[r[0]]:r}}class hd{static getBufferManager(e,t,n,r){return r.manifest?.live?new md(e,t,n,r):Ya(n[0].segmentReference)?new ld(e,t,n,r):new rd(e,t,n,r)}}import{ErrorCategory as gd,fromEvent as _d,isNullable as vd,Subject as yd,Subscription as bd,ValueSubject as xd}from"@vkontakte/videoplayer-shared";import{assertNever as Sd,ErrorCategory as Cd,Subject as wd}from"@vkontakte/videoplayer-shared";var Td=18,Ed=!1;try{Ed=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=Td}catch(e){console.error(e)}class Dd{bufferFull$=new wd;error$=new wd;buffer;queue=[];currentTask=null;destroyed=!1;abortRequested=!1;isAbortFixEnabled=!1;constructor(e,t=!1){this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener(`updateend`,this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(n=>{let r={operation:`append`,data:e,signal:t,callback:n};this.queue.push(r),this.pull()})}async remove(e,t,n){return n&&n.aborted?!1:new Promise(r=>{let i={operation:`remove`,from:e,to:t,signal:n,callback:r};this.queue.unshift(i),this.pull()})}async abort(e){return new Promise(t=>{let n,r=e=>{this.abortRequested=!1,t(e)};n=Ed&&e?{operation:`safariAbort`,init:e,callback:r}:{operation:`abort`,callback:r},this.isAbortFixEnabled&&this.currentTask&&(this.currentTask.callback(!1),this.currentTask=null);for(let{callback:e}of this.queue)e(!1);this.abortRequested=!0,n&&(this.queue=[n]),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}}completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:`BufferTaskQueueUnknown`,category:Cd.VIDEO_PIPELINE,message:`Buffer appending or removal failed`,thrown:e})}};pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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(e){e instanceof DOMException&&e.name===`QuotaExceededError`&&t===`append`?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&e.name===`InvalidStateError`||this.error$.next({id:`BufferTaskQueue:${t}`,category:Cd.VIDEO_PIPELINE,message:`Buffer operation failed`,thrown:e}),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:Sd(t)}}}var Od=Dd,kd=(e,t)=>{let n=0;for(let r=0;r<e.length;r++){let i=e.start(r)*1e3,a=e.end(r)*1e3;i<=t&&t<=a&&(n=a)}return Math.max(n-t,0)};class Ad{error$=new yd;updateEnd$=new xd(void 0);mediaSource;sourceBuffer;sourceBufferTaskQueue;subscription=new bd;constructor(e){this.mediaSource=e}init(e,t,n=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Od(this.sourceBuffer,n),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(e=>this.error$.next(e))),this.subscription.add(_d(this.sourceBuffer,`error`).subscribe(()=>this.error$.next({id:`SourceBuffer`,category:gd.VIDEO_PIPELINE,message:`SourceBuffer Error event fired`}))),this.subscription.add(_d(this.sourceBuffer,`updateend`).subscribe(this.updateEnd$))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,n){return this.sourceBufferTaskQueue.remove(e,t,n)}async clear(e){let t=this.getBufferState();if(vd(t))return Promise.resolve(!1);let n=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)n&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return n}warmUpMediaSource(){!vd(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode=`segments`)}getBufferState(){if(vd(this.sourceBuffer)||!I(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 vd(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||vd(e)?0:kd(this.sourceBuffer.buffered,e)}async abortBuffer(e){return vd(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}}import{ErrorCategory as jd,isHigher as Md,isLower as Nd,isLowerOrEqual as Pd,VideoQuality as Fd}from"@vkontakte/videoplayer-shared";var Id=e=>{switch(e){case`DASH_SEP`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_ONDEMAND`:case`DASH_STREAMS`:return!0;default:return!1}},Ld=Object.values(Fd).filter(e=>e!==Fd.INVARIANT).sort((e,t)=>Md(e,t)?-1:1),Rd=e=>{if(!e||e===Fd.INVARIANT)return null;let t=Ld.find(t=>Nd(t,e))??Fd.Q_1080P;return Pd(t,Fd.Q_1080P)?Fd.Q_1080P:t},zd=(e,t,n)=>e.category===jd.VIDEO_PIPELINE&&e.id.endsWith(`MediaError#${MediaError.MEDIA_ERR_DECODE}`)&&Id(t)?Rd(n):null,Bd=({height:e},t)=>{let n=`${e}p`;try{return Md(n,t)}catch{return!1}},Vd=(e,t)=>{e.video.forEach(e=>{e.representations.forEach(e=>{e.tvDisabled=e.tvDisabled||Bd(e,t)})})},Hd=(e,t,n)=>{let r=[];for(let i of e.representations){let e=`${i.mime}; codecs="${i.codecs}"`,a=t.canPlayType?.(e),o=!1;switch(n){case`probably`:o=a===`probably`;break;case`maybe`:o=!!a;break}o&&r.push(i)}return r.length?{...e,representations:r}:null},Ud=(e,t,n)=>{let r=[];for(let i of e){let e=Hd(i,t,n);e&&r.push(e)}return r},Wd=(e,t)=>{if(!e.length||!t.length)return[];let n=[],r=0,i=0;for(;r<e.length&&i<t.length;){let a=Math.max(e[r].from,t[i].from),o=Math.min(e[r].to,t[i].to);a<o&&n.push({from:a,to:o}),e[r].to<t[i].to?r++:i++}return n},Gd=[`timeupdate`,`progress`,`play`,`seeked`,`stalled`,`waiting`],Kd=[`timeupdate`,`progress`,`loadeddata`,`playing`,`seeked`];class qd{element=null;manifestUrlString=``;source=null;manifest=null;tuning;tracer;stallTracer=null;forceVideoCodec;stallTimeInWaitingExitAttemptMade=0;videoBufferManager;audioBufferManager;bufferManagers=[];videoNativeBufferManager;audioNativeBufferManager;nativeBufferManagers=[];throughputEstimator;subscription=new Bc;subscriptionRemovable=new Vc;representationSubscription=new Bc;fetcher;forceEnded$=new zc;stallWatchdogSubscription;destroyController=new xc;state$=new Dt(`none`);currentVideoRepresentation$=new R(void 0);currentVideoRepresentationInit$=new R(void 0);currentAudioRepresentation$=new R(void 0);currentVideoSegmentLength$=new R(0);currentAudioSegmentLength$=new R(0);error$=new zc;manifestRequested=new zc;manifestReceived=new zc;firstBytesRequested=new zc;firstBytesReceived=new zc;lastConnectionType$=new R(void 0);lastConnectionReused$=new R(void 0);lastRequestFirstBytes$=new R(void 0);lastConnectionMetrics$=new R(void 0);lastDownloadMetrics$=new R(void 0);currentLiveTextRepresentation$=new R(null);timeoutSourceOpenId;isLive$=new R(!1);isActiveLive$=new R(!1);isLowLatency$=new R(!1);liveDuration$=new R(0);liveSeekableDuration$=new R(0);liveAvailabilityStartTime$=new R(0);liveStreamStatus$=new R(void 0);currentBuffer$=new R({from:0,to:0});bufferLength$=new R(0);nativeBufferLength$=new R(0);liveLatency$=new R(void 0);liveLoadBufferLength$=new R(0);livePositionFromPlayer$=new R(0);currentStallDuration$=new R(0);videoLastDataObtainedTimestamp$=new R(0);fetcherRecoverableError$=new zc;fetcherError$=new zc;updateDurationError$=new zc;isOnDemand=!1;dashMaxTvVideoQuality;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(`DashProviderVirtualPlayer`),this.forceVideoCodec=e.forceVideoCodec,this.isOnDemand=e.isOnDemand||!1,this.dashMaxTvVideoQuality=e.dashMaxTvVideoQuality,this.fetcher=new wl({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam,measureNonSegmentRequests:e.tuning.throughputEstimator.measureNonSegmentRequests,handleExtendedNetworkErrorsSet:e.tuning.handleExtendedNetworkErrorsSet,useUrlCacheMechanism:e.tuning.useUrlCacheMechanism}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}initRepresentations=wc(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initRepresentationsStart`,kc({initialVideo:e,initialAudio:t,sourceHls:n})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(`representations_ready`);let r={fetcher:this.fetcher,tracer:this.tracer,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,n),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceInitDuration(),this.tuning.audioOnly?Tc(this.audioBufferManager):Tc(this.videoBufferManager);let i=[];e&&i.push(this.videoBufferManager?.startWith(e)??Promise.resolve()),t&&i.push(this.audioBufferManager?.startWith(t)??Promise.resolve()),yield Promise.all(i),this.state$.setState(`representations_ready`),this.tracer.log(`initRepresentationsEnd`)}.bind(this));async initManifest(e,t,n){this.tracer.log(`initManifest`),this.state$.startTransitionTo(`manifest_ready`),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,n),this.manifest=await this.updateManifest(),!this.tuning.audioOnly&&!this.manifest?.streams.video.length||this.tuning.audioOnly&&!this.manifest?.streams.audio.length?this.error$.next({id:`NoRepresentations`,category:Ec.PARSER,message:`No playable video representations`}):this.state$.setState(`manifest_ready`)}initBuffer(){let e=this.tracer.createComponentTracer(`initBuffer`);Tc(this.element),this.state$.setState(`running`),this.subscription.add(Lc(...Gd.map(e=>Ac(this.element,e)),Ac(Mc(),`online`),Nc(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),e=>this.error$.next({id:`DashVKPlayer`,category:Ec.WTF,message:`Internal logic error`,thrown:e}))),e.log(`tick maintain subscription initialized`);let t=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Lc(...t.map(e=>Ac(e,`updateend`))).subscribe(e=>this.reinitDecoderIfNeeded())),e.log(`reinit decoder subscription initialized`),this.subscription.add(Ac(this.element,`waiting`).subscribe(e=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription),this.stallTracer?.end(),this.stallTracer=null);let t=(this.element?.currentTime??0)*1e3;this.stallTracer=this.tracer.createComponentTracer(`stall `+t),this.stallWatchdogSubscription=Nc(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),e=>this.error$.next({id:`StallWatchdogCallback ${e instanceof Error?e.message:``}`,category:Ec.NETWORK,message:`Can't restore DASH after stall.`,thrown:e})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),e.log(`stall subscription initialized`),e.end()}async switchRepresentation(e,t,n){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,n)}async seek(e,t=!1){let n=this.tracer.createComponentTracer(`seek `+e);Tc(this.element);let r;r=t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(this.videoBufferManager?.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(r),n.log(`prepare seek `,{requestedPosition:e,forcePrecise:t}),await Promise.all([this.videoBufferManager?.prepareSeek(),this.audioBufferManager?.prepareSeek()]),this.element.currentTime=r/1e3,n.log(`set current time to `,{currentTime:r/1e3}),n.log(`seek to `,{position:r}),await Promise.all([this.videoBufferManager?.seek(r),this.audioBufferManager?.seek(r)]),await this.reinitDecoderIfNeeded(),n.end()}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Pc(this.element)&&Pc(this.source)&&Pc(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(e=>e.warmUpMediaSource())}getForwardBufferRepresentations(e){return e===`video`?this.videoBufferManager?.getForwardBufferRepresentations():this.audioBufferManager?.getForwardBufferRepresentations()}getActiveVideoSegmentProgress(){return this.videoBufferManager?.getActiveSegmentProgress()}getMpdVideoSegmentDuration(){return this.videoBufferManager?.getMpdSegmentDuration()}get isStreamEnded(){return this.source?.readyState===`ended`}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e,t){this.videoBufferManager?.setTarget(e),this.audioBufferManager?.setTarget(t)}getVideoForwardBufferDuration(){return this.videoBufferManager?.getForwardPlaybackBufferDuration()??0}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&&Mc().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Pc(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}updateSourceDurationFromSegments(){if(!this.source||this.source.readyState!==`open`||this.isLive$.getValue()||!this.tuning.useDurationFromSegments)return;let e=e=>{this.updateDurationError$.next({id:`updateDuration`,category:Ec.VIDEO_PIPELINE,message:"Duration can`t be updated",thrown:e})};try{if(!this.isAnyBufferUpdating()){this.source.duration=this.calculateDurationFromBuffersSegments()/1e3;return}}catch(t){e(t);return}let t=new Bc;t.add(Lc(...this.nativeBufferManagers.map(e=>e.updateEnd$)).subscribe(()=>{if(!this.isAnyBufferUpdating()){t.unsubscribe();try{this.source&&(this.source.duration=this.calculateDurationFromBuffersSegments()/1e3)}catch(t){e(t)}}}))}calculateDurationFromBuffersSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}isAnyBufferUpdating(){return!this.source||this.source.readyState!==`open`?!1:Array.from(this.source.sourceBuffers).some(e=>e.updating)}get isStreamNotOpen(){return this.source?.readyState!==`open`}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[],n=this.audioNativeBufferManager?.getBufferState()??[],r;if(r=Fc(this.videoBufferManager)?n:Fc(this.audioBufferManager)?t:Wd(t,n),Fc(this.element)||!r.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&r.some(({from:e,to:t})=>i>=e&&i<=t&&t-e>this.tuning.dash.minNativeBufferSize/2)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Tc(this.element),Tc(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;if(this.currentStallDuration$.next(t),this.stallTracer?.log(`timeInWaiting`,{timeInWaiting:t}),await this.reinitDecoderIfNeeded(t%1e3==0),this.isStallExceeded(t)){let e=this.audioBufferManager?.getMutexInfo()??``,n=this.videoBufferManager?.getMutexInfo()??``;if(this.stallTracer?.log(`stallExceeded`,kc({timeInWaiting:t,audioMutexState:e,videoMutexState:n,mutexStallExitPolicy:this.tuning.dash.mutexStallExitPolicy,seekStallExitPolicy:this.tuning.dash.seekStallExitPolicy})),this.tuning.dash.mutexStallExitPolicy&&(e||n)){let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}else if(this.tuning.dash.seekStallExitPolicy)if(this.stallTimeInWaitingExitAttemptMade>0&&t-this.stallTimeInWaitingExitAttemptMade>this.tuning.dash.restoreBufferBeforeCrashTimeout){let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}else this.stallTimeInWaitingExitAttemptMade===0&&(this.stallTracer?.log(`seek`),await this.seek((this.element.currentTime+1)*1e3),this.stallTimeInWaitingExitAttemptMade=t);else{let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}}await this.restoreAfterDeepStall()}isStallExceeded(e){if(Fc(this.element))return!1;let{crashOnStallTimeout:t,virtualBufferEmptinessTolerance:n}=this.tuning.dash,r=n,i=this.element?this.element.currentTime*1e3:0,a=i-r>0?this.tuning.dash.crashOnStallTWithoutDataTimeout:t,o=Rc(),s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let c=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoNativeBufferManager?.getForwardBufferDuration(i)??0,u=this.audioNativeBufferManager?.getForwardBufferDuration(i)??0,d=Pc(this.videoBufferManager)&&l<r&&o-s>a,f=Pc(this.audioBufferManager)&&u<r&&o-c>a;return(d||f)&&e>a||e>=t}async updateManifest(){this.tracer.log(`updateManifestStart`,{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Fc(e))return null;let t=this.parseManifest(e);if(!t)return null;let n=this.getResultManifest(t);return this.tracer.log(`updateManifestEnd`,kc(n)),n}fetchManifest=wc(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Fc(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:`LoadManifest`,category:Ec.NETWORK,message:`Failed to load manifest`,thrown:e})}}.bind(this));parseManifest(e){try{return Nl(e??``,this.manifestUrlString)}catch(t){let n=Cc(e)??{id:`ManifestParsing`,category:Ec.PARSER,message:`Failed to parse MPD manifest`,thrown:t};this.error$.next(n)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},n=(e,t,n)=>!!(this.element?.canPlayType?.(t)&&Fe()?.isTypeSupported?.(`${t}; codecs="${n}"`)||e===`text`),r,i;for(let a of[`video`,`audio`]){let o=e.streams[a],s=this.tuning.dash.checkRepresentationCanPlayType&&this.element?Ud(o,this.element,this.tuning.dash.checkRepresentationCanPlayType):o.filter(({mime:e,codecs:t})=>n(a,e,t));t[a]=s;let c,l;if(this.tuning.dash.codecsPrioritizeEnabled){if(a===`audio`)i=ca(s.map(({codecs:e})=>e)),c=i[0],c&&(t[a]=s.filter(({codecs:e})=>la(e)===c));else if(a===`video`){r=oa(s,{preferHdr:this.tuning.preferHDR});let e=this.forceVideoCodec;l=(e?r.find(t=>t.name===e.name&&t.hdr===e.hdr):void 0)??r[0],l&&(t[a]=s.filter(e=>la(e.codecs)===l.name&&!!e.hdr===l.hdr))}}else{let e=aa(new Set(s.map(({codecs:e})=>e)));e&&(t[a]=s.filter(({codecs:t})=>t.startsWith(e)))}if(a===`video`){if(!this.tuning.dash.codecsPrioritizeEnabled){let e=this.tuning.preferHDR,n=t.video.some(e=>e.hdr),r=t.video.some(e=>!e.hdr);A.display.isHDR&&e&&n?t.video=t.video.filter(e=>e.hdr):r&&(t.video=t.video.filter(e=>!e.hdr))}let{videoStreamRepresentaionsFilter:e}=this.tuning.dash;if(e.length&&fa(t,e),this.dashMaxTvVideoQuality&&Vd(t,this.dashMaxTvVideoQuality),this.isOnDemand&&this.tuning.dash.filterOnDemandQualityList)for(let e of t.video)e.representations=e.representations.sort((e,t)=>t.height-e.height).filter((e,t)=>t%2==0)}}let a={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(a.codecs={video:r,audio:i}),a}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.stallTimeInWaitingExitAttemptMade=0,this.currentStallDuration$.next(0),this.stallTracer?.end(),this.stallTracer=null}createBuffers(e,t,n,r){Tc(this.manifest),Tc(this.element);let i=e=>{this.representationSubscription.add(Ac(e,`error`).pipe(Dc(e=>!!this.element?.played.length)).subscribe(e=>{this.error$.next({id:`VideoSource`,category:Ec.VIDEO_PIPELINE,message:`Unexpected video source error`,thrown:e})}))};this.source=Re();let a=Mc().document,o=a.createElement(`source`);if(i(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),Ie())if(r){let e=a.createElement(`source`);i(e),e.type=`application/x-mpegurl`,e.src=r.url,this.element.appendChild(e)}else this.element.disableRemotePlayback=!0;if(Pc(t)){let t=this.manifest.streams.video.reduce((e,t)=>[...e,...t.representations],[]);t.length&&(this.videoNativeBufferManager=new Ad(this.source),this.videoBufferManager=hd.getBufferManager(`video`,this.videoNativeBufferManager,t,e),this.bufferManagers.push(this.videoBufferManager),this.nativeBufferManagers.push(this.videoNativeBufferManager))}if(Pc(n)){this.audioNativeBufferManager=new Ad(this.source);let t=this.manifest.streams.audio.reduce((e,t)=>[...e,...t.representations],[]);this.audioBufferManager=hd.getBufferManager(`audio`,this.audioNativeBufferManager,t,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=Mc().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:`OpenOfStream`,category:Ec.VIDEO_PIPELINE,message:`Failed to open MediaSource`,thrown:Error(`Timeout reject when wait sourceopen event`),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener(`sourceopen`,()=>{this.timeoutSourceOpenId&&Mc().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add(Lc(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),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(Lc(...Kd.map(e=>Ac(this.element,e)),Nc(this.tuning.dash.tickMaintainInterval)).pipe(Ic(e=>this.videoBufferManager?.getPlaybackBufferState()),Dc(Pc),Ic(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Lc(...Kd.map(e=>Ac(this.element,e)),Nc(this.tuning.dash.tickMaintainInterval)).pipe(Ic(e=>Math.min(this.videoBufferManager?.getForwardPlaybackBufferDuration()??1/0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??1/0)),Oc()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Dc(e=>e>this.tuning.dash.virtualBufferEmptinessTolerance)).subscribe(()=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=jc(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e(`error`,!0)))}async tick(){if(Fc(this.element)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,t=this.videoNativeBufferManager?.getBufferState()??[],n=this.audioNativeBufferManager?.getBufferState()??[],r=t.find(t=>e>=t.from&&e<=t.to),i=n.find(t=>e>=t.from&&e<=t.to),a=r?r.to-e:0,o=i?i.to-e:1/0;Pc(this.videoBufferManager)?this.nativeBufferLength$.next(Math.min(a,o)):Pc(this.audioBufferManager)&&this.nativeBufferLength$.next(o);let s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s),await Promise.all([this.videoBufferManager?.maintain(),this.audioBufferManager?.maintain()])}}import{assertNonNullable as Jd,combine as Yd,ErrorCategory as Xd,filter as Zd,filterChanged as Qd,fromEvent as $d,isNonNullable as ef,map as tf,merge as nf}from"@vkontakte/videoplayer-shared";class rf extends qd{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceInitDuration(){Jd(this.manifest),Jd(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(e=>e.representations).flatMap(e=>{let t=[];return e.duration&&t.push(e.duration),Ya(e.segmentReference)&&e.segmentReference.totalSegmentsDurationMs&&t.push(e.segmentReference.totalSegmentsDurationMs),t})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(){Jd(this.element);let e=this.element.currentTime*1e3;this.stallTracer?.log(`restore maintain`,{position:e}),await Promise.all([this.videoBufferManager?.maintain(e),this.audioBufferManager?.maintain(e)])}initDisableStallWatchdogSubscription(){Jd(this.element);let e=nf($d(this.element,`ended`),this.forceEnded$),t=this.nativeBufferLength$.pipe(Zd(e=>e>this.tuning.dash.virtualBufferEmptinessTolerance));this.representationSubscription.add(nf(e,t).subscribe(e=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Yd({allBuffersFull:nf(...this.bufferManagers.map(e=>e.fullyBuffered$)).pipe(tf(()=>this.bufferManagers.every(e=>e.fullyBuffered$.getValue()))),someBufferEnded:nf(...this.bufferManagers.map(e=>e.onLastSegment$)).pipe(tf(()=>this.bufferManagers.some(e=>e.onLastSegment$.getValue())))}).pipe(Qd(),tf(({allBuffersFull:e,someBufferEnded:t})=>e&&t),Zd(e=>e));this.representationSubscription.add(nf(this.forceEnded$,e).pipe(Zd(e=>ef(this.source)&&this.source.readyState===`open`&&Array.from(this.source.sourceBuffers).every(e=>!e.updating))).subscribe(()=>{try{this.source?.endOfStream()}catch(e){this.error$.next({id:`EndOfStream`,category:Xd.VIDEO_PIPELINE,message:`Failed to end MediaSource stream`,thrown:e})}}))}}class af extends bc{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:n,genericErrorListener:r}=this.getProviderSubscriptionInfo();n(t.timeUpdate$,e.position$),n(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(wa(),Ca(e=>Ta(e))).subscribe(()=>{this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wa(),Ca(e=>Ta(e))).subscribe(()=>{this.player.updateSourceDurationFromSegments()},r))}getPlayer(){return new rf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec,isOnDemand:this.params.isOnDemand||!1,dashMaxTvVideoQuality:this.params.dashMaxTvVideoQuality})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}import{combine as of,merge as sf,filter as cf,filterChanged as lf,isNullable as uf,map as df,ValueSubject as ff,isNonNullable as pf}from"@vkontakte/videoplayer-shared";import{isNullable as mf,ValueSubject as hf}from"@vkontakte/videoplayer-shared";class gf{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;varianceCoefficient$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new hf(e.initial),this.debounced$=new hf(e.initial),this.varianceCoefficient$=new hf(0);let t=e.label??`value`+Math.random().toString(16).substring(2,6);this.rawSeries$=new gr(`raw_${t}`),this.smoothedSeries$=new gr(`smoothed_${t}`),this.reportedSeries$=new gr(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,n=0;for(let e=0;e<this.pastMeasures.length;e++)this.pastMeasures[e]!==void 0&&(t+=(this.pastMeasures[e]-this.smoothed)**2,n++);this.takenMeasures=n,t/=n;let r=Math.sqrt(t);n>=2&&this.smoothed>0&&this.varianceCoefficient$.next(r/this.smoothed);let i=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>i||this.smoothed<a)&&(mf(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))}}class _f extends gf{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=lo(this.slow,e,this.params.emaAlphaSlow),this.fast=lo(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class vf extends gf{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=uo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=lo(this.emaSmoothed,e,this.params.emaAlpha);let n=fo(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=n?this.emaSmoothed:t}}class yf extends gf{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?lo(this.smoothed,e,this.params.emaAlpha):e}}class bf{static getSmoothedValue(e,t,n){return n.type===`TwoEma`?new _f({initial:e,emaAlphaSlow:n.emaAlphaSlow,emaAlphaFast:n.emaAlphaFast,changeThreshold:n.changeThreshold,fastDirection:t,deviationDepth:n.deviationDepth,deviationFactor:n.deviationFactor,label:`throughput`}):new vf({initial:e,emaAlpha:n.emaAlpha,basisTrendChangeCount:n.basisTrendChangeCount,changeThreshold:n.changeThreshold,deviationDepth:n.deviationDepth,deviationFactor:n.deviationFactor,label:`throughput`})}static getLiveBufferSmoothedValue(e,t){return new yf({initial:e,label:`liveEdgeDelay`,...t})}}import{assertNonNullable as xf,combine as Sf,ErrorCategory as Cf,filter as wf,filterChanged as Tf,fromEvent as Ef,interval as Df,isNonNullable as Of,isNullable as kf,map as Af,now as jf,throttle as Mf}from"@vkontakte/videoplayer-shared";var Nf=(e,t)=>{e&&e.playbackRate!==t&&(e.playbackRate=t)};import{isNullable as Pf,ValueSubject as Ff}from"@vkontakte/videoplayer-shared";class If{currentRepresentation$=new Ff(null);maxRepresentations=4;representationsCursor=0;representations=[];getCurrentPosition;currentSegment=null;constructor(e,t){this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Pf(e))for(let t of this.representations)for(let n of t){let t=n.segmentReference,r=t.segments.length,i=t.segments[0].time.from,a=t.segments[r-1].time.to;if(e<i||e>a)continue;let o=t.segments.find(t=>t.time.from<=e&&t.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...n,label:`Live Text`,language:`ru`,isAuto:!0,url:new URL(o.url,t.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let e=If.filterRepresentations(t.representations);if(e){this.representations[this.representationsCursor]=e,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(e=>If.filterRepresentations(e.representations))}static filterRepresentations(e){return e?.filter(e=>e.kind===`text`&&`segmentReference`in e&&Ya(e.segmentReference))}}class Lf extends qd{liveTextManager;liveStreamEndTimestamp=0;liveBuffer;livePauseWatchdogSubscription;liveWasInterrupted=!1;constructor(e){super(e),this.liveBuffer=bf.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(e){xf(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){let e=this.videoBufferManager?.getRepresentationInitialTime()??0;await super.seek(e,!1)}async tick(){await super.tick();let e=(this.element?.currentTime??0)*1e3;this.liveTextManager?.maintain(e)}setSourceInitDuration(){xf(this.source),this.source.duration=2**53-1}isStallExceeded(e){let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,n=this.liveStreamStatus$.getValue()===`active`;return(!t||n)&&super.isStallExceeded(e)}async restoreAfterDeepStall(){let{liveStallReinitInterval:e}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,n=this.currentStallDuration$.getValue(),r=this.liveStreamStatus$.getValue()===`active`;if(n%e===0){let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!r&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(e).catch(e=>{this.error$.next({id:`stallIntervalCallback`,category:Cf.VIDEO_PIPELINE,message:`stallIntervalCallback failed`,thrown:e})})}}async updateManifest(){let e=await super.updateManifest();if(kf(e))return null;if(kf(e.live))return this.error$.next({id:`ManifestParsing`,category:Cf.PARSER,message:`MPD doesnt contain live section for live stream`}),null;this.isLive$.next(!0);let{availabilityStartTime:t,latestSegmentPublishTime:n,streamIsUnpublished:r,streamIsAlive:i}=e.live,a=(e.duration??0)/1e3;this.liveSeekableDuration$.next(-1*a),this.liveDuration$.next((n-t)/1e3),this.liveAvailabilityStartTime$.next(e.live.availabilityStartTime);let o=`active`;if(i||(o=r?`unpublished`:`unexpectedly_down`),this.liveStreamStatus$.next(o),this.bufferManagers.forEach(t=>t.updateManifest(e)),this.liveTextManager?.updateLive(e),i&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(e).catch(e=>{this.error$.next({id:`updateManifest`,category:Cf.VIDEO_PIPELINE,message:`seekLive after stream restore failed`,thrown:e})})}return e}prepareManifestUrlString(e,t){return O(e,t,2)}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()===`active`?0:jf()-this.liveStreamEndTimestamp,n=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(n===0),this.manifestUrlString=O(this.manifestUrlString,n,2)}createBuffers(e,t,n,r){xf(this.manifest),super.createBuffers(e,t,n,r),If.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new If(this.manifest.streams.text,e))}initRepresentationSubscriptions(){xf(this.element),xf(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let e=this.videoBufferManager,t=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(e),this.initLiveBufferInfoSubscriptions(e,t),this.initLiveMaintainSubscription(t),Of(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){xf(this.element);let{liveUpdateInterval:e}=this.tuning.dash,t=()=>Df(e).subscribe(async t=>{let n=me(this.manifestUrlString,2);this.manifestUrlString=O(this.manifestUrlString,n+e,2),this.liveStreamStatus$.getValue()===`active`&&(this.manifest=await this.updateManifest())});this.representationSubscription.add(Ef(this.element,`pause`).subscribe(e=>{this.livePauseWatchdogSubscription=t(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add(Ef(this.element,`play`).subscribe(e=>this.livePauseWatchdogSubscription?.unsubscribe()))}initLiveDurationSubscriptions(e){this.representationSubscription.add(this.liveDuration$.pipe(Tf()).subscribe(e=>this.liveStreamEndTimestamp=jf())),this.representationSubscription.add(e.currentLowLatencySegmentLength$.subscribe(e=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!e)return;let t=this.liveSeekableDuration$.getValue()-e/1e3;this.liveSeekableDuration$.next(Math.max(t,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+e/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add(Sf({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Af(({isActiveLive:e,isLowLatency:t})=>e&&t),Tf(),wf(e=>!this.isManualDecreasePlaybackInLive())).subscribe(e=>Nf(this.element,1))),this.representationSubscription.add(Sf({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wf(e=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:e,isActiveLive:t,isLowLatency:n})=>{if(!n||!t)return;let r=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,i=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,a=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=e-r,s=1;Math.abs(o)>i&&(s=1+Math.sign(o)*a),Nf(this.element,s)}))}initLiveBufferInfoSubscriptions(e,t){this.representationSubscription.add(Sf({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wf(({bufferLength:e,isActiveLive:t,isLowLatency:n})=>t&&n&&!!e),Af(({bufferLength:e})=>e)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(e=>{let n=0;if(e){let e=(this.element?.currentTime??0)*1e3;n=Math.min(...t.map(t=>t.getLiveSegmentsToLoadState(this.manifest)?.to??e))-e}this.liveLoadBufferLength$.getValue()!==n&&this.liveLoadBufferLength$.next(n)})),this.representationSubscription.add(Sf({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:e.currentLiveSegmentServerLatency$}).pipe(wf(({isLive:e})=>e),Tf((e,t)=>t.bufferLength<e.bufferLength),Af(({rtt:e,bufferLength:t,segmentServerLatency:n})=>{let r=me(this.manifestUrlString,2);return(e/2+t+n+r)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(e){let t=0;this.representationSubscription.add(Sf({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Mf(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:n,bufferLength:r})=>{xf(this.element);let i=this.element.playbackRate,a=me(this.manifestUrlString,2),o=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,s=Math.min(o,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*i),c=this.tuning.dashCmafLive.normalizedActualBufferOffset*i,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*i,u=isFinite(n)?n:r,d=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),f=o<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(f);let p=`none`;if(d?p=`active_low_latency`:this.isLowLatency$.getValue()&&f?(e.forEach(e=>e.proceedLowLatencyLive()),p=`active_low_latency`):a!==0&&u<s?p=`live_forward_buffering`:u<s+l&&(p=`live_with_target_offset`),isFinite(n)&&(t=n>t?n:t),p===`live_forward_buffering`||p===`live_with_target_offset`){let e=t-(s+c),r=this.normalizeLiveOffset(Math.trunc(a+e/i)),o=Math.abs(r-a),l=0;!n||o<=this.tuning.dashCmafLive.offsetCalculationError?l=a:r>0&&o>this.tuning.dashCmafLive.offsetCalculationError&&(l=r),this.manifestUrlString=O(this.manifestUrlString,l,2)}(p===`live_with_target_offset`||p===`live_forward_buffering`)&&(t=0,this.manifest=await this.updateManifest())},e=>{this.error$.next({id:`updateLive`,category:Cf.VIDEO_PIPELINE,thrown:e,message:`Failed to update live with subscription`})}))}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}}class Rf extends bc{constructor(e){super(e),this.textTracksManager?.destroy()}getPlayer(){return new Lf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}subscribe(){super.subscribe();let e=!1,t=-1,{output:n,observableVideo:r,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0);let o=new ff(1);a(r.playbackRateState$,o),a(r.timeUpdate$,n.liveBufferTime$),a(this.player.liveSeekableDuration$,n.duration$),a(this.player.liveLatency$,n.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(n.elementVisible$.pipe(lf()).subscribe(t=>{let r=n.position$.getValue(),i=n.volume$.getValue(),a=!i.volume||i.muted;!t&&!r&&a?e=!0:t&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(df(e=>e.to)).subscribe(this.player.isLowLatency$)).add(of({liveBufferTime:n.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(df(({liveBufferTime:e,liveAvailabilityStartTime:t})=>e&&t?e+t:void 0)).subscribe(n.liveTime$)).add(of({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:sf(r.playbackRateState$,new ff(1))}).pipe(cf(({liveStreamStatus:e,liveDuration:t})=>e===`active`&&!!t)).subscribe(({liveDuration:e,playbackRate:r})=>{let i=n.liveBufferTime$.getValue(),a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;a||r<1-o||this.allocation.target.paused||uf(i)||(t=e-i)})).add(of({time:n.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:sf(r.playbackRateState$,new ff(1))}).pipe(lf((e,t)=>this.player.liveStreamStatus$.getValue()===`active`?e.liveDuration===t.liveDuration:e.time===t.time)).subscribe(({time:e,liveDuration:r,playbackRate:i})=>{let a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;if(!a&&!this.allocation.target.paused&&i>=1-o||uf(e)||uf(r))return;let s=-1*(r-e-t);n.position$.next(Math.min(s,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(e=>{if(e){let t=Ka(e);this.params.output.availableTextTracks$.next([t])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(cf(e=>pf(e))).subscribe(e=>n.isLiveEnded$.next(e===`unpublished`&&n.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,n=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(n).then(()=>{this.params.output.position$.next(e/1e3)})}}import{assertNever as zf,assertNonNullable as Bf,combine as Vf,debounce as Hf,ErrorCategory as Uf,filter as Wf,filterChanged as Gf,fromEvent as Kf,isNonNullable as qf,isNullable as Jf,map as Yf,merge as Xf,observableFrom as Zf,once as Qf,Subscription as $f,throttle as ep,timeout as tp}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as np}from"@vkontakte/videoplayer-shared";var rp=(e,t,n=0)=>{for(let r=0;r<e.length;r++)if(e.start(r)*1e3-n<=t&&e.end(r)*1e3+n>t)return!0;return!1};import{abortable as ip,assertNonNullable as ap,combine as op,ErrorCategory as U,filter as sp,filterChanged as cp,flattenObject as lp,fromEvent as up,getTraceSubscriptionMethod as dp,interval as fp,isNonNullable as pp,isNullable as mp,map as hp,merge as gp,now as _p,Subject as vp,Subscription as yp,SubscriptionRemovable as bp,tap as xp,throttle as Sp,ValueSubject as W}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as Cp}from"@vkontakte/videoplayer-shared";import{cancelIdleCallbackPolyfilled as wp}from"@vkontakte/videoplayer-shared";import{requestIdleCallbackPolyfilled as Tp}from"@vkontakte/videoplayer-shared";import{assertNever as Ep,ErrorCategory as Dp,Subject as Op}from"@vkontakte/videoplayer-shared";var kp=18,Ap=!1;try{Ap=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=kp}catch(e){console.error(e)}class jp{bufferFull$=new Op;error$=new Op;buffer;queue=[];currentTask=null;destroyed=!1;abortRequested=!1;isAbortFixEnabled=!1;constructor(e,t=!1){this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener(`updateend`,this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(n=>{let r={operation:`append`,data:e,signal:t,callback:n};this.queue.push(r),this.pull()})}async remove(e,t,n){return n&&n.aborted?!1:new Promise(r=>{let i={operation:`remove`,from:e,to:t,signal:n,callback:r};this.queue.unshift(i),this.pull()})}async abort(e){return new Promise(t=>{let n,r=e=>{this.abortRequested=!1,t(e)};n=Ap&&e?{operation:`safariAbort`,init:e,callback:r}:{operation:`abort`,callback:r},this.isAbortFixEnabled&&this.currentTask&&(this.currentTask.callback(!1),this.currentTask=null);for(let{callback:e}of this.queue)e(!1);this.abortRequested=!0,n&&(this.queue=[n]),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}}completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:`BufferTaskQueueUnknown`,category:Dp.VIDEO_PIPELINE,message:`Buffer appending or removal failed`,thrown:e})}};pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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(e){e instanceof DOMException&&e.name===`QuotaExceededError`&&t===`append`?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&e.name===`InvalidStateError`||this.error$.next({id:`BufferTaskQueue:${t}`,category:Dp.VIDEO_PIPELINE,message:`Buffer operation failed`,thrown:e}),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:Ep(t)}}}var Mp=jp;import{abortable as Np,assertNonNullable as G,ErrorCategory as Pp,fromEvent as Fp,getExponentialDelay as Ip,getWindow as Lp,isHigher as Rp,isNonNullable as zp,isNullable as K,now as Bp,once as Vp,Subject as Hp,Subscription as Up,ValueSubject as Wp,isAbortError as Gp}from"@vkontakte/videoplayer-shared";class Kp{currentLiveSegmentServerLatency$=new Wp(0);currentLowLatencySegmentLength$=new Wp(0);currentSegmentLength$=new Wp(0);onLastSegment$=new Wp(!1);fullyBuffered$=new Wp(!1);playingRepresentation$=new Wp(void 0);playingRepresentationInit$=new Wp(void 0);error$=new Hp;gaps=[];updateEnd$=new Wp(void 0);subscription=new Up;kind;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;forwardBufferRepresentations=new Map;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Cp;switchAbortController=new Cp;destroyAbortController=new Cp;useSmartRepresentationSwitch=!1;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;baseUrls=[];baseUrlsIndex=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;lastDataObtainedTimestampMs=0;loadByteRangeSegmentsTimeoutId=0;constructor(e,t,n,{fetcher:r,tuning:i,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:s=!1,manifest:c}){this.fetcher=r,this.tuning=i,this.compatibilityMode=s,this.forwardBufferTarget=i.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(n.map(e=>[e.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(n.map(e=>[e.id,e])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Np(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);G(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mp(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Fp(this.sourceBuffer,`updateend`).subscribe(this.updateEnd$)),this.subscription.add(Fp(this.sourceBuffer,`updateend`).subscribe(()=>{this.checkEjectedSegments(),this.maintain()},e=>{let t,n=this.mediaSource.readyState;n!==`open`&&(t={id:`SegmentEjection_source_${n}`,category:Pp.VIDEO_PIPELINE,message:`Error when trying to clear segments ejected by browser`,thrown:e}),t??={id:`SegmentEjection`,category:Pp.VIDEO_PIPELINE,message:`Error when trying to clear segments ejected by browser`,thrown:e},this.error$.next(t)})),this.subscription.add(Fp(this.sourceBuffer,`error`).subscribe(()=>this.error$.next({id:`SourceBuffer`,category:Pp.VIDEO_PIPELINE,message:`SourceBuffer Error event fired`}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(e=>{let t=this.getCurrentPosition();if(!this.sourceBuffer||!t||!I(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,Zn(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let r=this.getForwardBufferDuration(t),i=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(t,e*2,r<i).catch(e=>{this.handleAsyncError(e,`pruneBuffer`)})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(e=>this.error$.next(e))),yield this.loadInit(t,`high`,!0);let n=this.initData.get(t.id),r=this.segments.get(t.id),i=this.parsedInitData.get(t.id);G(n,`No init buffer for starting representation`),G(r,`No segments for starting representation`),n instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(i))}.bind(this));switchToWithPreviousAbort(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return Promise.resolve();this.switchAbortController.abort(),this.switchAbortController=new Cp;let n=this.switchAbortController.signal;return n.addEventListener(`abort`,()=>{this.switchingToRepresentationId===e&&(this.switchingToRepresentationId=void 0)},{once:!0}),Np(n,async function*(e,t=!1){this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)){this.switchingToRepresentationId===e&&(this.switchingToRepresentationId=void 0);return}if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let t=this.getCurrentPosition();zp(t)&&!this.isLive&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.downloadingRepresentationId=e,this.switchingToRepresentationId=void 0}this.maintain()}.bind(this))(e,t)}switchTo=Np(this.destroyAbortController.signal,async function*(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(!i||!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let t=this.getCurrentPosition();zp(t)&&!this.isLive&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));switchToOld=Np(this.destroyAbortController.signal,async function*(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(!i||!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let t=this.getCurrentPosition();zp(t)&&(!this.isLive&&!this.tuning.dash.useNewRepresentationSwitch&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.maintain(t)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));warmUpMediaSource(){!K(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 Cp,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||zp(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),n=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),i=this.segments.get(this.playingRepresentationId);if(G(t,`No such representation ${this.downloadingRepresentationId}`),G(n,`No such representation ${this.playingRepresentationId}`),K(r)||K(i))return;let a=r.find(t=>e>=t.time.from&&e<t.time.to);zp(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let o=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let r=this.getForwardBufferDuration(e),i=Hu(n),s=Hu(t),c=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&zp(i)&&zp(s)&&Rp(i.quality,s.quality),l=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(c||l?o+=Math.min(r,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&r>=a.time.to-e+100&&(o=a?a.time.to+100:-1/0),this.tuning.dash.useNewRepresentationSwitch){let t=[...this.segments.entries()].map(([t,n])=>({representationId:t,status:n.find(t=>e>=t.time.from&&e<t.time.to)?.status})).sort((e,t)=>{let n=this.representations.get(e.representationId),r=this.representations.get(t.representationId);if(K(n)||K(r))return 0;let i=Hu(n),a=Hu(r);return K(i)||K(a)?0:Rp(i.quality,a.quality)?-1:1}).find(e=>e.status===`fed`)?.representationId;t&&(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Zn(this.sourceBuffer.buffered)>=this.bufferLimit){let t=this.getForwardBufferDuration(e),n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,t<n).catch(e=>{this.handleAsyncError(e,`pruneBuffer`)});return}let s=[];if(!this.activeSegments.size&&(s=this.selectForwardBufferSegments(r,t.segmentReference.type,o),s.length)){let e=`auto`;if(this.tuning.dash.useFetchPriorityHints&&a)if(s.includes(a))e=`high`;else{let t=s.at(0);t&&t.time.from-a.time.to>=this.forwardBufferTarget/2&&(e=`low`)}this.loadSegments(s,t,e).catch(e=>{this.handleAsyncError(e,`loadSegments`)})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===`fed`&&!s.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=r.at(-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<100),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let n=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let i of e)Math.trunc(i.time.from-n)>0&&this.gaps.push({representation:t.id,from:n,to:i.time.from+r,persistent:!0}),n=i.time.to;zp(t.duration)&&t.duration-n>0&&!this.isLive&&this.gaps.push({representation:t.id,from:n,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,n=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],i=0,a=t.length-1;do r.unshift(t[a]),i+=t[a].time.to-t[a].time.from,a--;while(i<n&&a>=0);return this.liveInitialAdditionalOffset=i-n,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let n=t.flatMap(e=>e.representations).find(e=>e.id===this.downloadingRepresentationId);if(!n)return;let r=this.segments.get(n.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}seekLive=Np(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(e=>e.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let e of this.representations.keys()){let n=t.find(t=>t.id===e);n&&this.representations.set(e,n);let r=this.representations.get(e);if(!r||!Yu(r.segmentReference)){this.isSeekingLive=!1;return}let i=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,i)}let n=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(n);G(r,`Representation not found by id ${n}`);let i=this.segments.get(n);G(i,`No segments for starting representation`);let a=this.initData.get(n);if(G(a,`No init buffer for starting representation`),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(i,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){if(!e||[...this.segments.values()].every(e=>!e.length))return;let t=e.streams[this.kind].flatMap(e=>e.representations);for(let e of t){if(!e||!Yu(e.segmentReference))return;let t=e.segmentReference.segments.map(e=>({...e,status:`none`,size:void 0})),n=this.segments.get(e.id)??[],r=n.at(-1)?.time.to??0,i=t?.findIndex(e=>r>=e.time.from+100&&r<=e.time.to+100);if(i===-1){this.liveUpdateSegmentIndex=0;let t=this.getActualLiveStartingSegments(e.segmentReference);this.segments.set(e.id,t)}else{let r=t.slice(i+1);this.segments.set(e.id,[...n,...r])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;G(e);let t=this.segments.get(e);if(t?.length){let e=t[t.length-1];this.updateLowLatencyLiveIfNeeded(e)}}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 n of this.representations.values()){let r=n.segmentReference;if(!Yu(r))return;let i=this.segments.get(n.id)??[],a=i.find(t=>Math.floor(t.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),!i.find(t=>Math.floor(t.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let t=Math.round(e.time.to*r.timescale/1e3).toString(10),n=Ml(r.segmentTemplateUrl,{segmentTime:t});i.push({status:`none`,time:{from:e.time.to,to:1/0},url:n})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let n=this.segments.get(t);return n?n.find(t=>t.time.from<=e&&t.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&&wp&&wp(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&wp&&wp(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,n){return this.isLive?this.selectForwardBufferSegmentsLive(e,n):this.selectForwardBufferSegmentsRecord(e,t,n)}selectForwardBufferSegmentsLive(e,t){let n=e.findIndex(e=>t>=e.time.from&&t<e.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=n),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,n){let r=this.getForwardBufferDuration(n),i=Math.min(this.forwardBufferTarget,this.bufferLimit),a=e.findIndex(({status:e,time:{from:t,to:a}},o)=>{let s=t>n||t<=n&&a>=n||o===0&&n===0,c=this.preloadOnly&&t<=n+i||r<i&&a-t>=i||a<=n+i;return(e===`none`||e===`partially_ejected`&&s&&c&&this.sourceBuffer&&I(this.mediaSource,this.sourceBuffer)&&!(rp(this.sourceBuffer.buffered,t)&&rp(this.sourceBuffer.buffered,a)))&&s&&c});if(a===-1)return[];if(t!==`byteRange`)return e.slice(a,a+1);let o=e,s=0,c=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let e=a;e<o.length&&(s<=u||c<=d);e++){let t=o[e];if(e>a&&t.time.from>=n+i)break;if(s+=t.byte.to+1-t.byte.from,c+=t.time.to+1-t.time.from,t.status===`none`||t.status===`partially_ejected`)l.push(t);else break}return l}async loadSegments(e,t,n=`auto`){Yu(t.segmentReference)?await this.loadTemplateSegment(e[0],t,n):await this.loadByteRangeSegments(e,t,n)}async loadTemplateSegment(e,t,n=`auto`){e.status=`downloading`;let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id,startedAtMs:void 0};this.activeSegments.add(r);let{range:i,url:a,signal:o,onProgress:s,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Np(o,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>setTimeout(t,e))}.bind(this))(),o.aborted&&this.abortActiveSegments([e])),r.startedAtMs=Lp().performance.now();try{let e=await this.fetcher.fetch(a,{range:i,signal:o,onProgress:s,priority:n,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Bp(),!e)return;let l=new DataView(e),u=Bu(t.mime);if(!isFinite(r.segment.time.to)){let e=t.segmentReference.timescale;r.segment.time.to=u.getChunkEndTime(l,e)}s&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:d,serverDataPreparedTime:f}=u.getServerLatencyTimestamps(l);d&&f&&this.currentLiveSegmentServerLatency$.next(f-d),r.segment.status=`downloaded`,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(t){this.abortActiveSegments([e]),Gp(t)||(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())Yu(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,n=`auto`){if(!e.length)return;let r=[];for(let n of e){n.status=`downloading`;let e={segment:n,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id,startedAtMs:void 0};this.activeSegments.add(e),r.push(e)}let{range:i,url:a,signal:o,onProgress:s}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Np(o,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),Fp(window,`online`).pipe(Vp()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));let c=Lp().performance.now();for(let e of r)e.startedAtMs=c;try{await this.fetcher.fetch(a,{range:i,onProgress:s,signal:o,priority:n,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation,urlCacheMechanismEnabled:!Yu(t.segmentReference)}),this.lastDataObtainedTimestampMs=Bp(),this.failedDownloads=0}catch(t){this.abortActiveSegments(e),Gp(t)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Yu(t.segmentReference))throw Error(`Representation is not byte range type`);let n=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:i}=this.downloadAbortController;return{url:n,range:r,signal:i,onProgress:async(e,n)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Bp(),await this.onSomeByteRangesDataLoaded({dataView:e,loaded:n,signal:i,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:Pp.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Yu(t.segmentReference))throw Error(`Representation is not template type`);let n=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&n.searchParams.set(`low-latency`,`yes`);let r=n.toString(),{signal:i}=this.downloadAbortController,a=[];return{url:r,signal:i,onProgress:this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(e,n)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Bp();let r=this.onSomeTemplateDataLoaded({dataView:e,loaded:n,signal:i,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(r)}catch(e){this.error$.next({id:`SegmentFeeding`,category:Pp.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}}:void 0,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:n,onSegmentAppendFailed:r,signal:i}){if(!this.activeSegments.size||!I(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:s}=o;if(o.representationId===t){if(i.aborted){r();continue}if(o.loadedBytes=n,o.loadedBytes>o.feedingBytes){let t=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),n=Bu(a.mime).parseFeedableSegmentChunk(t,this.isLive);n?.byteLength&&(s.status=`partially_fed`,o.feedingBytes+=n.byteLength,await this.sourceBufferTaskQueue.append(n),o.fedBytes+=n.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:n,loaded:r,signal:i,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!I(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let s of this.activeSegments){let{segment:c}=s;if(s.representationId!==t)continue;if(i.aborted){await a();continue}let l=c.byte.from-n,u=c.byte.to-n,d=u-l+1,f=l<r,p=u<=r;if(!f)continue;let m=Bu(o.mime);if(c.status===`downloading`&&p){c.status=`downloaded`;let n=new DataView(e.buffer,e.byteOffset+l,d);await this.sourceBufferTaskQueue.append(n,i)&&!i.aborted?this.onSegmentFullyAppended(s,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status===`downloading`||c.status===`partially_fed`)&&(s.loadedBytes=Math.min(d,r-l),s.loadedBytes>s.feedingBytes)){let n=new DataView(e.buffer,e.byteOffset+l+s.feedingBytes,s.loadedBytes-s.feedingBytes),r=s.loadedBytes===d?n:m.parseFeedableSegmentChunk(n);r?.byteLength&&(c.status=`partially_fed`,s.feedingBytes+=r.byteLength,await this.sourceBufferTaskQueue.append(r,i)&&!i.aborted?(s.fedBytes+=r.byteLength,s.fedBytes===d&&this.onSegmentFullyAppended(s,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer))){!this.isLive&&A.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(rp(this.sourceBuffer.buffered,e.segment.time.from,100)&&rp(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:`EmptyAppendBuffer`,category:Pp.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`,Ju(e.segment)&&(e.segment.size=e.fedBytes);for(let n of this.representations.values())if(n.id!==t)for(let t of this.segments.get(n.id)??[])t.status===`fed`&&Math.round(t.time.from)===Math.round(e.segment.time.from)&&Math.round(t.time.to)===Math.round(e.segment.time.to)&&(t.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[n,r]of this.initData.entries()){let i=r instanceof Promise;t||=i,r===null&&(e=n)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let n=this.representations.get(e);n&&(this.initLoadIdleCallback=Tp(()=>this.loadInit(n,`low`,!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t=`auto`,n=!1){let r=this.tuning.dash.useFetchPriorityHints?t:`auto`,i=!n&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,a=(!n&&this.failedDownloads>0?Np(this.destroyAbortController.signal,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>setTimeout(t,e))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Bu(e.mime),{priority:r,ignoreNetworkErrors:i})).then(async t=>{if(!t)return;let{init:n,dataView:r,segments:i}=t,a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);this.initData.set(e.id,a);let o=i;this.isLive&&Yu(e.segmentReference)&&(o=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,o),n&&this.parsedInitData.set(e.id,n)}).then(()=>this.failedDownloads=0,t=>{i||this.initData.set(e.id,null),n&&this.error$.next({id:`LoadInits`,category:Pp.WTF,message:`loadInit threw`,thrown:t})});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,n=!1){if(!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||K(e))return!1;let r=[],i=0,a=e=>{e.sort((e,t)=>e.from-t.from);let t=[e[0]];for(let n=1;n<e.length;n++){let{from:r,to:i}=e[n],a=t[t.length-1];a.to>=r?a.to=Math.max(a.to,i):t.push(e[n])}return t},o=e=>{if(i>=t)return r;r.push({...e.time}),r=a(r);let n=Ju(e)?e.size??0:e.byte.to-e.byte.from;i+=n};for(let t of this.segments.values())for(let n of t){let t=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,r=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(t||r)&&n.status===`fed`&&o(n)}for(let e=0;e<this.sourceBuffer.buffered.length;e++){let t=this.sourceBuffer.buffered.start(e)*1e3,n=this.sourceBuffer.buffered.end(e)*1e3,r=0;for(let e of this.segments.values())for(let i of e)[`none`,`partially_ejected`].includes(i.status)&&Math.round(i.time.from)<=Math.round(t)&&Math.round(i.time.to)>=Math.round(n)&&r++;r===this.segments.size&&o({time:{from:t,to:n},url:``,status:`none`})}if(r.length&&n){let t=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let n of this.segments.values())for(let r of n)r.time.from>=e+t&&r.status===`fed`&&o(r)}return r.length?(await Promise.all(r.map(e=>this.sourceBufferTaskQueue.remove(e.from,e.to)))).reduce((e,t)=>e||t,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!I(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||!I(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||!I(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||K(e)?0:kd(this.sourceBuffer.buffered,e)}getForwardBufferRepresentations(e=this.getCurrentPosition()){if(this.forwardBufferRepresentations.clear(),zp(e))for(let[t,n]of this.segments.entries())this.forwardBufferRepresentations.set(t,n.filter(t=>t.time.from>=e&&t.time.to<=e+this.forwardBufferTarget));return this.forwardBufferRepresentations}getMpdSegmentDuration(){for(let e of this.segments.values()){let t=e[0];if(t&&t.time.to>t.time.from)return t.time.to-t.time.from}}getActiveSegmentProgress(){let e;for(let t of this.activeSegments)K(t.startedAtMs)||(!e||t.segment.time.from<e.segment.time.from)&&(e=t);if(!K(e?.startedAtMs))return{startedAtMs:e.startedAtMs,loadedBytes:e.loadedBytes,totalBytes:e.segment.size??void 0,segmentDurationMs:e.segment.time.to-e.segment.time.from}}detectGaps(e,t){if(!(!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)))for(let n of t){let t={representation:e,from:n.time.from,to:n.time.to,persistent:!1},{buffered:r}=this.sourceBuffer;for(let e=0;e<r.length;e++){let i=r.start(e)*1e3,a=r.end(e)*1e3;if(!(a<=n.time.from||i>=n.time.to)){if(i<=n.time.from&&a>=n.time.to){t=void 0;break}a>n.time.from&&a<n.time.to&&(t.from=a),i<n.time.to&&i>n.time.from&&(t.to=i)}}t&&t.to-t.from>1&&!this.gaps.some(e=>t&&e.from===t.from&&e.to===t.to)&&this.gaps.push(t)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer))return;let{buffered:n}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(e=>{if(r&&e.persistent)return!0;let t=Math.round(e.from),i=Math.round(e.to);for(let e=0;e<n.length;e++)if(t>=Math.round(n.start(e)*1e3)&&i<=Math.round(n.end(e)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Tp(()=>{try{this.detectGaps(e,t)}catch(e){this.error$.next({id:`GapDetection`,category:Pp.WTF,message:`detectGaps threw`,thrown:e})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||K(this.playingRepresentationId))return;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){let n=Math.floor(this.sourceBuffer.buffered.start(t)*1e3),r=Math.ceil(this.sourceBuffer.buffered.end(t)*1e3);e.push({from:n,to:r})}for(let t of this.segments.values())for(let n of t){let{status:t}=n;if(t!==`fed`&&t!==`partially_ejected`)continue;let r=Math.floor(n.time.from),i=Math.ceil(n.time.to),a=e.some(e=>e.from-100<=r&&e.to+100>=i),o=e.filter(e=>r>=e.from&&r<e.to-100||i>e.from+100&&i<=e.to);a||(o.length===1||this.gaps.some(e=>e.from===n.time.from||e.to===n.time.to)?n.status=`partially_ejected`:n.status=`none`)}}handleAsyncError(e,t){this.error$.next({id:t,category:Pp.VIDEO_PIPELINE,thrown:e,message:`Something went wrong`})}}import{AbortControllerPolyfilled as qp}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Jp}from"@vkontakte/videoplayer-shared";import{abortable as Yp,assertNever as Xp,fromEvent as Zp,merge as Qp,now as $p,Subject as em,ValueSubject as tm,flattenObject as nm,ErrorCategory as rm,SubscriptionRemovable as im,getWindow as am,suppressAbort as om}from"@vkontakte/videoplayer-shared";import{ErrorCategory as sm}from"@vkontakte/videoplayer-shared";var cm=new Set([2,3,4,5,6,9,19]),lm=new Set([1,8,18,21]),um=new Set([10,11,12,13,14,15,16]),dm=({txtCode:e,error$:t,recoverableError$:n,httpCode:r})=>{let i=parseInt(e);if(isNaN(i))return;let a={...fm(i),httpCode:r,UVBackendErrorCode:e,origin:`segment_fetcher`};if(cm.has(i)){t.next({...a,category:sm.NETWORK});return}if(lm.has(i)){n.next({...a,category:sm.FATAL,canBeRecoverable:!0});return}if(um.has(i)){t.next({...a,category:sm.FATAL});return}},fm=e=>{switch(e){case 1:return{id:`VideoDataLinkExpiredError`,message:`Video data links have expired`};case 5:return{id:`VideoServerError`,message:`Server error`};case 8:return{id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`};case 10:return{id:`UserAgentChange`,message:`User agent changed`};case 11:return{id:`forbiddenReferer`,message:`Forbidden referer`};case 12:case 13:case 14:case 15:case 16:return{id:`OKerror`,message:`Error #${e}`};case 18:return{id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`};case 21:return{id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`};default:return pm(e)}};function pm(e){return{id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${e})`}}import{devNull as mm,getWindow as hm}from"@vkontakte/videoplayer-shared";var gm=`vk_player_cached_fetches`,_m=[`fromCache`,`expires`,`sig`],vm=300*1e3,ym=`x-cache-expires`,bm=async e=>{let t=Sm(e),n=await hm().caches.open(gm);return{get:async()=>{let e=await n.match(t);return e&&!Cm(e)?(mm.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_hit`]}),e):(e&&(await n.delete(t),mm.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_missed`,`expired`]})),null)},set:r=>{n.put(t,wm(r,e))}}};function xm(){return typeof caches<`u`}function Sm(e){try{let t=new URL(e);return t.hostname=`cache.local`,_m.forEach(e=>t.searchParams.delete(e)),t.toString()}catch{return e}}function Cm(e){let t=e.headers.get(ym);if(!t)return!0;let n=Number(t);return isNaN(n)||n<=Date.now()}function wm(e,t){let n=e.clone(),r=new Headers(n.headers);return r.set(ym,Tm(t).toString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:r})}function Tm(e){try{let t=new URL(e).searchParams.get(`expires`);if(t&&!isNaN(Number(t)))return Number(t)}catch{return 0}return Date.now()+vm}var Em=async()=>{await hm().caches.delete(gm)};class Dm{throughputEstimator;requestQuic;tracer;manifestRequested$=new em;firstBytesManifest$=new em;firstBytesRequested$=new em;firstBytesReceived$=new em;lastConnectionType$=new tm(void 0);lastConnectionReused$=new tm(void 0);lastRequestFirstBytes$=new tm(void 0);lastConnectionMetrics$=new tm(void 0);lastDownloadMetrics$=new tm(void 0);recoverableError$=new em;error$=new em;abortAllController=new qp;subscription=new im;compatibilityMode;useEnableSubtitlesParam;useUrlCacheMechanism;measureNonSegmentRequests;startupPhase=!0;performanceObserver=null;pendingConnectionMetrics=new Map;handleExtendedNetworkErrorsSet=!1;constructor({throughputEstimator:e,requestQuic:t,tracer:n,compatibilityMode:r=!1,useEnableSubtitlesParam:i=!1,handleExtendedNetworkErrorsSet:a=!1,useUrlCacheMechanism:o=!1,measureNonSegmentRequests:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=n.createComponentTracer(`Fetcher`),this.useEnableSubtitlesParam=i,this.handleExtendedNetworkErrorsSet=a,this.measureNonSegmentRequests=s,am().PerformanceObserver&&this.setupPerformanceObserver(),this.useUrlCacheMechanism=o}onHeadersReceived(e){let{type:t,reused:n}=Gc(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(n)}setupPerformanceObserver(){this.performanceObserver=new(am()).PerformanceObserver(e=>{e.getEntriesByType(`resource`).forEach(e=>{this.processPerformanceResourceTiming(e)})}),this.performanceObserver.observe({entryTypes:[`resource`]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let n=this.extractConnectionMetrics(e);n&&this.lastConnectionMetrics$.next(n)}estimateNetworkType(){if(!(`connection`in am().navigator))return`unknown`;let e=am().navigator.connection;return e.effectiveType?{"slow-2g":`2g`,"2g":`2g`,"3g":`3g`,"4g":`lte`}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?`2g`:e.downlink<5?`3g`:e.downlink<50?`lte`:`wifi`:e.rtt?e.rtt>500?`2g`:e.rtt>250?`3g`:e.rtt>50?`lte`:`wifi`:`unknown`}extractConnectionMetrics(e){let t=0,n=0,r=0,i=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(i=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,n=e.secureConnectionStart-e.connectStart):n=i),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,n),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,i),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,n]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),i=r.origin+r.pathname,a=new URL(n.url);if(i===a.origin+a.pathname&&e.startTime>=n.startTime-10&&e.startTime<=n.startTime+1e3)return t}}catch{this.recoverableError$.next({id:`VideoDataFetchError`,message:`Video data fetch error with getting download metrics`,category:rm.WTF})}return null}trackRequestStart(e,t){let n=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(n,{url:e,startTime:t})}fetchManifest=Yp(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer(`FetchManifest`),n=e;this.requestQuic&&(n=Wc(n)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(n=il(n)),this.trackRequestStart(n,performance.now());let r=$p();this.manifestRequested$.next();let i=yield this.doFetch(n,{signal:this.abortAllController.signal}).catch(om);if(i){let a=$p();t.log(`success`,nm({url:n,message:`Request successfully executed`})),t.end(),this.onHeadersReceived(i.headers),this.firstBytesManifest$.next();let o=i.headers.get(`content-length`),s=0;o&&(s=parseInt(o,10));let c=await i.text();if((!o||isNaN(s)||s<=0)&&(s=new TextEncoder().encode(c).length),s>0){let t=a-r,n=s/(t/1e3)*8/1024,i={bytes:s,speed:n,url:e};this.lastDownloadMetrics$.next(i)}if(this.measureNonSegmentRequests&&this.startupPhase&&(this.throughputEstimator?.addRawRtt(a-r),o&&s>0)){let e=$p();this.throughputEstimator?.addRawSpeed(s,e-r)}return c}else return t.error(`error`,nm({url:n,message:`No data in request manifest`})),t.end(),null}.bind(this));fetch=Yp(this.abortAllController.signal,async function*(e,{rangeMethod:t=+!this.compatibilityMode,range:n,onProgress:r,priority:i=`auto`,signal:a,measureThroughput:o=!0,isLowLatency:s=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:l=!1,urlCacheMechanismEnabled:u=!1}={}){let d=e,f=new Headers,p=this.tracer.createComponentTracer(`Fetch`);if(n)switch(t){case 0:f.append(`Range`,`bytes=${n.from}-${n.to}`);break;case 1:{let e=new URL(d,am().location.href);e.searchParams.append(`bytes`,`${n.from}-${n.to}`),d=e.toString();break}default:Xp(t)}this.requestQuic&&(d=Wc(d));let m=this.abortAllController.signal,h;if(a){let e=new qp;if(h=Qp(Zp(this.abortAllController.signal,`abort`),Zp(a,`abort`)).subscribe(()=>{try{e.abort()}catch(e){om(e)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{e.abort()}catch(e){om(e)}m=e.signal}let g=0,_=$p();p.log(`startRequest`,nm({url:d,priority:i,rangeMethod:t,range:n,isLowLatency:s,requestStartedAt:_})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested$.next();let v=yield this.doFetch(d,{priority:i,headers:f,signal:m},{ignoreNetworkErrors:l,urlCacheMechanismEnabled:u}),y=$p();if(!v)return p.error(`error`,{message:`No response in request`}),p.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(y-_),!v.ok||!v.body){this.unsubscribeAbortSubscription(h);let e=`Fetch error ${v.status}: ${v.statusText}`;return p.error(`error`,{message:e}),p.end(),Promise.reject(Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let e=yield v.arrayBuffer(),t=$p();if(this.measureNonSegmentRequests&&this.startupPhase){let e=v.headers.get(`content-length`),n=e?parseInt(e,10):NaN;Number.isFinite(n)&&n>0&&this.throughputEstimator?.addRawSpeed(n,t-_)}let n={requestStartedAt:_,requestEndedAt:t,duration:t-_};return p.log(`endRequest`,nm(n)),p.end(),e}let b=v.body;if(o){this.startupPhase=!1;let e;[b,e]=v.body.tee(),this.throughputEstimator?.trackStream(e,s)}let x=b.getReader(),S,C=parseInt(v.headers.get(`content-length`)??``,10);Number.isFinite(C)&&(S=C),!S&&n&&(S=n.to-n.from+1);let w=S?new Uint8Array(S):new Uint8Array,T=!1,E=e=>{this.unsubscribeAbortSubscription(h),T=!0,om(e)},ee=Yp(m,async function*({done:e,value:t}){if(g===0&&(this.lastRequestFirstBytes$.next($p()-_),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(h);return}if(!e&&t){if(c&&S)w.set(t,g),g+=t.byteLength;else{let e=new Uint8Array(w.length+t.length);e.set(w),e.set(t,w.length),w=e,g+=t.byteLength}r?.(new DataView(w.buffer),g),yield x?.read().then(ee,E)}}.bind(this));yield x?.read().then(ee,E),this.unsubscribeAbortSubscription(h);let te=$p(),D={failed:T,requestStartedAt:_,requestEndedAt:te,duration:te-_};if(T)return p.error(`endRequest`,nm(D)),p.end(),null;if(g>0){let t=te-_,n=g/(t/1e3)*8/1024,r={bytes:g,speed:n,url:e};this.lastDownloadMetrics$.next(r)}return p.log(`endRequest`,nm(D)),p.end(),w.buffer}.bind(this));async fetchRepresentation(e,t,n){let{type:r}=e;switch(r){case`byteRange`:return await this.fetchByteRangeRepresentation(e,t,n)??null;case`template`:return await this.fetchTemplateRepresentation(e,n)??null;default:Xp(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&=(this.performanceObserver.disconnect(),null),this.pendingConnectionMetrics.clear(),this.tracer.end()}fetchByteRangeRepresentation=Yp(this.abortAllController.signal,async function*(e,t,n){if(e.type!==`byteRange`)return null;let{from:r,to:i}=e.initRange,a=r,o=i,s=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,s=i+1===c,s&&(a=Math.min(c,r),o=Math.max(l,i))),a=Math.min(a,0);let u=yield this.fetch(e.url,{range:{from:a,to:o},measureThroughput:!1,urlCacheMechanismEnabled:!0,...n});if(!u)return null;let d=new DataView(u,r-a,i-a+1);if(!t.validateData(d))throw Error(`Invalid media file`);let f=t.parseInit(d),p=e.indexRange??t.getIndexRange(f);if(!p)throw ReferenceError(`No way to load representation index`);let m;if(s)m=new DataView(u,p.from-a,p.to-p.from+1);else{let t=yield this.fetch(e.url,{range:p,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!t)return null;m=new DataView(t)}let h=t.parseSegments(m,f,p);return{init:f,dataView:new DataView(u),segments:h}}.bind(this));fetchTemplateRepresentation=Yp(this.abortAllController.signal,async function*(e,t){if(e.type!==`template`)return null;let n=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(n,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(e=>({...e,status:`none`,size:void 0})),dataView:new DataView(r)}:null}.bind(this));async doFetch(e,t,n){let r;if(this.useUrlCacheMechanism&&n?.urlCacheMechanismEnabled&&xm()){r=await bm(e);let t=await r.get();if(t)return t}let i=await Jp(e,r?{...t,cache:`no-store`}:t);if(i.ok)return r?.set(i),i;if(n?.ignoreNetworkErrors)return;let a=await i.text();if(this.handleExtendedNetworkErrorsSet){dm({txtCode:a,httpCode:i.status,error$:this.error$,recoverableError$:this.recoverableError$});return}let o=parseInt(a);if(!isNaN(o))switch(o){case 1:this.recoverableError$.next({id:`VideoDataLinkExpiredError`,message:`Video data links have expired`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;default:this.error$.next({id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${o})`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}}import{isNullable as Om,ValueSubject as km}from"@vkontakte/videoplayer-shared";class Am{currentRepresentation$=new km(null);maxRepresentations=4;representationsCursor=0;representations=[];getCurrentPosition;currentSegment=null;constructor(e,t){this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Om(e))for(let t of this.representations)for(let n of t){let t=n.segmentReference,r=t.segments.length,i=t.segments[0].time.from,a=t.segments[r-1].time.to;if(e<i||e>a)continue;let o=t.segments.find(t=>t.time.from<=e&&t.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...n,label:`Live Text`,language:`ru`,isAuto:!0,url:new URL(o.url,t.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let e=Am.filterRepresentations(t.representations);if(e){this.representations[this.representationsCursor]=e,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(e=>Am.filterRepresentations(e.representations))}static filterRepresentations(e){return e?.filter(e=>e.kind===`text`&&`segmentReference`in e&&Yu(e.segmentReference))}}var jm=[`timeupdate`,`progress`,`play`,`seeked`,`stalled`,`waiting`],Mm=[`timeupdate`,`progress`,`loadeddata`,`playing`,`seeked`];class Nm{element=null;manifestUrlString=``;source=null;manifest=null;tuning;tracer;forceVideoCodec;videoBufferManager;audioBufferManager;bufferManagers=[];liveTextManager;throughputEstimator;subscription=new yp;subscriptionRemovable=new bp;representationSubscription=new yp;fetcher;state$=new Dt(`none`);currentVideoRepresentation$=new W(void 0);currentVideoRepresentationInit$=new W(void 0);currentAudioRepresentation$=new W(void 0);currentVideoSegmentLength$=new W(0);currentAudioSegmentLength$=new W(0);error$=new vp;manifestRequested$=new vp;firstBytesManifest$=new vp;manifestReceived$=new vp;firstBytesRequested$=new vp;firstBytesReceived$=new vp;lastConnectionType$=new W(void 0);lastConnectionReused$=new W(void 0);lastRequestFirstBytes$=new W(void 0);lastConnectionMetrics$=new W(void 0);lastDownloadMetrics$=new W(void 0);currentLiveTextRepresentation$=new W(null);timeoutSourceOpenId;isLive$=new W(!1);isActiveLive$=new W(!1);isLowLatency$=new W(!1);liveDuration$=new W(0);liveSeekableDuration$=new W(0);liveAvailabilityStartTime$=new W(0);liveStreamStatus$=new W(void 0);bufferLength$=new W(0);liveLatency$=new W(void 0);liveLoadBufferLength$=new W(0);livePositionFromPlayer$=new W(0);currentStallDuration$=new W(0);videoLastDataObtainedTimestamp$=new W(0);fetcherRecoverableError$=new vp;fetcherError$=new vp;updateDurationError$=new vp;liveStreamEndTimestamp=0;liveBuffer;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;forceEnded$=new vp;gapWatchdogActive=!1;gapWatchdogSubscription;stallWatchdogSubscription;livePauseWatchdogSubscription;liveWasInterrupted=!1;isOnDemand=!1;dashMaxTvVideoQuality;destroyController=new np;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(`DashProviderPlayer`),this.forceVideoCodec=e.forceVideoCodec,this.isOnDemand=e.isOnDemand,this.dashMaxTvVideoQuality=e.dashMaxTvVideoQuality,this.fetcher=new Dm({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam,handleExtendedNetworkErrorsSet:e.tuning.handleExtendedNetworkErrorsSet,useUrlCacheMechanism:this.tuning.useUrlCacheMechanism,measureNonSegmentRequests:e.tuning.throughputEstimator.measureNonSegmentRequests}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=bf.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}initManifest=ip(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initManifest`),this.element=e,this.manifestUrlString=O(t,n,2),this.state$.startTransitionTo(`manifest_ready`),this.manifest=yield this.updateManifest(),!this.tuning.audioOnly&&!this.manifest?.streams.video.length||this.tuning.audioOnly&&!this.manifest?.streams.audio.length?this.error$.next({id:`NoRepresentations`,category:U.PARSER,message:`No playable video representations`}):this.state$.setState(`manifest_ready`)}.bind(this));updateManifest=ip(this.destroyController.signal,async function*(){this.tracer.log(`updateManifestStart`,{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(e=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:`LoadManifest`,category:U.NETWORK,message:`Failed to load manifest`,thrown:e})});if(!e)return null;let t=null;try{t=Nl(e??``,this.manifestUrlString),this.manifestReceived$.next()}catch(t){let n=Cc(e)??{id:`ManifestParsing`,category:U.PARSER,message:`Failed to parse MPD manifest`,thrown:t};this.error$.next(n)}if(!t)return null;let n=(e,t,n)=>!!(this.element?.canPlayType?.(t)&&Fe()?.isTypeSupported?.(`${t}; codecs="${n}"`)||e===`text`);if(t.live){this.isLive$.next(!0);let{availabilityStartTime:e,latestSegmentPublishTime:n,streamIsUnpublished:r,streamIsAlive:i}=t.live,a=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*a),this.liveDuration$.next((n-e)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let o=`active`;if(i||(o=r?`unpublished`:`unexpectedly_down`),this.liveStreamStatus$.next(o),i&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(e).catch(e=>{this.error$.next({id:`updateManifest`,category:U.VIDEO_PIPELINE,message:`seekLive after stream restore failed`,thrown:e})})}}let r={text:t.streams.text,video:[],audio:[]},i,a;for(let e of[`video`,`audio`]){let o=t.streams[e],s=this.tuning.dash.checkRepresentationCanPlayType&&this.element?Ud(o,this.element,this.tuning.dash.checkRepresentationCanPlayType):o.filter(({mime:t,codecs:r})=>n(e,t,r));r[e]=s;let c,l;if(this.tuning.dash.codecsPrioritizeEnabled){if(e===`audio`)a=ca(s.map(({codecs:e})=>e)),c=a[0],c&&(r[e]=s.filter(({codecs:e})=>la(e)===c));else if(e===`video`){i=oa(s,{preferHdr:this.tuning.preferHDR});let t=this.forceVideoCodec;l=(t?i.find(e=>e.name===t.name&&e.hdr===t.hdr):void 0)??i[0],l&&(r[e]=s.filter(e=>la(e.codecs)===l.name&&!!e.hdr===l.hdr))}}else{let t=aa(new Set(s.map(({codecs:e})=>e)));t&&(r[e]=s.filter(({codecs:e})=>e.startsWith(t)))}if(e===`video`){if(!this.tuning.dash.codecsPrioritizeEnabled){let e=this.tuning.preferHDR,t=r.video.some(e=>e.hdr),n=r.video.some(e=>!e.hdr);A.display.isHDR&&e&&t?r.video=r.video.filter(e=>e.hdr):n&&(r.video=r.video.filter(e=>!e.hdr))}let{videoStreamRepresentaionsFilter:e}=this.tuning.dash;if(e.length&&fa(r,e),this.dashMaxTvVideoQuality&&Vd(r,this.dashMaxTvVideoQuality),this.isOnDemand&&this.tuning.dash.filterOnDemandQualityList)for(let e of r.video)e.representations=e.representations.sort((e,t)=>t.height-e.height).filter((e,t)=>t%2==0)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:i,audio:a}),this.tracer.log(`updateManifestEnd`,lp(o)),o}.bind(this));setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ap(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`?0:_p()-this.liveStreamEndTimestamp,n=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(n===0),this.manifestUrlString=O(this.manifestUrlString,n,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)}initRepresentations=ip(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initRepresentationsStart`,lp({initialVideo:e,initialAudio:t,sourceHls:n})),ap(this.manifest),ap(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(`representations_ready`);let r=e=>{this.representationSubscription.add(up(e,`error`).pipe(sp(e=>!!this.element?.played.length)).subscribe(e=>{this.error$.next({id:`VideoSource`,category:U.VIDEO_PIPELINE,message:`Unexpected video source error`,thrown:e})}))};this.source=Re();let i=document.createElement(`source`);if(r(i),i.src=URL.createObjectURL(this.source),this.element.appendChild(i),Ie())if(n){let e=document.createElement(`source`);r(e),e.type=`application/x-mpegurl`,e.src=n.url,this.element.appendChild(e)}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};if(this.bufferManagers=[],pp(e)){let e=this.manifest.streams.video.reduce((e,t)=>[...e,...t.representations],[]);e.length&&(this.videoBufferManager=new Kp(`video`,this.source,e,a),this.bufferManagers.push(this.videoBufferManager))}if(pp(t)){let e=this.manifest.streams.audio.reduce((e,t)=>[...e,...t.representations],[]);this.audioBufferManager=new Kp(`audio`,this.source,e,a),this.bufferManagers.push(this.audioBufferManager)}if(Am.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Am(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(gp(...Mm.map(e=>up(this.element,e))).pipe(hp(e=>this.element?kd(this.element.buffered,this.element.currentTime*1e3):0),cp(),xp(e=>{e>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(gp(up(this.element,`ended`),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(cp()).subscribe(e=>this.liveStreamEndTimestamp=_p())),this.subscription.add(up(this.element,`pause`).subscribe(()=>{let{liveUpdateInterval:e}=this.tuning.dash;this.livePauseWatchdogSubscription=fp(e).subscribe(t=>{let n=me(this.manifestUrlString,2);this.manifestUrlString=O(this.manifestUrlString,n+e,2),this.liveStreamStatus$.getValue()===`active`&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(up(this.element,`play`).subscribe(e=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(op({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hp(({isActiveLive:e,isLowLatency:t})=>e&&t),cp()).subscribe(e=>{this.isManualDecreasePlaybackInLive()||Nf(this.element,1)})),this.representationSubscription.add(op({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(sp(({bufferLength:e,isActiveLive:t,isLowLatency:n})=>t&&n&&!!e)).subscribe(({bufferLength:e})=>this.liveBuffer.next(e))),this.videoBufferManager&&(this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(e=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!e)return;let t=this.liveSeekableDuration$.getValue()-e/1e3;this.liveSeekableDuration$.next(Math.max(t,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+e/1e3)})),this.representationSubscription.add(op({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(sp(({isLive:e})=>e),cp((e,t)=>t.bufferLength<e.bufferLength),hp(({rtt:e,bufferLength:t,segmentServerLatency:n})=>{let r=me(this.manifestUrlString,2);return(e/2+t+n+r)/1e3})).subscribe(this.liveLatency$))),this.representationSubscription.add(op({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:e,isActiveLive:t,isLowLatency:n})=>{if(!n||!t)return;let r=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,i=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,a=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=e-r;if(this.isManualDecreasePlaybackInLive())return;let s=1;Math.abs(o)>i&&(s=1+Math.sign(o)*a),Nf(this.element,s)})),this.representationSubscription.add(this.bufferLength$.subscribe(e=>{let t=0;if(e){let e=(this.element?.currentTime??0)*1e3;t=Math.min(...this.bufferManagers.map(t=>t.getLiveSegmentsToLoadState(this.manifest)?.to??e))-e}this.liveLoadBufferLength$.getValue()!==t&&this.liveLoadBufferLength$.next(t)}));let e=0;this.representationSubscription.add(op({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Sp(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:t,bufferLength:n})=>{if(!this.element||this.isUpdatingLive)return;let r=this.element.playbackRate,i=me(this.manifestUrlString,2),a=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,o=Math.min(a,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*r),s=this.tuning.dashCmafLive.normalizedActualBufferOffset*r,c=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*r,l=isFinite(t)?t:n,u=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),d=a<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(d);let f=`none`;if(u?f=`active_low_latency`:this.isLowLatency$.getValue()&&d?(this.bufferManagers.forEach(e=>e.proceedLowLatencyLive()),f=`active_low_latency`):i!==0&&l<o?f=`live_forward_buffering`:l<o+c&&(f=`live_with_target_offset`),isFinite(t)&&(e=t>e?t:e),f===`live_forward_buffering`||f===`live_with_target_offset`){let n=e-(o+s),a=this.normalizeLiveOffset(Math.trunc(i+n/r)),c=Math.abs(a-i),l=0;!t||c<=this.tuning.dashCmafLive.offsetCalculationError?l=i:a>0&&c>this.tuning.dashCmafLive.offsetCalculationError&&(l=a),this.manifestUrlString=O(this.manifestUrlString,l,2)}(f===`live_with_target_offset`||f===`live_forward_buffering`)&&(e=0,await this.updateLive())},e=>{this.error$.next({id:`updateLive`,category:U.VIDEO_PIPELINE,thrown:e,message:`Failed to update live with subscription`})}))}let o=op({allBuffersFull:gp(...this.bufferManagers.map(e=>e.fullyBuffered$)).pipe(hp(()=>this.bufferManagers.every(e=>e.fullyBuffered$.getValue()))),someBufferEnded:gp(...this.bufferManagers.map(e=>e.onLastSegment$)).pipe(hp(()=>this.bufferManagers.some(e=>e.onLastSegment$.getValue())))}).pipe(cp(),hp(({allBuffersFull:e,someBufferEnded:t})=>e&&t),sp(e=>e));if(this.representationSubscription.add(gp(this.forceEnded$,o).subscribe(()=>{if(this.source&&this.source.readyState===`open`&&Array.from(this.source.sourceBuffers).every(e=>!e.updating))try{this.source?.endOfStream()}catch(e){this.error$.next({id:`EndOfStream`,category:U.VIDEO_PIPELINE,message:`Failed to end MediaSource stream`,thrown:e})}})),this.representationSubscription.add(gp(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),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.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!==`open`){let e=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(t=>{e&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState===`open`){t();return}this.error$.next({id:`OpenOfStream`,category:U.VIDEO_PIPELINE,message:`Failed to open MediaSource`,thrown: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})})}if(!this.isLive$.getValue()){let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(e=>e.representations).flatMap(e=>{let t=[];return e.duration&&t.push(e.duration),Yu(e.segmentReference)&&e.segmentReference.totalSegmentsDurationMs&&t.push(e.segmentReference.totalSegmentsDurationMs),t})];this.source.duration=Math.max(...e)/1e3}let s=[];this.videoBufferManager&&pp(e)&&s.push(this.videoBufferManager.startWith(e)),this.audioBufferManager&&pp(t)&&s.push(this.audioBufferManager.startWith(t)),yield Promise.all(s),this.state$.setState(`representations_ready`),this.tracer.log(`initRepresentationsEnd`)}.bind(this));initBuffer(){ap(this.element),this.state$.setState(`running`),this.subscription.add(gp(...jm.map(e=>up(this.element,e)),up(window,`online`)).subscribe(()=>this.tick(),e=>{this.error$.next({id:`DashVKPlayer`,category:U.WTF,message:`Internal logic error`,thrown:e})})),this.subscription.add(up(this.element,`progress`).subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(up(this.element,`waiting`).subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&rp(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:e}=this.tuning.dashCmafLive,{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:n,liveStallReinitInterval:r,stallWatchdogInterval:i}=this.tuning.dash,a=this.isLive$.getValue(),o=this.liveStreamStatus$.getValue()===`active`;if(!this.element||this.source?.readyState!==`open`)return;let s=this.currentStallDuration$.getValue();s+=i,this.currentStallDuration$.next(s);let c={timeInWaiting:s},l=_p(),u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let d=this.audioBufferManager?.lastDataObtainedTimestamp??0,f=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,m=this.videoBufferManager&&f<100&&l-u>n,h=this.audioBufferManager&&p<100&&l-d>n;if((!e||o)&&((m||h)&&s>n||s>=t))throw Error(`Stall timeout exceeded: ${s} ms`);if(a&&s%r===0){let t=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!o&&e?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(t),this.updateManifest()):this.seekLive(t).catch(e=>{this.error$.next({id:`stallIntervalCallback`,category:U.VIDEO_PIPELINE,message:`stallIntervalCallback failed`,thrown:e})}),c.liveLastOffset=t}else{let e=this.element.currentTime*1e3;this.videoBufferManager?.maintain(e),this.audioBufferManager?.maintain(e),c.position=e}this.tracer.log(`stallIntervalCallback`,lp(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=fp(this.tuning.dash.stallWatchdogInterval).subscribe(e,e=>{this.error$.next({id:`StallWatchdogCallback`,category:U.NETWORK,message:`Can't restore DASH after stall.`,thrown:e})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,n=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.alwaysAbortPreviousSwitch?r?.switchToWithPreviousAbort(t,n):this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,n):r?.switchTo(t,n):r?.switchToOld(t,n)}async seek(e,t){ap(this.element),this.tuning.audioOnly?ap(this.audioBufferManager):ap(this.videoBufferManager);let n;n=t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(this.videoBufferManager?.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(n),rp(this.element.buffered,n)||await Promise.all([this.videoBufferManager?.abort(),this.audioBufferManager?.abort()]),!mp(this.element)&&(this.videoBufferManager?.maintain(n),this.audioBufferManager?.maintain(n),this.element.currentTime=n/1e3,this.tracer.log(`seek`,lp({requestedPosition:e,forcePrecise:t,position:n})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){pp(this.element)&&pp(this.source)&&pp(e)&&this.source?.readyState===`ended`&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(e=>e.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`)}getForwardBufferRepresentations(e){return e===`video`?this.videoBufferManager?.getForwardBufferRepresentations():this.audioBufferManager?.getForwardBufferRepresentations()}getActiveVideoSegmentProgress(){return this.videoBufferManager?.getActiveSegmentProgress()}getMpdVideoSegmentDuration(){return this.videoBufferManager?.getMpdSegmentDuration()}setBufferTarget(e,t){this.videoBufferManager?.setTarget(e),this.audioBufferManager?.setTarget(t)}getVideoForwardBufferDuration(){return this.videoBufferManager?.getForwardBufferDuration()??0}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=dp(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}tick=()=>{if(!this.element||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=fp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),e=>{this.error$.next({id:`GapWatchdog`,category:U.WTF,message:`Error handling gaps`,thrown:e})}),this.subscription.add(this.gapWatchdogSubscription))};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(),n={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 i=this.element.currentTime*1e3,a=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let e of this.bufferManagers)for(let t of e.gaps)(r&&t.persistent||e.playingRepresentation$.getValue()===t.representation)&&t.from-o<=i&&t.to+o>i&&(this.element.duration*1e3-t.to<this.tuning.endGapTolerance?a.push(1/0):a.push(t.to));if(a.length){let e=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,e===1/0?this.forceEnded$.next():(this.element.currentTime=e/1e3,n={...n,gapEnds:a,jumpTo:e,resultCurrentTime:this.element.currentTime},this.tracer.log(`jumpGap`,lp(n)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}isAnyBufferUpdating(){return!this.source||this.source.readyState!==`open`?!1:Array.from(this.source.sourceBuffers).some(e=>e.updating)}updateSourceDurationFromSegments(){if(!this.source||this.source.readyState!==`open`||this.isLive$.getValue()||!this.tuning.useDurationFromSegments)return;let e=e=>{this.updateDurationError$.next({id:`updateDuration`,category:U.VIDEO_PIPELINE,message:"Duration can`t be updated",thrown:e})};try{if(!this.isAnyBufferUpdating()){this.source.duration=this.calculateDurationFromSegments()/1e3;return}}catch(t){e(t);return}let t=new yp;t.add(gp(...this.bufferManagers.map(e=>e.updateEnd$)).subscribe(()=>{if(!this.isAnyBufferUpdating()){t.unsubscribe();try{this.source&&(this.source.duration=this.calculateDurationFromSegments()/1e3)}catch(t){e(t)}}}))}}class Pm{scene3D;subscription=new $f;volumeSubscription=new $f;videoState=new Dt(`stopped`);allocation;observableVideo=null;player;params;tracer;textTracksManager=null;droppedFramesManager=new qi;stallsManager=new _o;elementSizeManager=new wo;abrManager=new mc;failedVideoTrack;videoTracksMap=new Map;audioTracksMap=new Map;textTracksMap=new Map;videoStreamsMap=new Map;audioStreamsMap=new Map;videoTrackSwitchHistory=new Or;audioTrackSwitchHistory=new Or;constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn(e.source.url)),this.params=e,this.allocation=va(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(`dashProvider`),this.params.output.element$.next(this.allocation.video??void 0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Wr(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 Nm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec,isOnDemand:this.params.isOnDemand||!1,dashMaxTvVideoQuality:this.params.dashMaxTvVideoQuality}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Jf(this.observableVideo)&&(this.observableVideo=Qn(this.allocation.target),this.subscription.add(()=>this.observableVideo?.destroy()));let n=this.constructor.name,r=t=>{e.error$.next({id:n,category:Uf.WTF,message:`${n} internal logic error`,thrown:t})};return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:(e,t)=>this.subscription.add(e.subscribe(t,r))}}subscribe(){let{output:e,desiredState:t,observableVideo:n,genericErrorListener:r,connect:i}=this.getProviderSubscriptionInfo();qf(this.params.failedVideoTrack)&&(this.failedVideoTrack=this.params.failedVideoTrack,this.subscription.add(tp(this.params.tuning.dash.videoTrackBanAfterProviderFail).subscribe(()=>this.failedVideoTrack=null)));let a=this.allocation.video;a&&this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wf(e=>!!e.length),Qf()).subscribe(e=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:a,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e})}));let o=this.params.desiredState.seekState.stateChangeEnded$.pipe(Yf(e=>e.to.state!==`none`),Gf());this.abrManager.init({isSeeked$:o,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,throughputVariance$:this.params.dependencies.throughputEstimator.throughputVariance$,tuning:this.params.tuning,failedVideoTrack:this.params.failedVideoTrack,element:this.allocation.target,panelSize:this.params.panelSize,abrLogger:this.params.dependencies.abrLogger}),this.stallsManager.init({isSeeked$:o,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$:n.isBuffering$,looped$:n.looped$,playing$:n.playing$,duration:this.allocation.target.duration}),i(n.ended$,e.endedEvent$),i(n.looped$,e.loopedEvent$),i(n.error$,e.error$),i(n.isBuffering$,e.isBuffering$),i(n.currentBuffer$,e.currentBuffer$),i(n.currentBuffer$,e.currentNativeBuffer$),i(n.totalBufferDuration$,e.totalBufferDuration$),i(n.bufferRangeCount$,e.bufferRangeCount$),i(n.playing$,e.firstFrameEvent$),i(n.canplay$,e.canplay$),i(n.playedTime$,e.playedTime$),i(n.inPiP$,e.inPiP$),i(n.inFullscreen$,e.inFullscreen$),i(n.loadedMetadata$,e.loadedMetadataEvent$),i(this.player.error$,e.error$),i(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),i(this.player.updateDurationError$,e.updateDurationError$),i(this.player.fetcherError$,e.fetcherError$),i(this.player.videoLastDataObtainedTimestamp$,e.videoLastDataObtainedTimestamp$),i(this.player.manifestRequested$,e.manifestRequested$),i(this.player.firstBytesManifest$,e.firstBytesManifest$),i(this.player.manifestReceived$,e.manifestReceived$),i(this.player.firstBytesRequested$,e.firstBytesRequested$),i(this.player.firstBytesReceived$,e.firstBytesReceived$),i(this.player.lastConnectionType$,e.httpConnectionType$),i(this.player.lastConnectionReused$,e.httpConnectionReused$),i(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),i(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),i(this.player.isLive$,e.isLive$),i(this.player.lastRequestFirstBytes$.pipe(Wf(qf),Qf()),e.firstBytesEvent$),i(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),i(this.videoState.stateChangeEnded$.pipe(Yf(e=>e.to)),this.params.output.playbackState$),this.subscription.add(n.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wn(this.allocation.target,t.isLooped,r)),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),r)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,r))})),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:n}),this.subscription.add(Tn(this.allocation.target,t.volume,n.volumeState$,r,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(En(this.allocation.target,t.playbackRate,n.playbackRateState$,r)),this.allocation.video&&this.elementSizeManager.connect({video:this.allocation.video,observableVideo:n}),i(Qi(this.allocation.target,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(n.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`),this.scene3D&&this.scene3D.play()},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},r)).add(n.canplay$.subscribe(()=>{this.videoState.getState()===`playing`&&!this.allocation.target.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(n.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:e})=>{if(e===`manifest_ready`){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let e=this.player.getStreams(),t=this.player.getCodecs();if(Bf(e,`Manifest not loaded or empty`),!this.params.tuning.isAudioDisabled){let t=[];for(let n of e.audio){t.push(Ku(n));let e=[];for(let t of n.representations){let r=Uu(t);e.push(r),this.audioTracksMap.set(r,{stream:n,representation:t})}this.audioStreamsMap.set(n,e)}this.params.output.availableAudioStreams$.next(t)}let n=[];for(let t of e.video){n.push(qu(t));let e=[];for(let n of t.representations){let r=Hu({...n,streamId:t.id});r&&(e.push(r),this.videoTracksMap.set(r,{stream:t,representation:n}))}this.videoStreamsMap.set(t,e)}this.params.output.availableVideoStreams$.next(n);for(let t of e.text)for(let e of t.representations){let n=Wu(t,e);this.textTracksMap.set(n,{stream:t,representation:e})}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),t?.video&&this.params.output.availableVideoCodecs$.next(t.video),t?.audio&&this.params.output.availableAudioCodecs$.next(t.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else e===`representations_ready`&&(this.videoState.setState(`ready`),this.player.initBuffer())},r));let s=Xf(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$,Kf(this.allocation.target,`progress`)).pipe(Wf(()=>this.videoTracksMap.size>0||this.params.tuning.audioOnly&&this.audioTracksMap.size>0)),{abrThrottle:c}=this.params.tuning.dash;c&&(s=s.pipe(ep(c))),this.subscription.add(s.subscribe(async()=>{let e=this.player.state$.getState(),n=this.player.state$.getTransition();if(e!==`manifest_ready`&&e!==`running`||n)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let r=this.selectVideoAudioRepresentations();if(!r){if(this.params.tuning.audioOnly&&this.audioStreamsMap.size){let[,[t]]=this.audioStreamsMap.entries().next().value;e===`manifest_ready`&&await this.player.initRepresentations(void 0,t.id,this.params.sourceHls)}return}let[i,a]=r,o=[...this.videoTracksMap.keys()].find(e=>this.videoTracksMap.get(e)?.representation.id===i.id);qf(o)&&(this.stallsManager.lastVideoTrackSelected=o);let s=this.params.desiredState.autoVideoTrackLimits.getTransition();if(s&&this.params.output.autoVideoTrackLimits$.next(s.to),e===`manifest_ready`)await this.player.initRepresentations(i.id,a?.id,this.params.sourceHls);else if(await this.player.switchRepresentation(`video`,i.id),a){let e=!!t.audioStream.getTransition();await this.player.switchRepresentation(`audio`,a.id,e)}},r)),this.subscription.add(Vf({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Xf(Zf([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Yf(e=>e.to)))}).pipe(Yf(({videoState:e,autoVideoTrackState:t})=>e.to!==`stopped`&&t),Gf()).subscribe(e=>this.player.setSmartRepresentationSwitch(e))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:e})=>{this.scene3D&&e&&this.scene3D.pointCameraTo(e.x,e.y)})),this.subscription.add(this.elementSizeManager.subscribe(e=>{this.scene3D&&e&&this.scene3D.setViewportSize(e.width,e.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Gf()).subscribe(t=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.videoStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.videoStream.setState(a.to),e.currentVideoTrack$.next(r),e.currentVideoStream$.next(qu(i)),this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Gf()).subscribe(t=>{let n=[...this.audioTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentAudioStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.audioStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.audioStream.setState(a.to),e.currentAudioStream$.next(Ku(i)),this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(t=>{if(t?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(t),e.is3DVideo$.next(!0)}catch(t){e.warning$.next({id:`DashProvider`,message:`DashProvider could not initialize 3D-scene: ${t}`})}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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Yf(({to:e})=>e===`ready`),Gf()),u=[l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Zf([`init`])];this.params.tuning.dash.useDynamicBufferTarget&&u.push(this.params.dependencies.throughputEstimator.throughput$,e.currentVideoTrack$,n.currentBuffer$),this.subscription.add(Xf(...u).subscribe(()=>this.syncBufferTarget())),this.subscription.add(Xf(l,this.player.state$.stateChangeEnded$,Zf([`init`])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===`ready`)));let d=Xf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Zf([`init`])).pipe(Hf(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}syncBufferTarget(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.playbackState.getState()===`ready`,n=this.resolveBufferTargetMs(e,t);this.player.setBufferTarget(n,this.resolveAudioBufferTargetMs(e,t))}resolveAudioBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?Math.min(this.player.getVideoForwardBufferDuration()+n.audioBufferAheadOfVideoMs,n.forwardBufferTargetAuto):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}resolveBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?yc({throughputKbps:this.params.dependencies.throughputEstimator.throughput$.getValue(),currentBitrateKbps:this.getCurrentVideoBitrateKbps(),baseTargetMs:n.forwardBufferTargetAuto},n.dynamicBufferTarget):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}getCurrentVideoBitrateKbps(){let e=this.params.output.currentVideoTrack$.getValue();if(Jf(e))return null;let t=this.player.getForwardBufferRepresentations(`video`)?.get(e.id),n=Go(t);return isFinite(n)?n:e.bitrate}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pr:Nr,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Hr,n=this.params.tuning.useNewAutoSelectVideoTrack?Br:Vr,{desiredState:r,output:i}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:e})=>e===o),c=i.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:e})=>e===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let f=kd(this.allocation.target.buffered,this.allocation.target.currentTime*1e3),p;p=this.player.isActiveLive$.getValue()?this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.allocation.target.duration*1e3||1/0)-this.allocation.target.currentTime*1e3,h=Math.min(f/Math.min(p,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),_=[...this.audioStreamsMap.keys()].find(({id:e})=>e===g?.id)??this.audioStreamsMap.keys().next().value,v=0;if(_){if(s&&!a){let t=e(s,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}if(c){let t=e(c,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}}let y=this.player.isLive$.getValue(),b=this.allocation.target.duration*1e3,x=!y&&Number.isFinite(b)&&b>0?Math.max(0,b-this.allocation.target.currentTime*1e3):void 0,S=this.params.tuning.dash.useAbrPhases?{isLive:y,remainingDurationMs:x,mpdSegmentDurationMs:this.player.getMpdVideoSegmentDuration()}:{};this.abrManager.updateContext({isAuto:a,videoTracks:d,audioTracks:_?this.audioStreamsMap.get(_)??[]:[],currentVideoTrack:c,desiredVideoTrack:s,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:h,forwardBufferDuration:f,forwardBufferTarget:p,forwardVideoBufferRepresentations:this.player.getForwardBufferRepresentations(`video`),forwardAudioBufferRepresentations:this.player.getForwardBufferRepresentations(`audio`),videoSegmentLoadProgress:this.player.getActiveVideoSegmentProgress(),...S});let C=s,w;this.params.tuning.dash.useNewAbr?(C=this.abrManager.autoSelectTrack(`video`),w=_&&this.abrManager.autoSelectTrack(`audio`)):((a||!C)&&(C=n(d,{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:v,forwardBufferHealth:h,current:c,failedVideoTrack:this.failedVideoTrack,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger})),w=_&&t(C,d,this.audioStreamsMap.get(_)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,abrLogger:this.params.dependencies.abrLogger}));let T=this.videoTracksMap.get(C)?.representation,E=w&&this.audioTracksMap.get(w)?.representation;if(T&&E)return[T,E];if(T&&!E&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.allocation.target,this.params.source.url,e)}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===`requested`&&n?.to!==`paused`&&e!==`stopped`&&t!==`stopped`&&this.seek(r.position,r.forcePrecise),t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.player.stop(),this.allocation.target.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`),k(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`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`);return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):t===`playing`&&this.allocation.target.paused?this.playIfAllowed():n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return zf(e)}}};init3DScene=e=>{if(this.scene3D)return;let t=this.params.container,n=this.allocation.video;if(!t||!n)return;this.scene3D=new eo(t,n,{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 r=this.elementSizeManager.getValue();r&&this.scene3D.setViewportSize(r.width,r.height)};destroy3DScene=()=>{this.scene3D&&=(this.scene3D.destroy(),void 0)};playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:Uf.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Zf(e).subscribe(t,n)):e.then(t,n)}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.abrManager.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),on(this.allocation.target,this.params.tuning),this.tracer.end()}}class Fm extends Pm{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:n}=this.getProviderSubscriptionInfo();n(t.timeUpdate$,e.position$),n(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}import{combine as Im,merge as Lm,filter as Rm,filterChanged as zm,isNullable as Bm,map as Vm,ValueSubject as Hm,isNonNullable as Um}from"@vkontakte/videoplayer-shared";class Wm extends Pm{constructor(e){super(e),this.textTracksManager?.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:n,observableVideo:r,desiredState:i,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$,n.liveBufferTime$),a(this.player.liveSeekableDuration$,n.duration$),a(this.player.liveLatency$,n.liveLatency$);let o=new Hm(1);a(r.playbackRateState$,o),(this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab||this.params.tuning.live.catchupLiveForMutedInactiveTab)&&this.subscription.add(n.elementVisible$.pipe(zm()).subscribe(t=>{let r=n.position$.getValue(),i=n.volume$.getValue(),a=!i.volume||i.muted;!t&&!r&&a?e=!0:t&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(Vm(e=>e.to)).subscribe(this.player.isLowLatency$)).add(Im({liveBufferTime:n.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Vm(({liveBufferTime:e,liveAvailabilityStartTime:n})=>e&&n?e*1e3+n+t:void 0)).subscribe(n.liveTime$)).add(Im({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Lm(r.playbackRateState$,new Hm(1))}).pipe(Rm(({liveStreamStatus:e,liveDuration:t})=>e===`active`&&!!t)).subscribe(({liveDuration:e,playbackRate:r})=>{let i=n.liveBufferTime$.getValue(),a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;a||r<1-o||this.allocation.target.paused||Bm(i)||(t=e-i)})).add(Im({time:n.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Lm(r.playbackRateState$,new Hm(1))}).pipe(zm((e,t)=>this.player.liveStreamStatus$.getValue()===`active`?e.liveDuration===t.liveDuration:e.time===t.time)).subscribe(({time:e,liveDuration:r,playbackRate:i})=>{let a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;if(!a&&!this.allocation.target.paused&&i>=1-o||Bm(e)||Bm(r))return;let s=-1*(r-e-t);n.position$.next(Math.min(s,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(e=>{if(e){let t=Gu(e);this.params.output.availableTextTracks$.next([t])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Rm(e=>Um(e))).subscribe(e=>n.isLiveEnded$.next(e===`unpublished`&&n.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,n=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3)})}}import{fetchPolyfilled as Gm}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Km}from"@vkontakte/videoplayer-shared";var qm=`X-Playback-Duration`,Jm=async e=>{let t=await Km(e),n=await t.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(n)?.[1];return r?parseInt(r,10):t.headers.has(qm)?parseInt(t.headers.get(qm),10):void 0};import{assertNever as Ym,combine as Xm,debounce as Zm,ErrorCategory as Qm,filter as $m,filterChanged as eh,isNonNullable as th,isNullable as nh,map as rh,merge as ih,observableFrom as ah,Subscription as oh,ValueSubject as sh,VideoQuality as ch}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as lh}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as uh,getExponentialDelay as dh}from"@vkontakte/videoplayer-shared";var fh=e=>{let t=null;if(e.QUALITY&&(t=er(e.QUALITY)),!t&&e.RESOLUTION){let[n,r]=e.RESOLUTION.split(`x`).map(e=>parseInt(e,10));t=uh({width:n,height:r})}return t??null},ph=(e,t,n=!1)=>{let r=e.split(`
|
|
254
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,``);return new RegExp(t,`i`)}var jl=e=>{if(!e?.startsWith(`P`))return;let t=(e,t)=>{let n=e?parseFloat(e.replace(`,`,`.`)):NaN;return(isNaN(n)?0:n)*t},n=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(e),r=n?.[1]===`-`?-1:1,i={days:t(n?.[5],r),hours:t(n?.[6],r),minutes:t(n?.[7],r),seconds:t(n?.[8],r)};return i.days*24*60*60*1e3+i.hours*60*60*1e3+i.minutes*60*1e3+i.seconds*1e3},Ml=(e,t)=>{let n=e;n=n.replaceAll(`$$`,`$`);let r={RepresentationID:t.representationId,Number:t.segmentNumber,Bandwidth:t.bandwidth,Time:t.segmentTime};for(let[e,t]of Object.entries(r)){let r=RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,`g`);n=n.replaceAll(r,(e,n)=>Dl(t)?e:Dl(n)?t:t.padStart(parseInt(n,10),`0`))}return n},Nl=(e,t)=>{let n=new DOMParser().parseFromString(e,`application/xml`),r={video:[],audio:[],text:[]},i=n.children[0],a=Array.from(i.querySelectorAll(`MPD > BaseURL`).values()).map(e=>e.textContent?.trim()??``),o=a.at(0)??``,s=i.getAttribute(`type`)===`dynamic`,c=i.getAttribute(`availabilityStartTime`),l=i.getAttribute(`publishTime`),u=i.getElementsByTagName(`vk:Attrs`)[0],d=u?.getElementsByTagName(`vk:XLatestSegmentPublishTime`)[0].textContent,f=u?.getElementsByTagName(`vk:XStreamIsLive`)[0].textContent,p=u?.getElementsByTagName(`vk:XStreamIsUnpublished`)[0].textContent,m=u?.getElementsByTagName(`vk:XPlaybackDuration`)[0].textContent,h;s&&(h={availabilityStartTime:c?new Date(c).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:f===`yes`,streamIsUnpublished:p===`yes`});let g,_=i.getAttribute(`mediaPresentationDuration`),v=[...i.getElementsByTagName(`Period`)],y=v.reduce((e,t)=>({...e,[t.id]:t.children}),{}),b=v.reduce((e,t)=>({...e,[t.id]:t.getAttribute(`duration`)}),{});_?g=jl(_):Object.values(b).filter(e=>e).length&&!s?g=Object.values(b).reduce((e,t)=>e+(jl(t)??0),0):m&&(g=parseInt(m,10));let x=0,S=i.getAttribute(`profiles`)?.split(`,`)??[];for(let e of v.map(e=>e.id))for(let n of y[e]){let e=n.getAttribute(`id`)??`id`+(x++).toString(10),i=n.getAttribute(`mimeType`)??``,a=n.getAttribute(`codecs`)??``,s=n.getAttribute(`contentType`)??i?.split(`/`)[0],c=n.getAttribute(`profiles`)?.split(`,`)??[],l=kl(n.getAttribute(`lang`)??``)??{},u=n.querySelector(`Label`)?.textContent?.trim()??void 0,d=n.querySelectorAll(`Representation`),f=n.querySelector(`SegmentTemplate`),p=n.querySelector(`Role`)?.getAttribute(`value`)??void 0,m=n.querySelector(`AudioChannelConfiguration`)?.getAttribute(`value`),h=El(m)?parseInt(m,10):void 0,_=s,v={id:e,language:l.language,isDefault:p===`main`,label:u,codecs:a,hdr:_===`video`&&Tl(a),mime:i,channels:h,representations:[]};for(let e of d){let r=e.getAttribute(`lang`)??void 0,d=u??n.getAttribute(`label`)??e.getAttribute(`label`)??void 0,p=e.querySelector(`BaseURL`)?.textContent?.trim()??``,m=new URL(p||o,t).toString(),h=e.getAttribute(`mimeType`)??i,y=e.getAttribute(`codecs`)??a??``,b;if(s===`text`){let t=e.getAttribute(`id`)||``,n=l.privateuse?.includes(`x-auto`)||t.includes(`_auto`),r=e.querySelector(`SegmentTemplate`);if(r){let i={representationId:e.getAttribute(`id`)??void 0,bandwidth:e.getAttribute(`bandwidth`)??void 0},a=parseInt(e.getAttribute(`bandwidth`)??``,10)/1e3,o=parseInt(r.getAttribute(`startNumber`)??``,10)??1,s=parseInt(r.getAttribute(`timescale`)??``,10),c=r.querySelectorAll(`SegmentTimeline S`)??[],l=r.getAttribute(`media`);if(!l)continue;let u=[],d=0,f=``,p=0,h=o,_=0;for(let e of c){let t=parseInt(e.getAttribute(`d`)??``,10),n=parseInt(e.getAttribute(`r`)??``,10)||0,r=parseInt(e.getAttribute(`t`)??``,10);_=Number.isFinite(r)?r:_;let a=t/s*1e3,o=_/s*1e3;for(let e=0;e<n+1;e++){let n=Ml(l,{...i,segmentNumber:h.toString(10),segmentTime:(_+e*t).toString(10)}),r=(o??0)+e*a,s=r+a;h++,u.push({time:{from:r,to:s},url:n})}_+=(n+1)*t,d+=(n+1)*a}p=_/s*1e3,f=Ml(l,{...i,segmentNumber:h.toString(10),segmentTime:_.toString(10)}),b={id:t,kind:`text`,segmentReference:{type:`template`,baseUrl:m,segmentTemplateUrl:l,initUrl:``,totalSegmentsDurationMs:d,segments:u,nextSegmentBeyondManifest:{time:{from:p,to:1/0},url:f},timescale:s},profiles:[],duration:g,bitrate:a,mime:``,codecs:``,width:0,height:0,isAuto:n}}else b={id:t,isAuto:n,kind:`text`,url:m}}else{let t=e.getAttribute(`contentType`)??h?.split(`/`)[0]??s,r=n.getAttribute(`profiles`)?.split(`,`)??[],i=parseInt(e.getAttribute(`width`)??``,10),a=parseInt(e.getAttribute(`height`)??``,10),o=parseInt(e.getAttribute(`bandwidth`)??``,10)/1e3,l=e.getAttribute(`frameRate`)??``,u=e.getAttribute(`quality`)??void 0,d=l?Ol(l):void 0,p=`${e.getAttribute(`id`)??`id`+(x++).toString(10)}@${t===`video`?`${a}p`:t===`audio`?`${o}Kbps`:y}`,v=[...S,...c,...r],C,w=e.querySelector(`SegmentBase`),T=e.querySelector(`SegmentTemplate`)??f;if(w){let[t,n]=(e.querySelector(`SegmentBase Initialization`)?.getAttribute(`range`)??``).split(`-`).map(e=>parseInt(e,10)),r={from:t,to:n},i=e.querySelector(`SegmentBase`)?.getAttribute(`indexRange`),[a,o]=i?i.split(`-`).map(e=>parseInt(e,10)):[];C={type:`byteRange`,url:m,initRange:r,indexRange:i?{from:a,to:o}:void 0}}else if(T){let t={representationId:e.getAttribute(`id`)??void 0,bandwidth:e.getAttribute(`bandwidth`)??void 0},n=parseInt(T.getAttribute(`timescale`)??``,10),r=T.getAttribute(`initialization`)??``,i=T.getAttribute(`media`),a=parseInt(T.getAttribute(`startNumber`)??``,10)??1,o=Ml(r,t);if(!i)throw ReferenceError(`No media attribute in SegmentTemplate`);let s=T.querySelectorAll(`SegmentTimeline S`)??[],c=[],l=0,u=``,d=0;if(s.length){let e=a,r=0;for(let a of s){let o=parseInt(a.getAttribute(`d`)??``,10),s=parseInt(a.getAttribute(`r`)??``,10)||0,u=parseInt(a.getAttribute(`t`)??``,10);r=Number.isFinite(u)?u:r;let d=o/n*1e3,f=r/n*1e3;for(let n=0;n<s+1;n++){let a=Ml(i,{...t,segmentNumber:e.toString(10),segmentTime:(r+n*o).toString(10)}),s=(f??0)+n*d,l=s+d;e++,c.push({time:{from:s,to:l},url:a})}r+=(s+1)*o,l+=(s+1)*d}d=r/n*1e3,u=Ml(i,{...t,segmentNumber:e.toString(10),segmentTime:r.toString(10)})}else if(El(g)){let e=parseInt(T.getAttribute(`duration`)??``,10)/n*1e3,r=Math.ceil(g/e),a=0;for(let n=1;n<r;n++){let r=Ml(i,{...t,segmentNumber:n.toString(10),segmentTime:a.toString(10)});c.push({time:{from:a,to:a+e},url:r}),a+=e}d=a,u=Ml(i,{...t,segmentNumber:r.toString(10),segmentTime:a.toString(10)})}C={type:`template`,baseUrl:m,segmentTemplateUrl:i,initUrl:o,totalSegmentsDurationMs:l,segments:c,nextSegmentBeyondManifest:{time:{from:d,to:1/0},url:u},timescale:n}}else throw ReferenceError(`Unknown MPD segment referencing type`);if(!t||!h)continue;let E={video:`video`,audio:`audio`,text:`text`}[t];if(!E)continue;_||=E,b={id:p,kind:E,segmentReference:C,profiles:v,duration:g,bitrate:o,mime:h,codecs:y,width:i,height:a,fps:d,quality:u}}v.language||=r,v.label||=d,v.mime||=h,v.codecs||=y,v.hdr||=_===`video`&&Tl(y),v.representations.push(b)}if(_){let e=r[_].find(e=>e.id===v.id);if(e&&v.representations.every(e=>e.segmentReference.type===`template`))for(let t of e.representations){let e=v.representations.find(e=>e.id===t.id);if(!e)continue;let n=e.segmentReference,r=t.segmentReference;r.segments.push(...n.segments),r.nextSegmentBeyondManifest=n.nextSegmentBeyondManifest}else r[_].push(v)}}return{duration:g,streams:r,baseUrls:a,live:h}};import{AbortControllerPolyfilled as Pl}from"@vkontakte/videoplayer-shared";import{requestIdleCallbackPolyfilled as Fl}from"@vkontakte/videoplayer-shared";import{abortable as Il,assertNonNullable as Ll,ErrorCategory as Rl,flattenObject as z,fromEvent as zl,getExponentialDelay as Bl,getWindow as Vl,isAbortError as Hl,isHigher as Ul,isNonNullable as B,isNullable as V,once as Wl,Subject as Gl,Subscription as Kl,ValueSubject as ql}from"@vkontakte/videoplayer-shared";var Jl=e=>e.valid;class H{source;boxParser;type;size;content;valid;children;cursor=0;get id(){return this.type}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];let n=this.readUint32();this.type=this.readString(4),n===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,i;n===0||n===1?(this.size=void 0,this.valid=!1,i=void 0):n>e.byteLength?(this.size=n,this.valid=!1,i=Math.min(n-this.cursor,e.byteLength-this.cursor)):(this.size=n,this.valid=!0,i=n-this.cursor),this.content=new DataView(e.buffer,r,i)}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t=`ascii`){let n=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,n}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}}class Yl extends H{}import{assertNever as Xl}from"@vkontakte/videoplayer-shared";class Zl extends H{userData;constructor(e,t){if(super(e,t),!this.valid)return;let n=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(n,r)}parseData(e,t){switch(e){case`ondemandlivejson`:{let e=new TextDecoder(`ascii`).decode(t),n=JSON.parse(e);return{received:n[`t-in`],prepared:n[`t-out`]}}default:Xl(e)}}}class Ql extends H{majorBrand;minorVersion;compatibleBrands;constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let n=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let e=0;e<n.byteLength;e+=4){let e=this.readString(4);this.compatibleBrands.push(e)}}}class $l extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class eu extends H{version;flags;constructor(e,t){if(super(e,t),!this.valid)return;let n=this.readUint32();this.version=n>>>24,this.flags=n&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}}class tu extends eu{creationTime;modificationTime;timescale;duration;rate;volume;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())}}class nu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class ru extends H{data;constructor(e,t){super(e,t),this.data=this.content}}class iu extends eu{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;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 e=0;e<this.referenceCount;e++){let e=this.readUint32(),t=e>>>31,n=e<<1>>>1,r=this.readUint32();e=this.readUint32();let i=e>>>28,a=e<<3>>>3;this.segments.push({referenceType:t,referencedSize:n,subsegmentDuration:r,SAPType:i,SAPDeltaTime:a})}}}}class au extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class ou extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class su extends eu{stereoMode;constructor(e,t){if(super(e,t),this.valid){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}}}class cu extends eu{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}}class lu extends eu{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}}class uu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class du extends eu{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;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()}}class fu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class pu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class mu extends eu{sequenceNumber;constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}}class hu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class gu extends eu{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;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())}}class _u extends eu{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class vu extends eu{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let e=0;e<this.sampleCount;e++)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())}}class yu extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}}class bu extends eu{entryCount;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)))}}class xu extends H{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 Su={ftyp:Ql,moov:$l,mvhd:tu,moof:nu,mdat:ru,sidx:iu,trak:au,mdia:uu,mfhd:mu,tkhd:du,traf:hu,tfhd:gu,tfdt:_u,trun:vu,minf:fu,sv3d:ou,st3d:su,prhd:cu,proj:pu,equi:lu,uuid:Zl,stbl:yu,stsd:bu,avc1:xu,unknown:Yl};class Cu{options;constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],n=this.options.offset;for(;n<e.byteLength;){let r=new TextDecoder(`ascii`).decode(new DataView(e.buffer,e.byteOffset+n+4,4)),i;try{i=this.createBox(r,new DataView(e.buffer,e.byteOffset+n,e.byteLength-n))}catch(e){if(!(e instanceof RangeError))throw e}if(!i||!Jl(i))break;t.push(i),n+=i.size}return t}createBox(e,t){let n=Su[e];return n?new n(t,new Cu):new Yl(t,new Cu)}}class wu{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(e=>{Jl(e)&&(this.index[e.type]??=[],this.index[e.type].push(e),e.children.length>0&&this.indexBoxLevel(e.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}var Tu=new TextDecoder(`ascii`),Eu={validateData:e=>Tu.decode(new DataView(e.buffer,e.byteOffset+4,4))===`ftyp`,parseInit:e=>{let t={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},n=new wu(new Cu().parse(e));if(n.find(`sv3d`)){t.is3dVideo=!0;let e=n.find(`st3d`);e&&(t.stereoMode=e.stereoMode);let r=n.find(`prhd`);r&&(t.projectionData.pose.yaw=r.poseYawDegrees,t.projectionData.pose.pitch=r.posePitchDegrees,t.projectionData.pose.roll=r.poseRollDegrees);let i=n.find(`equi`);i&&(t.projectionData.bounds.top=i.projectionBoundsTop,t.projectionData.bounds.right=i.projectionBoundsRight,t.projectionData.bounds.bottom=i.projectionBoundsBottom,t.projectionData.bounds.left=i.projectionBoundsLeft)}return t},getIndexRange:()=>{},parseSegments:e=>{let t=new iu(e,new Cu),n=t.earliestPresentationTime/t.timescale*1e3,r=e.byteOffset+e.byteLength+t.firstOffset;return t.segments.map(e=>{if(e.referenceType!==0)throw Error(`Unsupported multilevel sidx`);let i=r,a=r+e.referencedSize-1,o=e.subsegmentDuration/t.timescale*1e3,s={status:`none`,time:{from:n,to:n+o},byte:{from:i,to:a},size:a-i+1};return n+=o,r+=e.referencedSize,s})},parseFeedableSegmentChunk:(e,t)=>{let n=new wu(new Cu().parse(e)),r=n.findAll(`moof`),i=t?n.findAll(`uuid`):n.findAll(`mdat`);if(!(i.length&&r.length))return null;let a=r[0],o=i[i.length-1],s=a.source.byteOffset,c=o.source.byteOffset-a.source.byteOffset+o.size;return new DataView(e.buffer,s,c)},getChunkEndTime:(e,t)=>{let n=new wu(new Cu().parse(e)).findAll(`traf`),r=n[n.length-1].children.find(e=>e.type===`tfhd`),i=n[n.length-1].children.find(e=>e.type===`tfdt`),a=n[n.length-1].children.find(e=>e.type===`trun`),o=0;return o=a.sampleDuration.length?a.sampleDuration.reduce((e,t)=>e+t,0):r.defaultSampleDuration*a.sampleCount,(Number(i.baseMediaDecodeTime)+o)/t*1e3},getServerLatencyTimestamps:e=>{let t=new wu(new Cu().parse(e)),n={},r=t.findAll(`uuid`).at(-1);return r?{serverDataReceivedTimestamp:r.userData.received,serverDataPreparedTime:r.userData.received}:n},getTimescaleFromIndex:e=>new wu(new Cu().parse(e)).find(`sidx`)?.timescale};import{assertNonNullable as Du,isNonNullable as Ou,isNullable as ku}from"@vkontakte/videoplayer-shared";import{assertNever as Au}from"@vkontakte/videoplayer-shared";var ju={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`}},Mu=e=>{let t=e.getUint8(0),n=0;t&128?n=1:t&64?n=2:t&32?n=3:t&16&&(n=4);let r=Nu(e,n),i=r in ju,a=i?ju[r].type:`binary`,o=e.getUint8(n),s=0;o&128?s=1:o&64?s=2:o&32?s=3:o&16?s=4:o&8?s=5:o&4?s=6:o&2?s=7:o&1&&(s=8);let c=new DataView(e.buffer,e.byteOffset+n+1,s-1),l=o&255>>s,u=Nu(c),d=l*2**((s-1)*8)+u,f=n+s,p;return p=f+d>e.byteLength?new DataView(e.buffer,e.byteOffset+f):new DataView(e.buffer,e.byteOffset+f,d),{tag:i?r:`0x`+r.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},Nu=(e,t=e.byteLength)=>{switch(t){case 1:return e.getUint8(0);case 2:return e.getUint16(0);case 3:return e.getUint8(0)*2**16+e.getUint16(1);case 4:return e.getUint32(0);case 5:return e.getUint8(0)*2**32+e.getUint32(1);case 6:return e.getUint16(0)*2**32+e.getUint32(2);case 7:{let t=e.getUint8(0)*2**48+e.getUint16(1)*2**32+e.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw ReferenceError(`Int64 is not supported`)}return 0},Pu=(e,t)=>{switch(t){case`int`:return e.getInt8(0);case`uint`:return Nu(e);case`float`:return e.byteLength===4?e.getFloat32(0):e.getFloat64(0);case`string`:return new TextDecoder(`ascii`).decode(e);case`utf8`:return new TextDecoder(`utf-8`).decode(e);case`date`:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case`master`:return e;case`binary`:return e;default:Au(t)}},Fu=(e,t)=>{let n=0;for(;n<e.byteLength;){let r=Mu(new DataView(e.buffer,e.byteOffset+n));if(!t(r))return;r.type===`master`&&Fu(r.value,t),n=r.value.byteOffset-e.byteOffset+r.valueSize}},Iu=e=>{if(e.getUint32(0)!==440786851)return!1;let t,n,r;return Fu(Mu(e).value,({tag:e,type:i,value:a})=>(e===17143?t=Pu(a,i):e===17026?n=Pu(a,i):e===17029&&(r=Pu(a,i)),!0)),(t===void 0||t<=1)&&n!==void 0&&n===`webm`&&(r===void 0||r<=2)},Lu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ru=[231,22612,22743,167,171,163,160,175],zu={validateData:Iu,parseInit:e=>{let t,n,r,i,a=!1,o=!1,s=!1,c,l,u=!1;return Fu(e,({tag:e,type:d,value:f,valueSize:p})=>(e===21419?l=Nu(Pu(f,d)):e!==21420&&(l=void 0),e===408125543?(t=f.byteOffset,n=f.byteOffset+p):e===357149030?a=!0:e===290298740?o=!0:e===2807729?r=Pu(f,d):e===17545?i=Pu(f,d):e===21420&&l===475249515?c=Pu(f,d):e===374648427?Fu(f,({tag:e,type:t,value:n})=>e===30321?(u=Pu(n,t)===1,!1):!0):a&&o&&Lu.includes(e)&&(s=!0),!s)),Du(t,`Failed to parse webm Segment start`),Du(n,`Failed to parse webm Segment end`),Du(i,`Failed to parse webm Segment duration`),r??=1e6,{segmentStart:Math.round(t/1e9*r*1e3),segmentEnd:Math.round(n/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:u,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},getIndexRange:e=>{if(ku(e.cuesSeekPosition))return;let t=e.segmentStart+e.cuesSeekPosition;return{from:t,to:t+1048576}},parseSegments:(e,t)=>{let n=!1,r=!1,i=e=>Ou(e.time)&&Ou(e.position),a=[],o;return Fu(e,({tag:e,type:t,value:s})=>{switch(e){case 475249515:n=!0;break;case 187:o&&i(o)&&a.push(o),o={};break;case 179:o&&(o.time=Pu(s,t));break;case 183:break;case 241:o&&(o.position=Pu(s,t));break;default:n&&Lu.includes(e)&&(r=!0)}return!(n&&r)}),o&&i(o)&&a.push(o),a.map((e,n)=>{let{time:r,position:i}=e,o=a[n+1],s=t.segmentStart+i,c=o?t.segmentStart+o.position-1:t.segmentEnd-1;return{status:`none`,time:{from:r,to:o?o.time:t.segmentDuration},byte:{from:s,to:c},size:c-s+1}})},parseFeedableSegmentChunk:e=>{let t=0,n=!1;try{Fu(e,r=>r.tag===524531317?r.tagSize<=e.byteLength?(t=r.tagSize,!1):(t+=r.tagHeaderSize,!0):Ru.includes(r.tag)?(t+r.tagSize<=e.byteLength&&(t+=r.tagSize,n||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return t>0&&t<=e.byteLength&&n?new DataView(e.buffer,e.byteOffset,t):null}},Bu=e=>{let t=/^(.+)\/([^;]+)(?:;.*)?$/.exec(e);if(t){let[,e,n]=t;if(e===`audio`||e===`video`)switch(n){case`webm`:return zu;case`mp4`:return Eu}}throw ReferenceError(`Unsupported mime type ${e}`)};import{videoSizeToQuality as Vu}from"@vkontakte/videoplayer-shared";var Hu=({id:e,width:t,height:n,bitrate:r,fps:i,quality:a,streamId:o,tvDisabled:s})=>{let c=(a?er(a):void 0)??Vu({width:t,height:n});return c&&{id:e,quality:c,bitrate:r,size:{width:t,height:n},fps:i,streamId:o,tvDisabled:s}},Uu=({id:e,bitrate:t})=>({id:e,bitrate:t}),Wu=({language:e,label:t},{id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Gu=({language:e,label:t,id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Ku=({id:e,language:t,label:n,codecs:r,isDefault:i,channels:a})=>({id:e,language:t,label:n,codec:r.split(`.`).at(0),isDefault:i,channels:a}),qu=({id:e,language:t,label:n,hdr:r,codecs:i})=>({id:e,language:t,hdr:r,label:n,codec:i.split(`.`).at(0)}),Ju=e=>`url`in e,Yu=e=>e.type===`template`;class Xu{error$=new Gl;playingRepresentation$=new ql(void 0);playingRepresentationInit$=new ql(void 0);currentSegmentLength$=new ql(0);onLastSegment$=new ql(!1);fullyBuffered$=new ql(!1);kind;nativeBufferManager;fetcher;tracer;tuning;representations;playingRepresentationId;downloadingRepresentationId;switchingRepresentationId;initData=new Map;initDataPromises=new Map;idleCallbacks=new Map;parsedInitData=new Map;forwardBufferRepresentations=new Map;segments=new Map;containerParser;bufferPlaybackQueue=[];downloadingBufferItems=[];preloadOnly=!1;forwardBufferTarget;failedDownloads=0;lastDataObtainedTimestampMs=0;loadByteRangeSegmentsTimeoutId=0;currentVirtualBufferSize=0;baseUrls=[];baseUrlsIndex=0;maintainPlaybackBufferMutex=!1;maintainNativeBufferMutex=!1;bufferClearingMutex=!1;abortNativeBufferMutex=!1;switchMutex=!1;seekMutex=!1;destroyAbortController=new Pl;switchAbortController=new Pl;downloadAbortController=new Pl;subscription=new Kl;getCurrentPosition;getCurrentStallDuration;constructor(e,t,n,{fetcher:r,tracer:i,tuning:a,getCurrentPosition:o,getCurrentStallDuration:s,manifest:c}){this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tracer=i.createComponentTracer(`${this.kind} virtualBuffer`),this.tuning=a,this.getCurrentPosition=o,this.getCurrentStallDuration=s,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=c?.baseUrls??[],this.representations=new Map(n.map(e=>[e.id,e]))}startWith=Il(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ll(t,`Cannot find representation ${e}`);let n=this.tracer.createComponentTracer(`startWith`);n.log(`start representation`,z({id:e})),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Bu(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),n.log(`started loadInitIfNeeded`),yield this.loadInitIfNeeded(t,`high`),n.log(`ended loadInitIfNeeded`);let r=this.initData.get(t.id),i=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Ll(r,`No init buffer for starting representation`),Ll(i,`No segments for starting representation`),n.log(`started native buffer init segment append`),yield this.nativeBufferManager.addInitSegment(r),n.log(`ended native buffer init segment append`),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a),n.end()}.bind(this));async switchTo(e,t=`default`){if(e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;let n=this.tracer.createComponentTracer(`switchTo ${t} ${this.getCurrentPosition()}`);return n.log(`abort previous switchTo`),this.switchAbortController.abort(),this.switchMutex=!1,n.log(`switchMutex released`),this.switchAbortController=new Pl,this.getSwitchWithAbort(n)(e,t)}getSwitchWithAbort(e){return Il(this.switchAbortController.signal,async function*(t,n){if(!V(this.downloadingRepresentationId)){this.switchMutex=!0,e.log(`switchMutex captured`);try{e.log(`start`,z({newRepresentationId:t,playingRepresentationId:this.playingRepresentationId,downloadingRepresentationId:this.downloadingRepresentationId,mode:n})),this.switchingRepresentationId=t;let r=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(t);Ll(i,`No such representation ${t}`),Ll(r,`No such representation ${this.downloadingRepresentationId}`),e.log(`abortDownload`),yield this.abortDownload(),e.log(`start loadInitIfNeeded`),yield this.loadInitIfNeeded(i,`high`),e.log(`ended loadInitIfNeeded`);let a=this.initData.get(i.id),o=this.segments.get(i.id);if(V(a)||V(o))return;let s=e=>e.segment.bufferStatus!==`fed`,c=e=>{let t=this.representations.get(e.representationId);return Ll(t,`No itemRepresentation for previous track before switch`),e.segment.networkStatus!==`downloaded`||this.forceSwitchCondition(t,i)},l=e=>{switch(n){case`lazy`:return s(e)&&c(e);case`force`:return!0;default:return s(e)}};e.log(`bufferPlaybackQueue before`,z(this.bufferPlaybackQueue)),this.bufferPlaybackQueue.filter(l).forEach(e=>e.segment.bufferStatus=`none`),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(e=>!l(e)),e.log(`bufferPlaybackQueue after`,z(this.bufferPlaybackQueue)),this.downloadingRepresentationId=t,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(e.log(`switchTo with maintain`),yield this.maintain()):(e.log(`switchTo with seek`),yield this.prepareSeek(),yield this.seek(this.getCurrentPosition()))}finally{this.switchMutex=!1,e.log(`switchMutex released`),e.end()}}}.bind(this))}async prepareSeek(){let e=this.tracer.createComponentTracer(`prepareSeek`);this.seekMutex=!0,e.log(`seekMutex captured`);try{e.log(`started abort`),await this.abort(),e.log(`started clearBuffer`),await this.clearBuffer(),e.log(`ended clearBuffer`)}catch{e.error(`seekMutex released`),this.seekMutex=!1}e.end()}async seek(e){let t=this.tracer.createComponentTracer(`seek ${e}`);this.seekMutex=!1,t.log(`seekMutex released`),t.log(`maintain started`),await this.maintain(e),t.log(`maintain ended`),t.end()}async maintain(e=this.getCurrentPosition()){V(e)||(await this.verifyBufferPlaybackQueue(e),await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardBufferRepresentations(e=this.getCurrentPosition()){if(this.forwardBufferRepresentations.clear(),B(e))for(let[t,n]of this.segments.entries())this.forwardBufferRepresentations.set(t,n.filter(t=>t.time.from>=e&&t.time.to<=e+this.forwardBufferTarget));return this.forwardBufferRepresentations}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(e=>e.segment.networkStatus===`downloaded`),n=t[t.length-1],r=B(e)&&B(n)?n.segment.time.to-e:0;return Math.max(r,0)}getPlaybackBufferState(){return this.bufferPlaybackQueue.length?{from:this.bufferPlaybackQueue[0].segment.time.from,to:this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to}:null}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??``;return(this.segments.get(t)?.find(t=>t.time.from<=e&&t.time.to>=e))?.time.from}getRepresentationInitialTime(){return V(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}getMutexInfo(){let e=``;return this.seekMutex&&(e+=`seek `),this.abortNativeBufferMutex&&(e+=`abort `),this.maintainNativeBufferMutex&&(e+=`maintainNative `),this.maintainPlaybackBufferMutex&&(e+=`maintainPlayback `),this.bufferClearingMutex&&(e+=`bufferClear `),this.switchMutex&&(e+=`switch `),e}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}getActiveSegmentProgress(){let e;for(let t of this.downloadingBufferItems)t.segment.networkStatus!==`downloading`||V(t.startedAtMs)||(!e||t.segment.time.from<e.segment.time.from)&&(e=t);if(!(!e||V(e.startedAtMs)))return{startedAtMs:e.startedAtMs,loadedBytes:e.segment.loadedBytes??0,totalBytes:B(e.segment.size)&&Number.isFinite(e.segment.size)?e.segment.size:void 0,segmentDurationMs:e.segment.time.to-e.segment.time.from}}getMpdSegmentDuration(){for(let e of this.segments.values()){let t=e[0];if(t&&t.time.to>t.time.from)return t.time.to-t.time.from}}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=Vl();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.cancelIdleCallback)for(let t of this.idleCallbacks.values())e.cancelIdleCallback(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId),this.tracer.log(`destroy`),this.tracer.end()}async verifyBufferPlaybackQueue(e){let t=this.getPlaybackBufferState();if(!this.tuning.dash.useBufferQueueVerification||!this.bufferPlaybackQueue.length||V(t)||this.withinInterval(e,t))return;let n=this.tracer.createComponentTracer(`verifyBufferPlaybackQueue `+e);this.tuning.dash.useVirtualBufferImplicitSeek?(n.log(`prepare seek `),await this.prepareSeek(),n.log(`seek `+e),await this.seek(e)):(n.log(`reset bufferPlaybackQueue`),this.bufferPlaybackQueue=[]),n.end()}forceSwitchCondition(e,t){let n=!0;if(this.kind===`video`){let r=Hu(e),i=Hu(t);n=B(r)&&B(i)&&Ul(i.quality,r.quality)}else if(this.kind===`audio`){let r=Uu(e),i=Uu(t);n=B(r?.bitrate)&&B(i?.bitrate)&&i.bitrate>r.bitrate}return n}async clearBuffer(){let e=this.tracer.createComponentTracer(`clearBuffer`);this.bufferClearingMutex=!0,e.log(`bufferClearingMutex captured`);try{e.log(`clearBuffer`,z({queue:this.bufferPlaybackQueue.slice(0,5)})),await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus=`none`),this.bufferPlaybackQueue=[]}finally{this.bufferClearingMutex=!1,e.log(`bufferClearingMutex released`),e.end()}}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new Pl,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus===`downloading`&&(e.segment.networkStatus=`none`,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null,e.startedAtMs=void 0);this.downloadingBufferItems=[]}async abortNativeBuffer(){let e=this.tracer.createComponentTracer(`abortNativeBuffer`);e.log(`abortNativeBufferMutex captured`),this.abortNativeBufferMutex=!0;try{e.log(`abortNativeBuffer`,z({bufferState:this.nativeBufferManager.getBufferState()}));let t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),n=t instanceof ArrayBuffer?t:void 0;return await this.nativeBufferManager.abortBuffer(n)}finally{this.abortNativeBufferMutex=!1,e.log(`abortNativeBufferMutex released`),this.tuning.dash.useAbortResetNativeBufferMutex&&(this.maintainNativeBufferMutex=!1),e.end()}}async loadInits(){for(let[e,t]of this.representations)this.idleCallbacks.set(t.id,Fl(async e=>await this.loadInitIfNeeded(t,`low`,!1)))}async loadInitIfNeeded(e,t=`auto`,n=!1){let r=this.initDataPromises.get(e.id),i;i=this.initData.has(e.id)&&this.segments.has(e.id)?Promise.resolve():B(r)?r:this.loadInit(e,t,n),await i}async loadInit(e,t=`auto`,n=!1){try{let n=this.tuning.dash.useFetchPriorityHints?t:`auto`,r=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,this.downloadAbortController.signal,n);this.initDataPromises.set(e.id,r);let{initMetadata:i,initDataView:a,segments:o}=await r??{};if(this.initDataPromises.delete(e.id),V(a)||V(o))return;i&&this.parsedInitData.set(e.id,i);let s=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e.id,s),this.segments.set(e.id,o),this.failedDownloads=0}catch(e){n&&!Hl(e)&&this.error$.next({id:`LoadInits`,category:Rl.WTF,message:`loadInit threw`,thrown:e})}}async maintainNativeBuffer(){let e=this.getCurrentPosition(),t=this.segments.get(this.downloadingRepresentationId??``),n=t?.[t?.length-1];if(V(e)||V(n)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.seekMutex||this.preloadOnly)return;let r;this.maintainNativeBufferMutex=!0;try{let t=this.bufferPlaybackQueue.find(t=>this.withinInterval(e,t.segment.time)),i=this.bufferPlaybackQueue.find(e=>e.segment.bufferStatus!==`fed`),a=this.initData.get(i?.representationId??``),o=this.bufferPlaybackQueue[0],s=this.destroyAbortController.signal,c=(this.getCurrentStallDuration()??0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&(c&&=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,n.time.to-e),u=c?this.getForwardPlaybackBufferDuration()>=l:!0;B(a)&&B(i)&&B(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus===`fed`)&&(r??=this.tracer.createComponentTracer(`native init ${e}`),r.log(`abortNativeBuffer`),await this.abortNativeBuffer(),r.log(`start addInitSegment`),await this.nativeBufferManager.addInitSegment(a,s),r.log(`end addInitSegment`),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId),r.log(`playingRepresentationId`,z({id:i.representationId}))),B(i)&&this.withinAppendInterval(e,i.segment.time)&&u&&(r??=this.tracer.createComponentTracer(`native append ${e}`),i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus===`none`?(r.log(`started appendSegmentFully`),await this.appendSegmentFully(i,s),r.log(`ended appendSegmentFully`)):(r.log(`started appendSegmentPartially`),await this.appendSegmentPartially(i,s),r.log(`ended appendSegmentPartially`))),B(o)&&B(t)&&this.withinRemoveInterval(e,o.segment.time)&&o.segment.time.to<t.segment.time.from+1&&(r??=this.tracer.createComponentTracer(`native remove ${e}`),r.log(`started removeSegment`),await this.removeSegment(o,s),r.log(`ended removeSegment`)),r?.log(`currentPosition`,z({currentPosition:e})),r?.log(`currentPlayingItem`,z(t)),r?.log(`nextPlayingItem`,z(i)),r?.log(`nextRemoveItem`,z(o)),r?.log(`queue`,z(this.bufferPlaybackQueue.slice(0,5))),r?.log(`buffer`,z(this.nativeBufferManager.getBufferState()??{})),this.pruneVirtualBuffer(e)}finally{this.maintainNativeBufferMutex=!1,r?.log(`maintainNativeBufferMutex released`),r?.end()}}async maintainPlaybackBuffer(e){Ll(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),n=this.representations.get(this.downloadingRepresentationId);if(V(t)||V(n)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.seekMutex)return;let r;this.maintainPlaybackBufferMutex=!0;try{let i=t.find(t=>e>=t.time.from&&e<t.time.to);B(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next(i?.time.to-i.time.from),this.downloadingBufferItems.length?r=this.tracer.createComponentTracer(`playbackMaintain ${e}`):this.downloadingBufferItems=this.selectDownloadingItems(e,t),r?.log(`maintainPlaybackBufferMutex captured`),r?.log(`currentSegment`,z(i)),r?.log(`downloadingBufferItems`,z(this.downloadingBufferItems)),r?.log(`processCachedItems`),await this.processCachedItems();let a=this.selectItemsToLoad();r?.log(`itemsToLoad`,z(a)),await this.loadItems(a,n),r?.log(`items downloaded`,z(a))}finally{this.maintainPlaybackBufferMutex=!1,r?.log(`maintainPlaybackBufferMutex released`),r?.end()}}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??``);if(V(t)||t.length===0)return;let n=t[t?.length-1];V(n)||(this.fullyBuffered$.next(n.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-n.time.from>0))}selectDownloadingItems(e,t){Ll(this.downloadingRepresentationId);let n=this.getPlaybackBufferState(),r,i;if(B(n)&&this.withinInterval(e,n)){i=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e);let n=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1];r=t.findIndex(e=>e.time.from>n.segment.time.from+this.tuning.dash.bufferTolerance)}else i=this.forwardBufferTarget,r=t.findIndex(t=>this.withinInterval(e,t.time));r=r===-1?0:r;let a=[];for(;r<t.length&&i>0;){a.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:e,to:n}=t[r].time;i-=n-e,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:n},r=this.tuning.dash.bufferTolerance,i=0){return B(e)?e+r>=t&&e-i<n:!1}withinAppendInterval(e,{from:t,to:n}){let{minNativeBufferSize:r,removeTimeShiftFromSegment:i}=this.tuning.dash;return this.withinInterval(e,{from:t,to:n},r,i)}withinRemoveInterval(e,{to:t}){let{removeTimeShiftFromSegment:n}=this.tuning.dash;return B(e)?e-n>t:!1}getExponentialDownloadDelay(){return Il(this.downloadAbortController.signal,async function*(){let e=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let n=Vl();this.loadByteRangeSegmentsTimeoutId=n.setTimeout(t,e),this.subscription.add(zl(n,`online`).pipe(Wl()).subscribe(()=>{t(),n.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this))}async waitExponentialDownloadDelay(){await this.getExponentialDownloadDelay()()}async appendSegmentFully(e,t){V(e.segment.data)||(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(V(e.segment.data)||V(e.segment.loadedBytes)||V(e.segment.feedingBytes)||V(e.segment.fedBytes)||V(e.segment.size))return;let n=e.segment.data,r=new DataView(n.buffer,n.byteOffset+e.segment.feedingBytes,n.byteLength-e.segment.feedingBytes),i=e.segment.loadedBytes===e.segment.size?r:this.parseFeedableSegmentChunk(r);i?.byteLength&&(e.segment.bufferStatus=`partially_fed`,e.segment.feedingBytes+=i.byteLength,await this.nativeBufferManager.append(i,t)&&(e.segment.fedBytes+=i.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:n,to:r}=e.segment.time,i=(r-n)/4;await this.nativeBufferManager.remove(0,r-i,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus=`none`,this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(t=>t===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(t=>t!==e||t.segment.networkStatus!==`downloaded`),(this.preloadOnly||B(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(t=>t===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:n,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let i,a=this.currentVirtualBufferSize-t+n;for(let t of this.segments.values())for(let n of t)B(n.size)&&a>0&&n.time.to<=e-r&&n.bufferStatus===`none`&&n.networkStatus===`downloaded`&&(i??=this.tracer.createComponentTracer(`prune before ${e}`),i.log(`bytesToPrune`,{bytesToPrune:a}),i.log(`prune segment`,z(n)),n.data=null,n.networkStatus=`none`,this.currentVirtualBufferSize-=n.size,a-=n.size);for(let t of this.segments.values())for(let n of[...t].reverse())B(n.size)&&a>0&&n.time.from>=e+r&&n.bufferStatus===`none`&&n.networkStatus===`downloaded`&&!this.bufferPlaybackQueue.find(e=>e.segment===n)&&!this.downloadingBufferItems.find(e=>e.segment===n)&&(i??=this.tracer.createComponentTracer(`prune after ${e}`),i.log(`bytesToPrune`,{bytesToPrune:a}),i.log(`prune segment`,z(n)),n.data=null,n.networkStatus=`none`,this.currentVirtualBufferSize-=n.size,a-=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 Zu,getWindow as Qu,isNonNullable as $u,isNullable as ed,now as td,isAbortError as nd}from"@vkontakte/videoplayer-shared";class rd extends Xu{constructor(e,t,n,r){super(e,t,n,r)}async loadItems(e,t,n=`auto`){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:i,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),r.aborted)return;let o=Qu().performance.now();for(let t of e)t.startedAtMs=o;try{await this.fetcher.fetch(i,{...a,priority:n,urlCacheMechanismEnabled:!0}),this.lastDataObtainedTimestampMs=td(),this.failedDownloads=0}catch(e){this.abortDownloadingItems(),nd(e)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,n=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,i=this.preloadOnly?this.forwardBufferTarget:0,a=0;for(;a<this.downloadingBufferItems.length&&this.downloadingBufferItems[a].segment.networkStatus===`none`&&(e<=r||t<=i);){let r=this.downloadingBufferItems[a],i=r.segment;i.networkStatus=`downloading`,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,n.push(r),e+=i.byte.to+1-i.byte.from,t+=i.time.to+1-i.time.from,a++}return n}prepareFetchParams(e,t){if(Ya(t.segmentReference))throw Error(`Representation is not byte range type`);let{signal:n}=this.downloadAbortController,r=t.segmentReference.url,i={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:i,onProgress:async(r,a)=>{if(!n.aborted)try{this.lastDataObtainedTimestampMs=td(),await this.onSomeDataLoaded({downloadingItems:e,dataView:r,loaded:a,signal:n,globalFrom:i?i.from:0,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:Zu.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}},signal:n,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:n,globalFrom:r,loaded:i,signal:a}){let o=this.representations.get(n);if(!(!this.downloadingBufferItems.length||ed(o)||ed(r)||a.aborted))for(let n of e){let{segment:e}=n,a=e.byte.from-r,o=e.byte.to-r,s=a<i,c=o<=i;!s||ed(e.size)||(e.networkStatus===`downloading`&&e.bufferStatus===`none`&&c?(e.data=new DataView(t.buffer,t.byteOffset+a,e.size),this.currentVirtualBufferSize+=e.size,this.onItemFullyDownloaded(n),e.loadedBytes=Math.min(e.size,i-a),await this.onDownloadItem(n)):$u(e.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&e.networkStatus===`downloading`&&(e.loadedBytes=Math.min(e.size,i-a),c&&(this.currentVirtualBufferSize+=e.size,this.onItemFullyDownloaded(n)),e.loadedBytes>e.feedingBytes&&(e.data=new DataView(t.buffer,t.byteOffset+a,e.loadedBytes),await this.onDownloadItem(n))))}}updateRepresentationBaseUrl(e,t){if(Ya(e.segmentReference))throw Error(`Representation is not byte range type`);e.segmentReference.url=t}}import{ErrorCategory as id,getWindow as ad,isAbortError as od,isNullable as sd,now as cd}from"@vkontakte/videoplayer-shared";class ld extends Xu{constructor(e,t,n,r){super(e,t,n,r)}async loadItems(e,t,n=`auto`){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:i,...a}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),r.aborted)return;let o=ad().performance.now();for(let t of e)t.startedAtMs=o;try{let t=await this.fetcher.fetch(i,{...a,priority:n});if(this.lastDataObtainedTimestampMs=cd(),sd(t))return;let r=e[0],o=new DataView(t);r.segment.size=o.byteLength,r.segment.loadedBytes=o.byteLength,r.segment.data=o,this.onItemFullyDownloaded(r),await this.onDownloadItem(r),this.failedDownloads=0}catch(e){this.abortDownloadingItems(),od(e)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let n=t.segment;n.networkStatus=`downloading`,n.size=1/0,n.loadedBytes=0,n.feedingBytes=0,n.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let n=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:n,onProgress:async(n,i)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=cd(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:i,signal:r,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:id.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ya(t.segmentReference))throw Error(`Representation is not template type`);return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:n,loaded:r,signal:i}){let a=e[0],{segment:o}=a,s=this.representations.get(n);!this.downloadingBufferItems.length||sd(s)||sd(o.feedingBytes)||o.networkStatus!==`downloading`||i.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(a)))}updateRepresentationBaseUrl(e,t){if(!Ya(e.segmentReference))throw Error(`Representation is not template type`);e.segmentReference.baseUrl=t}}import{assertNonNullable as ud,ErrorCategory as dd,isNullable as fd,ValueSubject as pd}from"@vkontakte/videoplayer-shared";class md extends ld{currentLiveSegmentServerLatency$=new pd(0);currentLowLatencySegmentLength$=new pd(0);liveInitialAdditionalOffset=0;isSeekingLive=!1;isActiveLowLatency;constructor(e,t,n,r){super(e,t,n,r),this.isActiveLowLatency=r.isActiveLowLatency}updateManifest(e){if(!e||[...this.segments.values()].every(e=>!e.length))return;let t=e.streams[this.kind].flatMap(e=>e.representations);for(let e of t){if(fd(e)||!Ya(e.segmentReference))return;let t=e.segmentReference.segments.map(e=>({...e,networkStatus:`none`,bufferStatus:`none`,size:void 0})),n=this.segments.get(e.id)??[],r=n.at(-1)?.time.to??0,i=t?.findIndex(e=>r>=e.time.from+100&&r<=e.time.to+100);if(i===-1){let t=this.getActualLiveStartingSegments(e.segmentReference);this.segments.set(e.id,t)}else{let r=t.slice(i+1);this.segments.set(e.id,[...n,...r])}this.representations.set(e.id,e)}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ud(e);let t=this.segments.get(e);if(t?.length){let n={representationId:e,segmentIndex:t.length-1,segment:t[t.length-1]};this.updateLowLatencyLive(n)}}getLiveSegmentsToLoadState(e){let t=(e?.streams[this.kind])?.flatMap(e=>e.representations).find(e=>e.id===this.downloadingRepresentationId);if(fd(t))return;let n=this.segments.get(t.id);if(n?.length)return{from:n[0].time.from,to:n[n.length-1].time.to}}getRepresentationInitialTime(){if(fd(this.playingRepresentationId))return 0;let e=this.representations.get(this.playingRepresentationId)?.segmentReference;return fd(e)||!Ya(e)?0:this.getActualLiveStartingSegments(e)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(e,t){return{...super.prepareFetchParams(e,t),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:e,...t}){await super.onSomeDataLoaded({downloadingItems:e,...t}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(e[0])}onItemFullyDownloaded(e){if(super.onItemFullyDownloaded(e),fd(e.segment.data)||!this.isActiveLowLatency())return;let t=e.segment.data,{serverDataReceivedTimestamp:n,serverDataPreparedTime:r}=this.containerParser.getServerLatencyTimestamps(t);n&&r&&this.currentLiveSegmentServerLatency$.next(r-n),this.updateLowLatencyItemTime(e),this.updateLowLatencyLive(e)}updateLowLatencyItemTime(e){let t=e.segment.data,n=this.representations.get(e.representationId)?.segmentReference;if(fd(e.segment.data)||fd(n)||!Ya(n))return;let r=this.containerParser;if(e.segment.isCurrentLowLatency){let{timescale:i}=n;e.segment.time.to=r.getChunkEndTime(t,i)}}updateLowLatencyLive(e){let t=0;for(let n of this.representations.values()){let r=n.segmentReference;if(!Ya(r))return;let i=this.segments.get(n.id)??[],a=i.find(t=>Math.floor(t.time.from)===Math.floor(e.segment.time.from));if(a?.isCurrentLowLatency&&(a.time.to=e.segment.time.to,t=a.time.to-a.time.from,a.isCurrentLowLatency=!1),!i.find(t=>Math.floor(t.time.from)===Math.floor(e.segment.time.to))&&this.isActiveLowLatency()){let t=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Ml(r.segmentTemplateUrl,{segmentTime:t});i.push({networkStatus:`none`,bufferStatus:`none`,time:{from:e.segment.time.to,to:e.segment.time.to+this.tuning.dash.bufferTolerance},url:n,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(t)}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!0)}getFetchUrl(e,t){let n=super.getFetchUrl(e,t);return this.isActiveLowLatency()&&n.searchParams.set(`low-latency`,`yes`),n}async loadInit(e,t=`auto`,n=!1){try{let n=this.tuning.dash.useFetchPriorityHints?t:`auto`,r=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,this.downloadAbortController.signal,n);this.initDataPromises.set(e.id,r);let{initMetadata:i,initDataView:a,segments:o}=await r??{};if(this.initDataPromises.delete(e.id),fd(a)||fd(o))return;i&&this.parsedInitData.set(e.id,i);let s=this.getActualLiveStartingSegments(e.segmentReference);this.segments.has(e.id)||this.segments.set(e.id,s);let c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e.id,c),this.failedDownloads=0}catch(e){n&&this.error$.next({id:`LoadInits`,category:dd.WTF,message:`loadInit threw`,thrown:e})}}getActualLiveStartingSegments(e){let t=e.segments,n=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],i=0,a=t.length-1;do r.unshift(t[a]),i+=t[a].time.to-t[a].time.from,a--;while(i<n&&a>=0);return this.liveInitialAdditionalOffset=i-n,this.isActiveLowLatency()?[r[0]]:r}}class hd{static getBufferManager(e,t,n,r){return r.manifest?.live?new md(e,t,n,r):Ya(n[0].segmentReference)?new ld(e,t,n,r):new rd(e,t,n,r)}}import{ErrorCategory as gd,fromEvent as _d,isNullable as vd,Subject as yd,Subscription as bd,ValueSubject as xd}from"@vkontakte/videoplayer-shared";import{assertNever as Sd,ErrorCategory as Cd,Subject as wd}from"@vkontakte/videoplayer-shared";var Td=18,Ed=!1;try{Ed=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=Td}catch(e){console.error(e)}class Dd{bufferFull$=new wd;error$=new wd;buffer;queue=[];currentTask=null;destroyed=!1;abortRequested=!1;isAbortFixEnabled=!1;constructor(e,t=!1){this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener(`updateend`,this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(n=>{let r={operation:`append`,data:e,signal:t,callback:n};this.queue.push(r),this.pull()})}async remove(e,t,n){return n&&n.aborted?!1:new Promise(r=>{let i={operation:`remove`,from:e,to:t,signal:n,callback:r};this.queue.unshift(i),this.pull()})}async abort(e){return new Promise(t=>{let n,r=e=>{this.abortRequested=!1,t(e)};n=Ed&&e?{operation:`safariAbort`,init:e,callback:r}:{operation:`abort`,callback:r},this.isAbortFixEnabled&&this.currentTask&&(this.currentTask.callback(!1),this.currentTask=null);for(let{callback:e}of this.queue)e(!1);this.abortRequested=!0,n&&(this.queue=[n]),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}}completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:`BufferTaskQueueUnknown`,category:Cd.VIDEO_PIPELINE,message:`Buffer appending or removal failed`,thrown:e})}};pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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(e){e instanceof DOMException&&e.name===`QuotaExceededError`&&t===`append`?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&e.name===`InvalidStateError`||this.error$.next({id:`BufferTaskQueue:${t}`,category:Cd.VIDEO_PIPELINE,message:`Buffer operation failed`,thrown:e}),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:Sd(t)}}}var Od=Dd,kd=(e,t)=>{let n=0;for(let r=0;r<e.length;r++){let i=e.start(r)*1e3,a=e.end(r)*1e3;i<=t&&t<=a&&(n=a)}return Math.max(n-t,0)};class Ad{error$=new yd;updateEnd$=new xd(void 0);mediaSource;sourceBuffer;sourceBufferTaskQueue;subscription=new bd;constructor(e){this.mediaSource=e}init(e,t,n=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Od(this.sourceBuffer,n),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(e=>this.error$.next(e))),this.subscription.add(_d(this.sourceBuffer,`error`).subscribe(()=>this.error$.next({id:`SourceBuffer`,category:gd.VIDEO_PIPELINE,message:`SourceBuffer Error event fired`}))),this.subscription.add(_d(this.sourceBuffer,`updateend`).subscribe(this.updateEnd$))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,n){return this.sourceBufferTaskQueue.remove(e,t,n)}async clear(e){let t=this.getBufferState();if(vd(t))return Promise.resolve(!1);let n=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)n&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return n}warmUpMediaSource(){!vd(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode=`segments`)}getBufferState(){if(vd(this.sourceBuffer)||!I(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 vd(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||vd(e)?0:kd(this.sourceBuffer.buffered,e)}async abortBuffer(e){return vd(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}}import{ErrorCategory as jd,isHigher as Md,isLower as Nd,isLowerOrEqual as Pd,VideoQuality as Fd}from"@vkontakte/videoplayer-shared";var Id=e=>{switch(e){case`DASH_SEP`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_ONDEMAND`:case`DASH_STREAMS`:return!0;default:return!1}},Ld=Object.values(Fd).filter(e=>e!==Fd.INVARIANT).sort((e,t)=>Md(e,t)?-1:1),Rd=e=>{if(!e||e===Fd.INVARIANT)return null;let t=Ld.find(t=>Nd(t,e))??Fd.Q_1080P;return Pd(t,Fd.Q_1080P)?Fd.Q_1080P:t},zd=(e,t,n)=>e.category===jd.VIDEO_PIPELINE&&e.id.endsWith(`MediaError#${MediaError.MEDIA_ERR_DECODE}`)&&Id(t)?Rd(n):null,Bd=({height:e},t)=>{let n=`${e}p`;try{return Md(n,t)}catch{return!1}},Vd=(e,t)=>{e.video.forEach(e=>{e.representations.forEach(e=>{e.tvDisabled=e.tvDisabled||Bd(e,t)})})},Hd=(e,t,n)=>{let r=[];for(let i of e.representations){let e=`${i.mime}; codecs="${i.codecs}"`,a=t.canPlayType?.(e),o=!1;switch(n){case`probably`:o=a===`probably`;break;case`maybe`:o=!!a;break}o&&r.push(i)}return r.length?{...e,representations:r}:null},Ud=(e,t,n)=>{let r=[];for(let i of e){let e=Hd(i,t,n);e&&r.push(e)}return r},Wd=(e,t)=>{if(!e.length||!t.length)return[];let n=[],r=0,i=0;for(;r<e.length&&i<t.length;){let a=Math.max(e[r].from,t[i].from),o=Math.min(e[r].to,t[i].to);a<o&&n.push({from:a,to:o}),e[r].to<t[i].to?r++:i++}return n},Gd=[`timeupdate`,`progress`,`play`,`seeked`,`stalled`,`waiting`],Kd=[`timeupdate`,`progress`,`loadeddata`,`playing`,`seeked`];class qd{element=null;manifestUrlString=``;source=null;manifest=null;tuning;tracer;stallTracer=null;forceVideoCodec;stallTimeInWaitingExitAttemptMade=0;videoBufferManager;audioBufferManager;bufferManagers=[];videoNativeBufferManager;audioNativeBufferManager;nativeBufferManagers=[];throughputEstimator;subscription=new Bc;subscriptionRemovable=new Vc;representationSubscription=new Bc;fetcher;forceEnded$=new zc;stallWatchdogSubscription;destroyController=new xc;state$=new Dt(`none`);currentVideoRepresentation$=new R(void 0);currentVideoRepresentationInit$=new R(void 0);currentAudioRepresentation$=new R(void 0);currentVideoSegmentLength$=new R(0);currentAudioSegmentLength$=new R(0);error$=new zc;manifestRequested=new zc;manifestReceived=new zc;firstBytesRequested=new zc;firstBytesReceived=new zc;lastConnectionType$=new R(void 0);lastConnectionReused$=new R(void 0);lastRequestFirstBytes$=new R(void 0);lastConnectionMetrics$=new R(void 0);lastDownloadMetrics$=new R(void 0);currentLiveTextRepresentation$=new R(null);timeoutSourceOpenId;isLive$=new R(!1);isActiveLive$=new R(!1);isLowLatency$=new R(!1);liveDuration$=new R(0);liveSeekableDuration$=new R(0);liveAvailabilityStartTime$=new R(0);liveStreamStatus$=new R(void 0);currentBuffer$=new R({from:0,to:0});bufferLength$=new R(0);nativeBufferLength$=new R(0);liveLatency$=new R(void 0);liveLoadBufferLength$=new R(0);livePositionFromPlayer$=new R(0);currentStallDuration$=new R(0);videoLastDataObtainedTimestamp$=new R(0);fetcherRecoverableError$=new zc;fetcherError$=new zc;updateDurationError$=new zc;isOnDemand=!1;dashMaxTvVideoQuality;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(`DashProviderVirtualPlayer`),this.forceVideoCodec=e.forceVideoCodec,this.isOnDemand=e.isOnDemand||!1,this.dashMaxTvVideoQuality=e.dashMaxTvVideoQuality,this.fetcher=new wl({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam,measureNonSegmentRequests:e.tuning.throughputEstimator.measureNonSegmentRequests,handleExtendedNetworkErrorsSet:e.tuning.handleExtendedNetworkErrorsSet,useUrlCacheMechanism:e.tuning.useUrlCacheMechanism}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}initRepresentations=wc(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initRepresentationsStart`,kc({initialVideo:e,initialAudio:t,sourceHls:n})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(`representations_ready`);let r={fetcher:this.fetcher,tracer:this.tracer,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,n),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceInitDuration(),this.tuning.audioOnly?Tc(this.audioBufferManager):Tc(this.videoBufferManager);let i=[];e&&i.push(this.videoBufferManager?.startWith(e)??Promise.resolve()),t&&i.push(this.audioBufferManager?.startWith(t)??Promise.resolve()),yield Promise.all(i),this.state$.setState(`representations_ready`),this.tracer.log(`initRepresentationsEnd`)}.bind(this));async initManifest(e,t,n){this.tracer.log(`initManifest`),this.state$.startTransitionTo(`manifest_ready`),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,n),this.manifest=await this.updateManifest(),!this.tuning.audioOnly&&!this.manifest?.streams.video.length||this.tuning.audioOnly&&!this.manifest?.streams.audio.length?this.error$.next({id:`NoRepresentations`,category:Ec.PARSER,message:`No playable video representations`}):this.state$.setState(`manifest_ready`)}initBuffer(){let e=this.tracer.createComponentTracer(`initBuffer`);Tc(this.element),this.state$.setState(`running`),this.subscription.add(Lc(...Gd.map(e=>Ac(this.element,e)),Ac(Mc(),`online`),Nc(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),e=>this.error$.next({id:`DashVKPlayer`,category:Ec.WTF,message:`Internal logic error`,thrown:e}))),e.log(`tick maintain subscription initialized`);let t=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Lc(...t.map(e=>Ac(e,`updateend`))).subscribe(e=>this.reinitDecoderIfNeeded())),e.log(`reinit decoder subscription initialized`),this.subscription.add(Ac(this.element,`waiting`).subscribe(e=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription),this.stallTracer?.end(),this.stallTracer=null);let t=(this.element?.currentTime??0)*1e3;this.stallTracer=this.tracer.createComponentTracer(`stall `+t),this.stallWatchdogSubscription=Nc(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),e=>this.error$.next({id:`StallWatchdogCallback ${e instanceof Error?e.message:``}`,category:Ec.NETWORK,message:`Can't restore DASH after stall.`,thrown:e})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),e.log(`stall subscription initialized`),e.end()}async switchRepresentation(e,t,n){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,n)}async seek(e,t=!1){let n=this.tracer.createComponentTracer(`seek `+e);Tc(this.element);let r;r=t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(this.videoBufferManager?.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(r),n.log(`prepare seek `,{requestedPosition:e,forcePrecise:t}),await Promise.all([this.videoBufferManager?.prepareSeek(),this.audioBufferManager?.prepareSeek()]),this.element.currentTime=r/1e3,n.log(`set current time to `,{currentTime:r/1e3}),n.log(`seek to `,{position:r}),await Promise.all([this.videoBufferManager?.seek(r),this.audioBufferManager?.seek(r)]),await this.reinitDecoderIfNeeded(),n.end()}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Pc(this.element)&&Pc(this.source)&&Pc(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(e=>e.warmUpMediaSource())}getForwardBufferRepresentations(e){return e===`video`?this.videoBufferManager?.getForwardBufferRepresentations():this.audioBufferManager?.getForwardBufferRepresentations()}getActiveVideoSegmentProgress(){return this.videoBufferManager?.getActiveSegmentProgress()}getMpdVideoSegmentDuration(){return this.videoBufferManager?.getMpdSegmentDuration()}get isStreamEnded(){return this.source?.readyState===`ended`}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e,t){this.videoBufferManager?.setTarget(e),this.audioBufferManager?.setTarget(t)}getVideoForwardBufferDuration(){return this.videoBufferManager?.getForwardPlaybackBufferDuration()??0}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&&Mc().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Pc(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}updateSourceDurationFromSegments(){if(!this.source||this.source.readyState!==`open`||this.isLive$.getValue()||!this.tuning.useDurationFromSegments)return;let e=e=>{this.updateDurationError$.next({id:`updateDuration`,category:Ec.VIDEO_PIPELINE,message:"Duration can`t be updated",thrown:e})};try{if(!this.isAnyBufferUpdating()){this.source.duration=this.calculateDurationFromBuffersSegments()/1e3;return}}catch(t){e(t);return}let t=new Bc;t.add(Lc(...this.nativeBufferManagers.map(e=>e.updateEnd$)).subscribe(()=>{if(!this.isAnyBufferUpdating()){t.unsubscribe();try{this.source&&(this.source.duration=this.calculateDurationFromBuffersSegments()/1e3)}catch(t){e(t)}}}))}calculateDurationFromBuffersSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}isAnyBufferUpdating(){return!this.source||this.source.readyState!==`open`?!1:Array.from(this.source.sourceBuffers).some(e=>e.updating)}get isStreamNotOpen(){return this.source?.readyState!==`open`}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[],n=this.audioNativeBufferManager?.getBufferState()??[],r;if(r=Fc(this.videoBufferManager)?n:Fc(this.audioBufferManager)?t:Wd(t,n),Fc(this.element)||!r.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&r.some(({from:e,to:t})=>i>=e&&i<=t&&t-e>this.tuning.dash.minNativeBufferSize/2)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Tc(this.element),Tc(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;if(this.currentStallDuration$.next(t),this.stallTracer?.log(`timeInWaiting`,{timeInWaiting:t}),await this.reinitDecoderIfNeeded(t%1e3==0),this.isStallExceeded(t)){let e=this.audioBufferManager?.getMutexInfo()??``,n=this.videoBufferManager?.getMutexInfo()??``;if(this.stallTracer?.log(`stallExceeded`,kc({timeInWaiting:t,audioMutexState:e,videoMutexState:n,mutexStallExitPolicy:this.tuning.dash.mutexStallExitPolicy,seekStallExitPolicy:this.tuning.dash.seekStallExitPolicy})),this.tuning.dash.mutexStallExitPolicy&&(e||n)){let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}else if(this.tuning.dash.seekStallExitPolicy)if(this.stallTimeInWaitingExitAttemptMade>0&&t-this.stallTimeInWaitingExitAttemptMade>this.tuning.dash.restoreBufferBeforeCrashTimeout){let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}else this.stallTimeInWaitingExitAttemptMade===0&&(this.stallTracer?.log(`seek`),await this.seek((this.element.currentTime+1)*1e3),this.stallTimeInWaitingExitAttemptMade=t);else{let r=`video: ${n} | audio: ${e}`;throw this.stallTracer?.setSpanAttributes({videoMutexState:n,audioMutexState:e,timeInWaiting:t,unexpectedStall:!0}),Error(`Stall timeout exceeded: ${r} ${t} ms`)}}await this.restoreAfterDeepStall()}isStallExceeded(e){if(Fc(this.element))return!1;let{crashOnStallTimeout:t,virtualBufferEmptinessTolerance:n}=this.tuning.dash,r=n,i=this.element?this.element.currentTime*1e3:0,a=i-r>0?this.tuning.dash.crashOnStallTWithoutDataTimeout:t,o=Rc(),s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let c=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoNativeBufferManager?.getForwardBufferDuration(i)??0,u=this.audioNativeBufferManager?.getForwardBufferDuration(i)??0,d=Pc(this.videoBufferManager)&&l<r&&o-s>a,f=Pc(this.audioBufferManager)&&u<r&&o-c>a;return(d||f)&&e>a||e>=t}async updateManifest(){this.tracer.log(`updateManifestStart`,{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Fc(e))return null;let t=this.parseManifest(e);if(!t)return null;let n=this.getResultManifest(t);return this.tracer.log(`updateManifestEnd`,kc(n)),n}fetchManifest=wc(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Fc(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:`LoadManifest`,category:Ec.NETWORK,message:`Failed to load manifest`,thrown:e})}}.bind(this));parseManifest(e){try{return Nl(e??``,this.manifestUrlString)}catch(t){let n=Cc(e)??{id:`ManifestParsing`,category:Ec.PARSER,message:`Failed to parse MPD manifest`,thrown:t};this.error$.next(n)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},n=(e,t,n)=>!!(this.element?.canPlayType?.(t)&&Fe()?.isTypeSupported?.(`${t}; codecs="${n}"`)||e===`text`),r,i;for(let a of[`video`,`audio`]){let o=e.streams[a],s=this.tuning.dash.checkRepresentationCanPlayType&&this.element?Ud(o,this.element,this.tuning.dash.checkRepresentationCanPlayType):o.filter(({mime:e,codecs:t})=>n(a,e,t));t[a]=s;let c,l;if(this.tuning.dash.codecsPrioritizeEnabled){if(a===`audio`)i=ca(s.map(({codecs:e})=>e)),c=i[0],c&&(t[a]=s.filter(({codecs:e})=>la(e)===c));else if(a===`video`){r=oa(s,{preferHdr:this.tuning.preferHDR});let e=this.forceVideoCodec;l=(e?r.find(t=>t.name===e.name&&t.hdr===e.hdr):void 0)??r[0],l&&(t[a]=s.filter(e=>la(e.codecs)===l.name&&!!e.hdr===l.hdr))}}else{let e=aa(new Set(s.map(({codecs:e})=>e)));e&&(t[a]=s.filter(({codecs:t})=>t.startsWith(e)))}if(a===`video`){if(!this.tuning.dash.codecsPrioritizeEnabled){let e=this.tuning.preferHDR,n=t.video.some(e=>e.hdr),r=t.video.some(e=>!e.hdr);A.display.isHDR&&e&&n?t.video=t.video.filter(e=>e.hdr):r&&(t.video=t.video.filter(e=>!e.hdr))}let{videoStreamRepresentaionsFilter:e}=this.tuning.dash;if(e.length&&fa(t,e),this.dashMaxTvVideoQuality&&Vd(t,this.dashMaxTvVideoQuality),this.isOnDemand&&this.tuning.dash.filterOnDemandQualityList)for(let e of t.video)e.representations=e.representations.sort((e,t)=>t.height-e.height).filter((e,t)=>t%2==0)}}let a={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(a.codecs={video:r,audio:i}),a}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.stallTimeInWaitingExitAttemptMade=0,this.currentStallDuration$.next(0),this.stallTracer?.end(),this.stallTracer=null}createBuffers(e,t,n,r){Tc(this.manifest),Tc(this.element);let i=e=>{this.representationSubscription.add(Ac(e,`error`).pipe(Dc(e=>!!this.element?.played.length)).subscribe(e=>{this.error$.next({id:`VideoSource`,category:Ec.VIDEO_PIPELINE,message:`Unexpected video source error`,thrown:e})}))};this.source=Re();let a=Mc().document,o=a.createElement(`source`);if(i(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),Ie())if(r){let e=a.createElement(`source`);i(e),e.type=`application/x-mpegurl`,e.src=r.url,this.element.appendChild(e)}else this.element.disableRemotePlayback=!0;if(Pc(t)){let t=this.manifest.streams.video.reduce((e,t)=>[...e,...t.representations],[]);t.length&&(this.videoNativeBufferManager=new Ad(this.source),this.videoBufferManager=hd.getBufferManager(`video`,this.videoNativeBufferManager,t,e),this.bufferManagers.push(this.videoBufferManager),this.nativeBufferManagers.push(this.videoNativeBufferManager))}if(Pc(n)){this.audioNativeBufferManager=new Ad(this.source);let t=this.manifest.streams.audio.reduce((e,t)=>[...e,...t.representations],[]);this.audioBufferManager=hd.getBufferManager(`audio`,this.audioNativeBufferManager,t,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=Mc().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:`OpenOfStream`,category:Ec.VIDEO_PIPELINE,message:`Failed to open MediaSource`,thrown:Error(`Timeout reject when wait sourceopen event`),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener(`sourceopen`,()=>{this.timeoutSourceOpenId&&Mc().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add(Lc(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),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(Lc(...Kd.map(e=>Ac(this.element,e)),Nc(this.tuning.dash.tickMaintainInterval)).pipe(Ic(e=>this.videoBufferManager?.getPlaybackBufferState()),Dc(Pc),Ic(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Lc(...Kd.map(e=>Ac(this.element,e)),Nc(this.tuning.dash.tickMaintainInterval)).pipe(Ic(e=>Math.min(this.videoBufferManager?.getForwardPlaybackBufferDuration()??1/0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??1/0)),Oc()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Dc(e=>e>this.tuning.dash.virtualBufferEmptinessTolerance)).subscribe(()=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=jc(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e(`error`,!0)))}async tick(){if(Fc(this.element)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,t=this.videoNativeBufferManager?.getBufferState()??[],n=this.audioNativeBufferManager?.getBufferState()??[],r=t.find(t=>e>=t.from&&e<=t.to),i=n.find(t=>e>=t.from&&e<=t.to),a=r?r.to-e:0,o=i?i.to-e:1/0;Pc(this.videoBufferManager)?this.nativeBufferLength$.next(Math.min(a,o)):Pc(this.audioBufferManager)&&this.nativeBufferLength$.next(o);let s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s),await Promise.all([this.videoBufferManager?.maintain(),this.audioBufferManager?.maintain()])}}import{assertNonNullable as Jd,combine as Yd,ErrorCategory as Xd,filter as Zd,filterChanged as Qd,fromEvent as $d,isNonNullable as ef,map as tf,merge as nf}from"@vkontakte/videoplayer-shared";class rf extends qd{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceInitDuration(){Jd(this.manifest),Jd(this.source);let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(e=>e.representations).flatMap(e=>{let t=[];return e.duration&&t.push(e.duration),Ya(e.segmentReference)&&e.segmentReference.totalSegmentsDurationMs&&t.push(e.segmentReference.totalSegmentsDurationMs),t})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(){Jd(this.element);let e=this.element.currentTime*1e3;this.stallTracer?.log(`restore maintain`,{position:e}),await Promise.all([this.videoBufferManager?.maintain(e),this.audioBufferManager?.maintain(e)])}initDisableStallWatchdogSubscription(){Jd(this.element);let e=nf($d(this.element,`ended`),this.forceEnded$),t=this.nativeBufferLength$.pipe(Zd(e=>e>this.tuning.dash.virtualBufferEmptinessTolerance));this.representationSubscription.add(nf(e,t).subscribe(e=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Yd({allBuffersFull:nf(...this.bufferManagers.map(e=>e.fullyBuffered$)).pipe(tf(()=>this.bufferManagers.every(e=>e.fullyBuffered$.getValue()))),someBufferEnded:nf(...this.bufferManagers.map(e=>e.onLastSegment$)).pipe(tf(()=>this.bufferManagers.some(e=>e.onLastSegment$.getValue())))}).pipe(Qd(),tf(({allBuffersFull:e,someBufferEnded:t})=>e&&t),Zd(e=>e));this.representationSubscription.add(nf(this.forceEnded$,e).pipe(Zd(e=>ef(this.source)&&this.source.readyState===`open`&&Array.from(this.source.sourceBuffers).every(e=>!e.updating))).subscribe(()=>{try{this.source?.endOfStream()}catch(e){this.error$.next({id:`EndOfStream`,category:Xd.VIDEO_PIPELINE,message:`Failed to end MediaSource stream`,thrown:e})}}))}}class af extends bc{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:n,genericErrorListener:r}=this.getProviderSubscriptionInfo();n(t.timeUpdate$,e.position$),n(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(wa(),Ca(e=>Ta(e))).subscribe(()=>{this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wa(),Ca(e=>Ta(e))).subscribe(()=>{this.player.updateSourceDurationFromSegments()},r))}getPlayer(){return new rf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec,isOnDemand:this.params.isOnDemand||!1,dashMaxTvVideoQuality:this.params.dashMaxTvVideoQuality})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}import{combine as of,merge as sf,filter as cf,filterChanged as lf,isNullable as uf,map as df,ValueSubject as ff,isNonNullable as pf}from"@vkontakte/videoplayer-shared";import{isNullable as mf,ValueSubject as hf}from"@vkontakte/videoplayer-shared";class gf{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;varianceCoefficient$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new hf(e.initial),this.debounced$=new hf(e.initial),this.varianceCoefficient$=new hf(0);let t=e.label??`value`+Math.random().toString(16).substring(2,6);this.rawSeries$=new gr(`raw_${t}`),this.smoothedSeries$=new gr(`smoothed_${t}`),this.reportedSeries$=new gr(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,n=0;for(let e=0;e<this.pastMeasures.length;e++)this.pastMeasures[e]!==void 0&&(t+=(this.pastMeasures[e]-this.smoothed)**2,n++);this.takenMeasures=n,t/=n;let r=Math.sqrt(t);n>=2&&this.smoothed>0&&this.varianceCoefficient$.next(r/this.smoothed);let i=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>i||this.smoothed<a)&&(mf(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))}}class _f extends gf{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=lo(this.slow,e,this.params.emaAlphaSlow),this.fast=lo(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class vf extends gf{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=uo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=lo(this.emaSmoothed,e,this.params.emaAlpha);let n=fo(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=n?this.emaSmoothed:t}}class yf extends gf{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?lo(this.smoothed,e,this.params.emaAlpha):e}}class bf{static getSmoothedValue(e,t,n){return n.type===`TwoEma`?new _f({initial:e,emaAlphaSlow:n.emaAlphaSlow,emaAlphaFast:n.emaAlphaFast,changeThreshold:n.changeThreshold,fastDirection:t,deviationDepth:n.deviationDepth,deviationFactor:n.deviationFactor,label:`throughput`}):new vf({initial:e,emaAlpha:n.emaAlpha,basisTrendChangeCount:n.basisTrendChangeCount,changeThreshold:n.changeThreshold,deviationDepth:n.deviationDepth,deviationFactor:n.deviationFactor,label:`throughput`})}static getLiveBufferSmoothedValue(e,t){return new yf({initial:e,label:`liveEdgeDelay`,...t})}}import{assertNonNullable as xf,combine as Sf,ErrorCategory as Cf,filter as wf,filterChanged as Tf,fromEvent as Ef,interval as Df,isNonNullable as Of,isNullable as kf,map as Af,now as jf,throttle as Mf}from"@vkontakte/videoplayer-shared";var Nf=(e,t)=>{e&&e.playbackRate!==t&&(e.playbackRate=t)};import{isNullable as Pf,ValueSubject as Ff}from"@vkontakte/videoplayer-shared";class If{currentRepresentation$=new Ff(null);maxRepresentations=4;representationsCursor=0;representations=[];getCurrentPosition;currentSegment=null;constructor(e,t){this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Pf(e))for(let t of this.representations)for(let n of t){let t=n.segmentReference,r=t.segments.length,i=t.segments[0].time.from,a=t.segments[r-1].time.to;if(e<i||e>a)continue;let o=t.segments.find(t=>t.time.from<=e&&t.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...n,label:`Live Text`,language:`ru`,isAuto:!0,url:new URL(o.url,t.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let e=If.filterRepresentations(t.representations);if(e){this.representations[this.representationsCursor]=e,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(e=>If.filterRepresentations(e.representations))}static filterRepresentations(e){return e?.filter(e=>e.kind===`text`&&`segmentReference`in e&&Ya(e.segmentReference))}}class Lf extends qd{liveTextManager;liveStreamEndTimestamp=0;liveBuffer;livePauseWatchdogSubscription;liveWasInterrupted=!1;constructor(e){super(e),this.liveBuffer=bf.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(e){xf(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){let e=this.videoBufferManager?.getRepresentationInitialTime()??0;await super.seek(e,!1)}async tick(){await super.tick();let e=(this.element?.currentTime??0)*1e3;this.liveTextManager?.maintain(e)}setSourceInitDuration(){xf(this.source),this.source.duration=2**53-1}isStallExceeded(e){let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,n=this.liveStreamStatus$.getValue()===`active`;return(!t||n)&&super.isStallExceeded(e)}async restoreAfterDeepStall(){let{liveStallReinitInterval:e}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,n=this.currentStallDuration$.getValue(),r=this.liveStreamStatus$.getValue()===`active`;if(n%e===0){let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!r&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(e).catch(e=>{this.error$.next({id:`stallIntervalCallback`,category:Cf.VIDEO_PIPELINE,message:`stallIntervalCallback failed`,thrown:e})})}}async updateManifest(){let e=await super.updateManifest();if(kf(e))return null;if(kf(e.live))return this.error$.next({id:`ManifestParsing`,category:Cf.PARSER,message:`MPD doesnt contain live section for live stream`}),null;this.isLive$.next(!0);let{availabilityStartTime:t,latestSegmentPublishTime:n,streamIsUnpublished:r,streamIsAlive:i}=e.live,a=(e.duration??0)/1e3;this.liveSeekableDuration$.next(-1*a),this.liveDuration$.next((n-t)/1e3),this.liveAvailabilityStartTime$.next(e.live.availabilityStartTime);let o=`active`;if(i||(o=r?`unpublished`:`unexpectedly_down`),this.liveStreamStatus$.next(o),this.bufferManagers.forEach(t=>t.updateManifest(e)),this.liveTextManager?.updateLive(e),i&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(e).catch(e=>{this.error$.next({id:`updateManifest`,category:Cf.VIDEO_PIPELINE,message:`seekLive after stream restore failed`,thrown:e})})}return e}prepareManifestUrlString(e,t){return O(e,t,2)}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()===`active`?0:jf()-this.liveStreamEndTimestamp,n=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(n===0),this.manifestUrlString=O(this.manifestUrlString,n,2)}createBuffers(e,t,n,r){xf(this.manifest),super.createBuffers(e,t,n,r),If.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new If(this.manifest.streams.text,e))}initRepresentationSubscriptions(){xf(this.element),xf(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let e=this.videoBufferManager,t=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(e),this.initLiveBufferInfoSubscriptions(e,t),this.initLiveMaintainSubscription(t),Of(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){xf(this.element);let{liveUpdateInterval:e}=this.tuning.dash,t=()=>Df(e).subscribe(async t=>{let n=me(this.manifestUrlString,2);this.manifestUrlString=O(this.manifestUrlString,n+e,2),this.liveStreamStatus$.getValue()===`active`&&(this.manifest=await this.updateManifest())});this.representationSubscription.add(Ef(this.element,`pause`).subscribe(e=>{this.livePauseWatchdogSubscription=t(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add(Ef(this.element,`play`).subscribe(e=>this.livePauseWatchdogSubscription?.unsubscribe()))}initLiveDurationSubscriptions(e){this.representationSubscription.add(this.liveDuration$.pipe(Tf()).subscribe(e=>this.liveStreamEndTimestamp=jf())),this.representationSubscription.add(e.currentLowLatencySegmentLength$.subscribe(e=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!e)return;let t=this.liveSeekableDuration$.getValue()-e/1e3;this.liveSeekableDuration$.next(Math.max(t,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+e/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add(Sf({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Af(({isActiveLive:e,isLowLatency:t})=>e&&t),Tf(),wf(e=>!this.isManualDecreasePlaybackInLive())).subscribe(e=>Nf(this.element,1))),this.representationSubscription.add(Sf({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wf(e=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:e,isActiveLive:t,isLowLatency:n})=>{if(!n||!t)return;let r=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,i=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,a=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=e-r,s=1;Math.abs(o)>i&&(s=1+Math.sign(o)*a),Nf(this.element,s)}))}initLiveBufferInfoSubscriptions(e,t){this.representationSubscription.add(Sf({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wf(({bufferLength:e,isActiveLive:t,isLowLatency:n})=>t&&n&&!!e),Af(({bufferLength:e})=>e)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(e=>{let n=0;if(e){let e=(this.element?.currentTime??0)*1e3;n=Math.min(...t.map(t=>t.getLiveSegmentsToLoadState(this.manifest)?.to??e))-e}this.liveLoadBufferLength$.getValue()!==n&&this.liveLoadBufferLength$.next(n)})),this.representationSubscription.add(Sf({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:e.currentLiveSegmentServerLatency$}).pipe(wf(({isLive:e})=>e),Tf((e,t)=>t.bufferLength<e.bufferLength),Af(({rtt:e,bufferLength:t,segmentServerLatency:n})=>{let r=me(this.manifestUrlString,2);return(e/2+t+n+r)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(e){let t=0;this.representationSubscription.add(Sf({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Mf(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:n,bufferLength:r})=>{xf(this.element);let i=this.element.playbackRate,a=me(this.manifestUrlString,2),o=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,s=Math.min(o,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*i),c=this.tuning.dashCmafLive.normalizedActualBufferOffset*i,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*i,u=isFinite(n)?n:r,d=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),f=o<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(f);let p=`none`;if(d?p=`active_low_latency`:this.isLowLatency$.getValue()&&f?(e.forEach(e=>e.proceedLowLatencyLive()),p=`active_low_latency`):a!==0&&u<s?p=`live_forward_buffering`:u<s+l&&(p=`live_with_target_offset`),isFinite(n)&&(t=n>t?n:t),p===`live_forward_buffering`||p===`live_with_target_offset`){let e=t-(s+c),r=this.normalizeLiveOffset(Math.trunc(a+e/i)),o=Math.abs(r-a),l=0;!n||o<=this.tuning.dashCmafLive.offsetCalculationError?l=a:r>0&&o>this.tuning.dashCmafLive.offsetCalculationError&&(l=r),this.manifestUrlString=O(this.manifestUrlString,l,2)}(p===`live_with_target_offset`||p===`live_forward_buffering`)&&(t=0,this.manifest=await this.updateManifest())},e=>{this.error$.next({id:`updateLive`,category:Cf.VIDEO_PIPELINE,thrown:e,message:`Failed to update live with subscription`})}))}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}}class Rf extends bc{constructor(e){super(e),this.textTracksManager?.destroy()}getPlayer(){return new Lf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}subscribe(){super.subscribe();let e=!1,t=-1,{output:n,observableVideo:r,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0);let o=new ff(1);a(r.playbackRateState$,o),a(r.timeUpdate$,n.liveBufferTime$),a(this.player.liveSeekableDuration$,n.duration$),a(this.player.liveLatency$,n.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(n.elementVisible$.pipe(lf()).subscribe(t=>{let r=n.position$.getValue(),i=n.volume$.getValue(),a=!i.volume||i.muted;!t&&!r&&a?e=!0:t&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(df(e=>e.to)).subscribe(this.player.isLowLatency$)).add(of({liveBufferTime:n.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(df(({liveBufferTime:e,liveAvailabilityStartTime:t})=>e&&t?e+t:void 0)).subscribe(n.liveTime$)).add(of({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:sf(r.playbackRateState$,new ff(1))}).pipe(cf(({liveStreamStatus:e,liveDuration:t})=>e===`active`&&!!t)).subscribe(({liveDuration:e,playbackRate:r})=>{let i=n.liveBufferTime$.getValue(),a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;a||r<1-o||this.allocation.target.paused||uf(i)||(t=e-i)})).add(of({time:n.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:sf(r.playbackRateState$,new ff(1))}).pipe(lf((e,t)=>this.player.liveStreamStatus$.getValue()===`active`?e.liveDuration===t.liveDuration:e.time===t.time)).subscribe(({time:e,liveDuration:r,playbackRate:i})=>{let a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;if(!a&&!this.allocation.target.paused&&i>=1-o||uf(e)||uf(r))return;let s=-1*(r-e-t);n.position$.next(Math.min(s,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(e=>{if(e){let t=Ka(e);this.params.output.availableTextTracks$.next([t])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(cf(e=>pf(e))).subscribe(e=>n.isLiveEnded$.next(e===`unpublished`&&n.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,n=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(n).then(()=>{this.params.output.position$.next(e/1e3)})}}import{assertNever as zf,assertNonNullable as Bf,combine as Vf,debounce as Hf,ErrorCategory as Uf,filter as Wf,filterChanged as Gf,fromEvent as Kf,isNonNullable as qf,isNullable as Jf,map as Yf,merge as Xf,observableFrom as Zf,once as Qf,Subscription as $f,throttle as ep,timeout as tp}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as np}from"@vkontakte/videoplayer-shared";var rp=(e,t,n=0)=>{for(let r=0;r<e.length;r++)if(e.start(r)*1e3-n<=t&&e.end(r)*1e3+n>t)return!0;return!1};import{abortable as ip,assertNonNullable as ap,combine as op,ErrorCategory as U,filter as sp,filterChanged as cp,flattenObject as lp,fromEvent as up,getTraceSubscriptionMethod as dp,interval as fp,isNonNullable as pp,isNullable as mp,map as hp,merge as gp,now as _p,Subject as vp,Subscription as yp,SubscriptionRemovable as bp,tap as xp,throttle as Sp,ValueSubject as W}from"@vkontakte/videoplayer-shared";import{AbortControllerPolyfilled as Cp}from"@vkontakte/videoplayer-shared";import{cancelIdleCallbackPolyfilled as wp}from"@vkontakte/videoplayer-shared";import{requestIdleCallbackPolyfilled as Tp}from"@vkontakte/videoplayer-shared";import{assertNever as Ep,ErrorCategory as Dp,Subject as Op}from"@vkontakte/videoplayer-shared";var kp=18,Ap=!1;try{Ap=A.browser.isSafari&&!!A.browser.safariVersion&&A.browser.safariVersion<=kp}catch(e){console.error(e)}class jp{bufferFull$=new Op;error$=new Op;buffer;queue=[];currentTask=null;destroyed=!1;abortRequested=!1;isAbortFixEnabled=!1;constructor(e,t=!1){this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener(`updateend`,this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(n=>{let r={operation:`append`,data:e,signal:t,callback:n};this.queue.push(r),this.pull()})}async remove(e,t,n){return n&&n.aborted?!1:new Promise(r=>{let i={operation:`remove`,from:e,to:t,signal:n,callback:r};this.queue.unshift(i),this.pull()})}async abort(e){return new Promise(t=>{let n,r=e=>{this.abortRequested=!1,t(e)};n=Ap&&e?{operation:`safariAbort`,init:e,callback:r}:{operation:`abort`,callback:r},this.isAbortFixEnabled&&this.currentTask&&(this.currentTask.callback(!1),this.currentTask=null);for(let{callback:e}of this.queue)e(!1);this.abortRequested=!0,n&&(this.queue=[n]),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}}completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:`BufferTaskQueueUnknown`,category:Dp.VIDEO_PIPELINE,message:`Buffer appending or removal failed`,thrown:e})}};pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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(e){e instanceof DOMException&&e.name===`QuotaExceededError`&&t===`append`?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&e.name===`InvalidStateError`||this.error$.next({id:`BufferTaskQueue:${t}`,category:Dp.VIDEO_PIPELINE,message:`Buffer operation failed`,thrown:e}),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:Ep(t)}}}var Mp=jp;import{abortable as Np,assertNonNullable as G,ErrorCategory as Pp,fromEvent as Fp,getExponentialDelay as Ip,getWindow as Lp,isHigher as Rp,isNonNullable as zp,isNullable as K,now as Bp,once as Vp,Subject as Hp,Subscription as Up,ValueSubject as Wp,isAbortError as Gp}from"@vkontakte/videoplayer-shared";class Kp{currentLiveSegmentServerLatency$=new Wp(0);currentLowLatencySegmentLength$=new Wp(0);currentSegmentLength$=new Wp(0);onLastSegment$=new Wp(!1);fullyBuffered$=new Wp(!1);playingRepresentation$=new Wp(void 0);playingRepresentationInit$=new Wp(void 0);error$=new Hp;gaps=[];updateEnd$=new Wp(void 0);subscription=new Up;kind;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;forwardBufferRepresentations=new Map;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Cp;switchAbortController=new Cp;destroyAbortController=new Cp;useSmartRepresentationSwitch=!1;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;baseUrls=[];baseUrlsIndex=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;lastDataObtainedTimestampMs=0;loadByteRangeSegmentsTimeoutId=0;constructor(e,t,n,{fetcher:r,tuning:i,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:s=!1,manifest:c}){this.fetcher=r,this.tuning=i,this.compatibilityMode=s,this.forwardBufferTarget=i.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!c?.live,this.baseUrls=c?.baseUrls??[],this.initData=new Map(n.map(e=>[e.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(n.map(e=>[e.id,e])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Np(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);G(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mp(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Fp(this.sourceBuffer,`updateend`).subscribe(this.updateEnd$)),this.subscription.add(Fp(this.sourceBuffer,`updateend`).subscribe(()=>{this.checkEjectedSegments(),this.maintain()},e=>{let t,n=this.mediaSource.readyState;n!==`open`&&(t={id:`SegmentEjection_source_${n}`,category:Pp.VIDEO_PIPELINE,message:`Error when trying to clear segments ejected by browser`,thrown:e}),t??={id:`SegmentEjection`,category:Pp.VIDEO_PIPELINE,message:`Error when trying to clear segments ejected by browser`,thrown:e},this.error$.next(t)})),this.subscription.add(Fp(this.sourceBuffer,`error`).subscribe(()=>this.error$.next({id:`SourceBuffer`,category:Pp.VIDEO_PIPELINE,message:`SourceBuffer Error event fired`}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(e=>{let t=this.getCurrentPosition();if(!this.sourceBuffer||!t||!I(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,Zn(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let r=this.getForwardBufferDuration(t),i=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(t,e*2,r<i).catch(e=>{this.handleAsyncError(e,`pruneBuffer`)})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(e=>this.error$.next(e))),yield this.loadInit(t,`high`,!0);let n=this.initData.get(t.id),r=this.segments.get(t.id),i=this.parsedInitData.get(t.id);G(n,`No init buffer for starting representation`),G(r,`No segments for starting representation`),n instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(i))}.bind(this));switchToWithPreviousAbort(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return Promise.resolve();this.switchAbortController.abort(),this.switchAbortController=new Cp;let n=this.switchAbortController.signal;return n.addEventListener(`abort`,()=>{this.switchingToRepresentationId===e&&(this.switchingToRepresentationId=void 0)},{once:!0}),Np(n,async function*(e,t=!1){this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)){this.switchingToRepresentationId===e&&(this.switchingToRepresentationId=void 0);return}if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let t=this.getCurrentPosition();zp(t)&&!this.isLive&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.downloadingRepresentationId=e,this.switchingToRepresentationId=void 0}this.maintain()}.bind(this))(e,t)}switchTo=Np(this.destroyAbortController.signal,async function*(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(!i||!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let t=this.getCurrentPosition();zp(t)&&!this.isLive&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));switchToOld=Np(this.destroyAbortController.signal,async function*(e,t=!1){if(!I(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let n=this.representations.get(e);G(n,`No such representation ${e}`);let r=this.segments.get(e),i=this.initData.get(e);if(K(i)||K(r)?yield this.loadInit(n,`high`,!1):i instanceof Promise&&(yield i),r=this.segments.get(e),G(r,`No segments for starting representation`),i=this.initData.get(e),!(!i||!(i instanceof ArrayBuffer)||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let t=this.getCurrentPosition();zp(t)&&(!this.isLive&&!this.tuning.dash.useNewRepresentationSwitch&&(this.bufferLimit=1/0,yield this.pruneBuffer(t,1/0,!0)),this.maintain(t)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));warmUpMediaSource(){!K(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 Cp,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||zp(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),n=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),i=this.segments.get(this.playingRepresentationId);if(G(t,`No such representation ${this.downloadingRepresentationId}`),G(n,`No such representation ${this.playingRepresentationId}`),K(r)||K(i))return;let a=r.find(t=>e>=t.time.from&&e<t.time.to);zp(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let o=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let r=this.getForwardBufferDuration(e),i=Hu(n),s=Hu(t),c=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&zp(i)&&zp(s)&&Rp(i.quality,s.quality),l=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(c||l?o+=Math.min(r,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&r>=a.time.to-e+100&&(o=a?a.time.to+100:-1/0),this.tuning.dash.useNewRepresentationSwitch){let t=[...this.segments.entries()].map(([t,n])=>({representationId:t,status:n.find(t=>e>=t.time.from&&e<t.time.to)?.status})).sort((e,t)=>{let n=this.representations.get(e.representationId),r=this.representations.get(t.representationId);if(K(n)||K(r))return 0;let i=Hu(n),a=Hu(r);return K(i)||K(a)?0:Rp(i.quality,a.quality)?-1:1}).find(e=>e.status===`fed`)?.representationId;t&&(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Zn(this.sourceBuffer.buffered)>=this.bufferLimit){let t=this.getForwardBufferDuration(e),n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,t<n).catch(e=>{this.handleAsyncError(e,`pruneBuffer`)});return}let s=[];if(!this.activeSegments.size&&(s=this.selectForwardBufferSegments(r,t.segmentReference.type,o),s.length)){let e=`auto`;if(this.tuning.dash.useFetchPriorityHints&&a)if(s.includes(a))e=`high`;else{let t=s.at(0);t&&t.time.from-a.time.to>=this.forwardBufferTarget/2&&(e=`low`)}this.loadSegments(s,t,e).catch(e=>{this.handleAsyncError(e,`loadSegments`)})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===`fed`&&!s.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=r.at(-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<100),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let n=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let i of e)Math.trunc(i.time.from-n)>0&&this.gaps.push({representation:t.id,from:n,to:i.time.from+r,persistent:!0}),n=i.time.to;zp(t.duration)&&t.duration-n>0&&!this.isLive&&this.gaps.push({representation:t.id,from:n,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,n=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],i=0,a=t.length-1;do r.unshift(t[a]),i+=t[a].time.to-t[a].time.from,a--;while(i<n&&a>=0);return this.liveInitialAdditionalOffset=i-n,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let n=t.flatMap(e=>e.representations).find(e=>e.id===this.downloadingRepresentationId);if(!n)return;let r=this.segments.get(n.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}seekLive=Np(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(e=>e.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let e of this.representations.keys()){let n=t.find(t=>t.id===e);n&&this.representations.set(e,n);let r=this.representations.get(e);if(!r||!Yu(r.segmentReference)){this.isSeekingLive=!1;return}let i=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,i)}let n=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(n);G(r,`Representation not found by id ${n}`);let i=this.segments.get(n);G(i,`No segments for starting representation`);let a=this.initData.get(n);if(G(a,`No init buffer for starting representation`),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(i,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){if(!e||[...this.segments.values()].every(e=>!e.length))return;let t=e.streams[this.kind].flatMap(e=>e.representations);for(let e of t){if(!e||!Yu(e.segmentReference))return;let t=e.segmentReference.segments.map(e=>({...e,status:`none`,size:void 0})),n=this.segments.get(e.id)??[],r=n.at(-1)?.time.to??0,i=t?.findIndex(e=>r>=e.time.from+100&&r<=e.time.to+100);if(i===-1){this.liveUpdateSegmentIndex=0;let t=this.getActualLiveStartingSegments(e.segmentReference);this.segments.set(e.id,t)}else{let r=t.slice(i+1);this.segments.set(e.id,[...n,...r])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;G(e);let t=this.segments.get(e);if(t?.length){let e=t[t.length-1];this.updateLowLatencyLiveIfNeeded(e)}}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 n of this.representations.values()){let r=n.segmentReference;if(!Yu(r))return;let i=this.segments.get(n.id)??[],a=i.find(t=>Math.floor(t.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),!i.find(t=>Math.floor(t.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let t=Math.round(e.time.to*r.timescale/1e3).toString(10),n=Ml(r.segmentTemplateUrl,{segmentTime:t});i.push({status:`none`,time:{from:e.time.to,to:1/0},url:n})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let n=this.segments.get(t);return n?n.find(t=>t.time.from<=e&&t.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&&wp&&wp(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&wp&&wp(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,n){return this.isLive?this.selectForwardBufferSegmentsLive(e,n):this.selectForwardBufferSegmentsRecord(e,t,n)}selectForwardBufferSegmentsLive(e,t){let n=e.findIndex(e=>t>=e.time.from&&t<e.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=n),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,n){let r=this.getForwardBufferDuration(n),i=Math.min(this.forwardBufferTarget,this.bufferLimit),a=e.findIndex(({status:e,time:{from:t,to:a}},o)=>{let s=t>n||t<=n&&a>=n||o===0&&n===0,c=this.preloadOnly&&t<=n+i||r<i&&a-t>=i||a<=n+i;return(e===`none`||e===`partially_ejected`&&s&&c&&this.sourceBuffer&&I(this.mediaSource,this.sourceBuffer)&&!(rp(this.sourceBuffer.buffered,t)&&rp(this.sourceBuffer.buffered,a)))&&s&&c});if(a===-1)return[];if(t!==`byteRange`)return e.slice(a,a+1);let o=e,s=0,c=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let e=a;e<o.length&&(s<=u||c<=d);e++){let t=o[e];if(e>a&&t.time.from>=n+i)break;if(s+=t.byte.to+1-t.byte.from,c+=t.time.to+1-t.time.from,t.status===`none`||t.status===`partially_ejected`)l.push(t);else break}return l}async loadSegments(e,t,n=`auto`){Yu(t.segmentReference)?await this.loadTemplateSegment(e[0],t,n):await this.loadByteRangeSegments(e,t,n)}async loadTemplateSegment(e,t,n=`auto`){e.status=`downloading`;let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id,startedAtMs:void 0};this.activeSegments.add(r);let{range:i,url:a,signal:o,onProgress:s,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Np(o,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>setTimeout(t,e))}.bind(this))(),o.aborted&&this.abortActiveSegments([e])),r.startedAtMs=Lp().performance.now();try{let e=await this.fetcher.fetch(a,{range:i,signal:o,onProgress:s,priority:n,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Bp(),!e)return;let l=new DataView(e),u=Bu(t.mime);if(!isFinite(r.segment.time.to)){let e=t.segmentReference.timescale;r.segment.time.to=u.getChunkEndTime(l,e)}s&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:d,serverDataPreparedTime:f}=u.getServerLatencyTimestamps(l);d&&f&&this.currentLiveSegmentServerLatency$.next(f-d),r.segment.status=`downloaded`,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(t){this.abortActiveSegments([e]),Gp(t)||(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())Yu(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,n=`auto`){if(!e.length)return;let r=[];for(let n of e){n.status=`downloading`;let e={segment:n,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id,startedAtMs:void 0};this.activeSegments.add(e),r.push(e)}let{range:i,url:a,signal:o,onProgress:s}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Np(o,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),Fp(window,`online`).pipe(Vp()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));let c=Lp().performance.now();for(let e of r)e.startedAtMs=c;try{await this.fetcher.fetch(a,{range:i,onProgress:s,signal:o,priority:n,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation,urlCacheMechanismEnabled:!Yu(t.segmentReference)}),this.lastDataObtainedTimestampMs=Bp(),this.failedDownloads=0}catch(t){this.abortActiveSegments(e),Gp(t)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Yu(t.segmentReference))throw Error(`Representation is not byte range type`);let n=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:i}=this.downloadAbortController;return{url:n,range:r,signal:i,onProgress:async(e,n)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Bp(),await this.onSomeByteRangesDataLoaded({dataView:e,loaded:n,signal:i,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(e){this.error$.next({id:`SegmentFeeding`,category:Pp.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Yu(t.segmentReference))throw Error(`Representation is not template type`);let n=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&n.searchParams.set(`low-latency`,`yes`);let r=n.toString(),{signal:i}=this.downloadAbortController,a=[];return{url:r,signal:i,onProgress:this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(e,n)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=Bp();let r=this.onSomeTemplateDataLoaded({dataView:e,loaded:n,signal:i,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(r)}catch(e){this.error$.next({id:`SegmentFeeding`,category:Pp.VIDEO_PIPELINE,message:`Error when feeding segments`,thrown:e})}}:void 0,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:n,onSegmentAppendFailed:r,signal:i}){if(!this.activeSegments.size||!I(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:s}=o;if(o.representationId===t){if(i.aborted){r();continue}if(o.loadedBytes=n,o.loadedBytes>o.feedingBytes){let t=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),n=Bu(a.mime).parseFeedableSegmentChunk(t,this.isLive);n?.byteLength&&(s.status=`partially_fed`,o.feedingBytes+=n.byteLength,await this.sourceBufferTaskQueue.append(n),o.fedBytes+=n.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:n,loaded:r,signal:i,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!I(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let s of this.activeSegments){let{segment:c}=s;if(s.representationId!==t)continue;if(i.aborted){await a();continue}let l=c.byte.from-n,u=c.byte.to-n,d=u-l+1,f=l<r,p=u<=r;if(!f)continue;let m=Bu(o.mime);if(c.status===`downloading`&&p){c.status=`downloaded`;let n=new DataView(e.buffer,e.byteOffset+l,d);await this.sourceBufferTaskQueue.append(n,i)&&!i.aborted?this.onSegmentFullyAppended(s,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status===`downloading`||c.status===`partially_fed`)&&(s.loadedBytes=Math.min(d,r-l),s.loadedBytes>s.feedingBytes)){let n=new DataView(e.buffer,e.byteOffset+l+s.feedingBytes,s.loadedBytes-s.feedingBytes),r=s.loadedBytes===d?n:m.parseFeedableSegmentChunk(n);r?.byteLength&&(c.status=`partially_fed`,s.feedingBytes+=r.byteLength,await this.sourceBufferTaskQueue.append(r,i)&&!i.aborted?(s.fedBytes+=r.byteLength,s.fedBytes===d&&this.onSegmentFullyAppended(s,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer))){!this.isLive&&A.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(rp(this.sourceBuffer.buffered,e.segment.time.from,100)&&rp(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:`EmptyAppendBuffer`,category:Pp.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`,Ju(e.segment)&&(e.segment.size=e.fedBytes);for(let n of this.representations.values())if(n.id!==t)for(let t of this.segments.get(n.id)??[])t.status===`fed`&&Math.round(t.time.from)===Math.round(e.segment.time.from)&&Math.round(t.time.to)===Math.round(e.segment.time.to)&&(t.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[n,r]of this.initData.entries()){let i=r instanceof Promise;t||=i,r===null&&(e=n)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let n=this.representations.get(e);n&&(this.initLoadIdleCallback=Tp(()=>this.loadInit(n,`low`,!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t=`auto`,n=!1){let r=this.tuning.dash.useFetchPriorityHints?t:`auto`,i=!n&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,a=(!n&&this.failedDownloads>0?Np(this.destroyAbortController.signal,async function*(){let e=Ip(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>setTimeout(t,e))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Bu(e.mime),{priority:r,ignoreNetworkErrors:i})).then(async t=>{if(!t)return;let{init:n,dataView:r,segments:i}=t,a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);this.initData.set(e.id,a);let o=i;this.isLive&&Yu(e.segmentReference)&&(o=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,o),n&&this.parsedInitData.set(e.id,n)}).then(()=>this.failedDownloads=0,t=>{i||this.initData.set(e.id,null),n&&this.error$.next({id:`LoadInits`,category:Pp.WTF,message:`loadInit threw`,thrown:t})});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,n=!1){if(!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||K(e))return!1;let r=[],i=0,a=e=>{e.sort((e,t)=>e.from-t.from);let t=[e[0]];for(let n=1;n<e.length;n++){let{from:r,to:i}=e[n],a=t[t.length-1];a.to>=r?a.to=Math.max(a.to,i):t.push(e[n])}return t},o=e=>{if(i>=t)return r;r.push({...e.time}),r=a(r);let n=Ju(e)?e.size??0:e.byte.to-e.byte.from;i+=n};for(let t of this.segments.values())for(let n of t){let t=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,r=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(t||r)&&n.status===`fed`&&o(n)}for(let e=0;e<this.sourceBuffer.buffered.length;e++){let t=this.sourceBuffer.buffered.start(e)*1e3,n=this.sourceBuffer.buffered.end(e)*1e3,r=0;for(let e of this.segments.values())for(let i of e)[`none`,`partially_ejected`].includes(i.status)&&Math.round(i.time.from)<=Math.round(t)&&Math.round(i.time.to)>=Math.round(n)&&r++;r===this.segments.size&&o({time:{from:t,to:n},url:``,status:`none`})}if(r.length&&n){let t=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let n of this.segments.values())for(let r of n)r.time.from>=e+t&&r.status===`fed`&&o(r)}return r.length?(await Promise.all(r.map(e=>this.sourceBufferTaskQueue.remove(e.from,e.to)))).reduce((e,t)=>e||t,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!I(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||!I(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||!I(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||K(e)?0:kd(this.sourceBuffer.buffered,e)}getForwardBufferRepresentations(e=this.getCurrentPosition()){if(this.forwardBufferRepresentations.clear(),zp(e))for(let[t,n]of this.segments.entries())this.forwardBufferRepresentations.set(t,n.filter(t=>t.time.from>=e&&t.time.to<=e+this.forwardBufferTarget));return this.forwardBufferRepresentations}getMpdSegmentDuration(){for(let e of this.segments.values()){let t=e[0];if(t&&t.time.to>t.time.from)return t.time.to-t.time.from}}getActiveSegmentProgress(){let e;for(let t of this.activeSegments)K(t.startedAtMs)||(!e||t.segment.time.from<e.segment.time.from)&&(e=t);if(!K(e?.startedAtMs))return{startedAtMs:e.startedAtMs,loadedBytes:e.loadedBytes,totalBytes:e.segment.size??void 0,segmentDurationMs:e.segment.time.to-e.segment.time.from}}detectGaps(e,t){if(!(!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer)))for(let n of t){let t={representation:e,from:n.time.from,to:n.time.to,persistent:!1},{buffered:r}=this.sourceBuffer;for(let e=0;e<r.length;e++){let i=r.start(e)*1e3,a=r.end(e)*1e3;if(!(a<=n.time.from||i>=n.time.to)){if(i<=n.time.from&&a>=n.time.to){t=void 0;break}a>n.time.from&&a<n.time.to&&(t.from=a),i<n.time.to&&i>n.time.from&&(t.to=i)}}t&&t.to-t.from>1&&!this.gaps.some(e=>t&&e.from===t.from&&e.to===t.to)&&this.gaps.push(t)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!I(this.mediaSource,this.sourceBuffer))return;let{buffered:n}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(e=>{if(r&&e.persistent)return!0;let t=Math.round(e.from),i=Math.round(e.to);for(let e=0;e<n.length;e++)if(t>=Math.round(n.start(e)*1e3)&&i<=Math.round(n.end(e)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Tp(()=>{try{this.detectGaps(e,t)}catch(e){this.error$.next({id:`GapDetection`,category:Pp.WTF,message:`detectGaps threw`,thrown:e})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(K(this.sourceBuffer)||!I(this.mediaSource,this.sourceBuffer)||K(this.playingRepresentationId))return;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){let n=Math.floor(this.sourceBuffer.buffered.start(t)*1e3),r=Math.ceil(this.sourceBuffer.buffered.end(t)*1e3);e.push({from:n,to:r})}for(let t of this.segments.values())for(let n of t){let{status:t}=n;if(t!==`fed`&&t!==`partially_ejected`)continue;let r=Math.floor(n.time.from),i=Math.ceil(n.time.to),a=e.some(e=>e.from-100<=r&&e.to+100>=i),o=e.filter(e=>r>=e.from&&r<e.to-100||i>e.from+100&&i<=e.to);a||(o.length===1||this.gaps.some(e=>e.from===n.time.from||e.to===n.time.to)?n.status=`partially_ejected`:n.status=`none`)}}handleAsyncError(e,t){this.error$.next({id:t,category:Pp.VIDEO_PIPELINE,thrown:e,message:`Something went wrong`})}}import{AbortControllerPolyfilled as qp}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Jp}from"@vkontakte/videoplayer-shared";import{abortable as Yp,assertNever as Xp,fromEvent as Zp,merge as Qp,now as $p,Subject as em,ValueSubject as tm,flattenObject as nm,ErrorCategory as rm,SubscriptionRemovable as im,getWindow as am,suppressAbort as om}from"@vkontakte/videoplayer-shared";import{ErrorCategory as sm}from"@vkontakte/videoplayer-shared";var cm=new Set([2,3,4,5,6,9,19]),lm=new Set([1,8,18,21]),um=new Set([10,11,12,13,14,15,16]),dm=({txtCode:e,error$:t,recoverableError$:n,httpCode:r})=>{let i=parseInt(e);if(isNaN(i))return;let a={...fm(i),httpCode:r,UVBackendErrorCode:e,origin:`segment_fetcher`};if(cm.has(i)){t.next({...a,category:sm.NETWORK});return}if(lm.has(i)){n.next({...a,category:sm.FATAL,canBeRecoverable:!0});return}if(um.has(i)){t.next({...a,category:sm.FATAL});return}},fm=e=>{switch(e){case 1:return{id:`VideoDataLinkExpiredError`,message:`Video data links have expired`};case 5:return{id:`VideoServerError`,message:`Server error`};case 8:return{id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`};case 10:return{id:`UserAgentChange`,message:`User agent changed`};case 11:return{id:`forbiddenReferer`,message:`Forbidden referer`};case 12:case 13:case 14:case 15:case 16:return{id:`OKerror`,message:`Error #${e}`};case 18:return{id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`};case 21:return{id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`};default:return pm(e)}};function pm(e){return{id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${e})`}}import{devNull as mm,getWindow as hm}from"@vkontakte/videoplayer-shared";var gm=`vk_player_cached_fetches`,_m=[`fromCache`,`expires`,`sig`],vm=300*1e3,ym=`x-cache-expires`,bm=async e=>{let t=Sm(e),n=await hm().caches.open(gm);return{get:async()=>{let e=await n.match(t);return e&&!Cm(e)?(mm.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_hit`]}),e):(e&&(await n.delete(t),mm.push(`core`,{key:`videoplayer_url_cache`,strings:[`cache_missed`,`expired`]})),null)},set:r=>{n.put(t,wm(r,e))}}};function xm(){return typeof caches<`u`}function Sm(e){try{let t=new URL(e);return t.hostname=`cache.local`,_m.forEach(e=>t.searchParams.delete(e)),t.toString()}catch{return e}}function Cm(e){let t=e.headers.get(ym);if(!t)return!0;let n=Number(t);return isNaN(n)||n<=Date.now()}function wm(e,t){let n=e.clone(),r=new Headers(n.headers);return r.set(ym,Tm(t).toString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:r})}function Tm(e){try{let t=new URL(e).searchParams.get(`expires`);if(t&&!isNaN(Number(t)))return Number(t)}catch{return 0}return Date.now()+vm}var Em=async()=>{await hm().caches.delete(gm)};class Dm{throughputEstimator;requestQuic;tracer;manifestRequested$=new em;firstBytesManifest$=new em;firstBytesRequested$=new em;firstBytesReceived$=new em;lastConnectionType$=new tm(void 0);lastConnectionReused$=new tm(void 0);lastRequestFirstBytes$=new tm(void 0);lastConnectionMetrics$=new tm(void 0);lastDownloadMetrics$=new tm(void 0);recoverableError$=new em;error$=new em;abortAllController=new qp;subscription=new im;compatibilityMode;useEnableSubtitlesParam;useUrlCacheMechanism;measureNonSegmentRequests;startupPhase=!0;performanceObserver=null;pendingConnectionMetrics=new Map;handleExtendedNetworkErrorsSet=!1;constructor({throughputEstimator:e,requestQuic:t,tracer:n,compatibilityMode:r=!1,useEnableSubtitlesParam:i=!1,handleExtendedNetworkErrorsSet:a=!1,useUrlCacheMechanism:o=!1,measureNonSegmentRequests:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=n.createComponentTracer(`Fetcher`),this.useEnableSubtitlesParam=i,this.handleExtendedNetworkErrorsSet=a,this.measureNonSegmentRequests=s,am().PerformanceObserver&&this.setupPerformanceObserver(),this.useUrlCacheMechanism=o}onHeadersReceived(e){let{type:t,reused:n}=Gc(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(n)}setupPerformanceObserver(){this.performanceObserver=new(am()).PerformanceObserver(e=>{e.getEntriesByType(`resource`).forEach(e=>{this.processPerformanceResourceTiming(e)})}),this.performanceObserver.observe({entryTypes:[`resource`]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let n=this.extractConnectionMetrics(e);n&&this.lastConnectionMetrics$.next(n)}estimateNetworkType(){if(!(`connection`in am().navigator))return`unknown`;let e=am().navigator.connection;return e.effectiveType?{"slow-2g":`2g`,"2g":`2g`,"3g":`3g`,"4g":`lte`}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?`2g`:e.downlink<5?`3g`:e.downlink<50?`lte`:`wifi`:e.rtt?e.rtt>500?`2g`:e.rtt>250?`3g`:e.rtt>50?`lte`:`wifi`:`unknown`}extractConnectionMetrics(e){let t=0,n=0,r=0,i=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(i=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,n=e.secureConnectionStart-e.connectStart):n=i),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,n),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,i),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,n]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),i=r.origin+r.pathname,a=new URL(n.url);if(i===a.origin+a.pathname&&e.startTime>=n.startTime-10&&e.startTime<=n.startTime+1e3)return t}}catch{this.recoverableError$.next({id:`VideoDataFetchError`,message:`Video data fetch error with getting download metrics`,category:rm.WTF})}return null}trackRequestStart(e,t){let n=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(n,{url:e,startTime:t})}fetchManifest=Yp(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer(`FetchManifest`),n=e;this.requestQuic&&(n=Wc(n)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(n=il(n)),this.trackRequestStart(n,performance.now());let r=$p();this.manifestRequested$.next();let i=yield this.doFetch(n,{signal:this.abortAllController.signal}).catch(om);if(i){let a=$p();t.log(`success`,nm({url:n,message:`Request successfully executed`})),t.end(),this.onHeadersReceived(i.headers),this.firstBytesManifest$.next();let o=i.headers.get(`content-length`),s=0;o&&(s=parseInt(o,10));let c=await i.text();if((!o||isNaN(s)||s<=0)&&(s=new TextEncoder().encode(c).length),s>0){let t=a-r,n=s/(t/1e3)*8/1024,i={bytes:s,speed:n,url:e};this.lastDownloadMetrics$.next(i)}if(this.measureNonSegmentRequests&&this.startupPhase&&(this.throughputEstimator?.addRawRtt(a-r),o&&s>0)){let e=$p();this.throughputEstimator?.addRawSpeed(s,e-r)}return c}else return t.error(`error`,nm({url:n,message:`No data in request manifest`})),t.end(),null}.bind(this));fetch=Yp(this.abortAllController.signal,async function*(e,{rangeMethod:t=+!this.compatibilityMode,range:n,onProgress:r,priority:i=`auto`,signal:a,measureThroughput:o=!0,isLowLatency:s=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:l=!1,urlCacheMechanismEnabled:u=!1}={}){let d=e,f=new Headers,p=this.tracer.createComponentTracer(`Fetch`);if(n)switch(t){case 0:f.append(`Range`,`bytes=${n.from}-${n.to}`);break;case 1:{let e=new URL(d,am().location.href);e.searchParams.append(`bytes`,`${n.from}-${n.to}`),d=e.toString();break}default:Xp(t)}this.requestQuic&&(d=Wc(d));let m=this.abortAllController.signal,h;if(a){let e=new qp;if(h=Qp(Zp(this.abortAllController.signal,`abort`),Zp(a,`abort`)).subscribe(()=>{try{e.abort()}catch(e){om(e)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{e.abort()}catch(e){om(e)}m=e.signal}let g=0,_=$p();p.log(`startRequest`,nm({url:d,priority:i,rangeMethod:t,range:n,isLowLatency:s,requestStartedAt:_})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested$.next();let v=yield this.doFetch(d,{priority:i,headers:f,signal:m},{ignoreNetworkErrors:l,urlCacheMechanismEnabled:u}),y=$p();if(!v)return p.error(`error`,{message:`No response in request`}),p.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(y-_),!v.ok||!v.body){this.unsubscribeAbortSubscription(h);let e=`Fetch error ${v.status}: ${v.statusText}`;return p.error(`error`,{message:e}),p.end(),Promise.reject(Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let e=yield v.arrayBuffer(),t=$p();if(this.measureNonSegmentRequests&&this.startupPhase){let e=v.headers.get(`content-length`),n=e?parseInt(e,10):NaN;Number.isFinite(n)&&n>0&&this.throughputEstimator?.addRawSpeed(n,t-_)}let n={requestStartedAt:_,requestEndedAt:t,duration:t-_};return p.log(`endRequest`,nm(n)),p.end(),e}let b=v.body;if(o){this.startupPhase=!1;let e;[b,e]=v.body.tee(),this.throughputEstimator?.trackStream(e,s)}let x=b.getReader(),S,C=parseInt(v.headers.get(`content-length`)??``,10);Number.isFinite(C)&&(S=C),!S&&n&&(S=n.to-n.from+1);let w=S?new Uint8Array(S):new Uint8Array,T=!1,E=e=>{this.unsubscribeAbortSubscription(h),T=!0,om(e)},ee=Yp(m,async function*({done:e,value:t}){if(g===0&&(this.lastRequestFirstBytes$.next($p()-_),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(h);return}if(!e&&t){if(c&&S)w.set(t,g),g+=t.byteLength;else{let e=new Uint8Array(w.length+t.length);e.set(w),e.set(t,w.length),w=e,g+=t.byteLength}r?.(new DataView(w.buffer),g),yield x?.read().then(ee,E)}}.bind(this));yield x?.read().then(ee,E),this.unsubscribeAbortSubscription(h);let te=$p(),D={failed:T,requestStartedAt:_,requestEndedAt:te,duration:te-_};if(T)return p.error(`endRequest`,nm(D)),p.end(),null;if(g>0){let t=te-_,n=g/(t/1e3)*8/1024,r={bytes:g,speed:n,url:e};this.lastDownloadMetrics$.next(r)}return p.log(`endRequest`,nm(D)),p.end(),w.buffer}.bind(this));async fetchRepresentation(e,t,n){let{type:r}=e;switch(r){case`byteRange`:return await this.fetchByteRangeRepresentation(e,t,n)??null;case`template`:return await this.fetchTemplateRepresentation(e,n)??null;default:Xp(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&=(this.performanceObserver.disconnect(),null),this.pendingConnectionMetrics.clear(),this.tracer.end()}fetchByteRangeRepresentation=Yp(this.abortAllController.signal,async function*(e,t,n){if(e.type!==`byteRange`)return null;let{from:r,to:i}=e.initRange,a=r,o=i,s=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,s=i+1===c,s&&(a=Math.min(c,r),o=Math.max(l,i))),a=Math.min(a,0);let u=yield this.fetch(e.url,{range:{from:a,to:o},measureThroughput:!1,urlCacheMechanismEnabled:!0,...n});if(!u)return null;let d=new DataView(u,r-a,i-a+1);if(!t.validateData(d))throw Error(`Invalid media file`);let f=t.parseInit(d),p=e.indexRange??t.getIndexRange(f);if(!p)throw ReferenceError(`No way to load representation index`);let m;if(s)m=new DataView(u,p.from-a,p.to-p.from+1);else{let t=yield this.fetch(e.url,{range:p,measureThroughput:!1,urlCacheMechanismEnabled:!0});if(!t)return null;m=new DataView(t)}let h=t.parseSegments(m,f,p);return{init:f,dataView:new DataView(u),segments:h}}.bind(this));fetchTemplateRepresentation=Yp(this.abortAllController.signal,async function*(e,t){if(e.type!==`template`)return null;let n=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(n,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(e=>({...e,status:`none`,size:void 0})),dataView:new DataView(r)}:null}.bind(this));async doFetch(e,t,n){let r;if(this.useUrlCacheMechanism&&n?.urlCacheMechanismEnabled&&xm()){r=await bm(e);let t=await r.get();if(t)return t}let i=await Jp(e,r?{...t,cache:`no-store`}:t);if(i.ok)return r?.set(i),i;if(n?.ignoreNetworkErrors)return;let a=await i.text();if(this.handleExtendedNetworkErrorsSet){dm({txtCode:a,httpCode:i.status,error$:this.error$,recoverableError$:this.recoverableError$});return}let o=parseInt(a);if(!isNaN(o))switch(o){case 1:this.recoverableError$.next({id:`VideoDataLinkExpiredError`,message:`Video data links have expired`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:`VideoDataLinkBlockedForFloodError`,message:`Url blocked for flood`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:`VideoDataLinkIllegalIpChangeError`,message:`Client IP has changed`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:`VideoDataLinkIllegalHostChangeError`,message:`Request HOST has changed`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a});break;default:this.error$.next({id:`GeneralVideoDataFetchError`,message:`Generic video data fetch error (${o})`,category:rm.FATAL,httpCode:i.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}}import{isNullable as Om,ValueSubject as km}from"@vkontakte/videoplayer-shared";class Am{currentRepresentation$=new km(null);maxRepresentations=4;representationsCursor=0;representations=[];getCurrentPosition;currentSegment=null;constructor(e,t){this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Om(e))for(let t of this.representations)for(let n of t){let t=n.segmentReference,r=t.segments.length,i=t.segments[0].time.from,a=t.segments[r-1].time.to;if(e<i||e>a)continue;let o=t.segments.find(t=>t.time.from<=e&&t.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...n,label:`Live Text`,language:`ru`,isAuto:!0,url:new URL(o.url,t.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let e=Am.filterRepresentations(t.representations);if(e){this.representations[this.representationsCursor]=e,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(e=>Am.filterRepresentations(e.representations))}static filterRepresentations(e){return e?.filter(e=>e.kind===`text`&&`segmentReference`in e&&Yu(e.segmentReference))}}var jm=[`timeupdate`,`progress`,`play`,`seeked`,`stalled`,`waiting`],Mm=[`timeupdate`,`progress`,`loadeddata`,`playing`,`seeked`];class Nm{element=null;manifestUrlString=``;source=null;manifest=null;tuning;tracer;forceVideoCodec;videoBufferManager;audioBufferManager;bufferManagers=[];liveTextManager;throughputEstimator;subscription=new yp;subscriptionRemovable=new bp;representationSubscription=new yp;fetcher;state$=new Dt(`none`);currentVideoRepresentation$=new W(void 0);currentVideoRepresentationInit$=new W(void 0);currentAudioRepresentation$=new W(void 0);currentVideoSegmentLength$=new W(0);currentAudioSegmentLength$=new W(0);error$=new vp;manifestRequested$=new vp;firstBytesManifest$=new vp;manifestReceived$=new vp;firstBytesRequested$=new vp;firstBytesReceived$=new vp;lastConnectionType$=new W(void 0);lastConnectionReused$=new W(void 0);lastRequestFirstBytes$=new W(void 0);lastConnectionMetrics$=new W(void 0);lastDownloadMetrics$=new W(void 0);currentLiveTextRepresentation$=new W(null);timeoutSourceOpenId;isLive$=new W(!1);isActiveLive$=new W(!1);isLowLatency$=new W(!1);liveDuration$=new W(0);liveSeekableDuration$=new W(0);liveAvailabilityStartTime$=new W(0);liveStreamStatus$=new W(void 0);bufferLength$=new W(0);liveLatency$=new W(void 0);liveLoadBufferLength$=new W(0);livePositionFromPlayer$=new W(0);currentStallDuration$=new W(0);videoLastDataObtainedTimestamp$=new W(0);fetcherRecoverableError$=new vp;fetcherError$=new vp;updateDurationError$=new vp;liveStreamEndTimestamp=0;liveBuffer;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;forceEnded$=new vp;gapWatchdogActive=!1;gapWatchdogSubscription;stallWatchdogSubscription;livePauseWatchdogSubscription;liveWasInterrupted=!1;isOnDemand=!1;dashMaxTvVideoQuality;destroyController=new np;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(`DashProviderPlayer`),this.forceVideoCodec=e.forceVideoCodec,this.isOnDemand=e.isOnDemand,this.dashMaxTvVideoQuality=e.dashMaxTvVideoQuality,this.fetcher=new Dm({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam,handleExtendedNetworkErrorsSet:e.tuning.handleExtendedNetworkErrorsSet,useUrlCacheMechanism:this.tuning.useUrlCacheMechanism,measureNonSegmentRequests:e.tuning.throughputEstimator.measureNonSegmentRequests}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=bf.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}initManifest=ip(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initManifest`),this.element=e,this.manifestUrlString=O(t,n,2),this.state$.startTransitionTo(`manifest_ready`),this.manifest=yield this.updateManifest(),!this.tuning.audioOnly&&!this.manifest?.streams.video.length||this.tuning.audioOnly&&!this.manifest?.streams.audio.length?this.error$.next({id:`NoRepresentations`,category:U.PARSER,message:`No playable video representations`}):this.state$.setState(`manifest_ready`)}.bind(this));updateManifest=ip(this.destroyController.signal,async function*(){this.tracer.log(`updateManifestStart`,{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(e=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:`LoadManifest`,category:U.NETWORK,message:`Failed to load manifest`,thrown:e})});if(!e)return null;let t=null;try{t=Nl(e??``,this.manifestUrlString),this.manifestReceived$.next()}catch(t){let n=Cc(e)??{id:`ManifestParsing`,category:U.PARSER,message:`Failed to parse MPD manifest`,thrown:t};this.error$.next(n)}if(!t)return null;let n=(e,t,n)=>!!(this.element?.canPlayType?.(t)&&Fe()?.isTypeSupported?.(`${t}; codecs="${n}"`)||e===`text`);if(t.live){this.isLive$.next(!0);let{availabilityStartTime:e,latestSegmentPublishTime:n,streamIsUnpublished:r,streamIsAlive:i}=t.live,a=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*a),this.liveDuration$.next((n-e)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let o=`active`;if(i||(o=r?`unpublished`:`unexpectedly_down`),this.liveStreamStatus$.next(o),i&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let e=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(e).catch(e=>{this.error$.next({id:`updateManifest`,category:U.VIDEO_PIPELINE,message:`seekLive after stream restore failed`,thrown:e})})}}let r={text:t.streams.text,video:[],audio:[]},i,a;for(let e of[`video`,`audio`]){let o=t.streams[e],s=this.tuning.dash.checkRepresentationCanPlayType&&this.element?Ud(o,this.element,this.tuning.dash.checkRepresentationCanPlayType):o.filter(({mime:t,codecs:r})=>n(e,t,r));r[e]=s;let c,l;if(this.tuning.dash.codecsPrioritizeEnabled){if(e===`audio`)a=ca(s.map(({codecs:e})=>e)),c=a[0],c&&(r[e]=s.filter(({codecs:e})=>la(e)===c));else if(e===`video`){i=oa(s,{preferHdr:this.tuning.preferHDR});let t=this.forceVideoCodec;l=(t?i.find(e=>e.name===t.name&&e.hdr===t.hdr):void 0)??i[0],l&&(r[e]=s.filter(e=>la(e.codecs)===l.name&&!!e.hdr===l.hdr))}}else{let t=aa(new Set(s.map(({codecs:e})=>e)));t&&(r[e]=s.filter(({codecs:e})=>e.startsWith(t)))}if(e===`video`){if(!this.tuning.dash.codecsPrioritizeEnabled){let e=this.tuning.preferHDR,t=r.video.some(e=>e.hdr),n=r.video.some(e=>!e.hdr);A.display.isHDR&&e&&t?r.video=r.video.filter(e=>e.hdr):n&&(r.video=r.video.filter(e=>!e.hdr))}let{videoStreamRepresentaionsFilter:e}=this.tuning.dash;if(e.length&&fa(r,e),this.dashMaxTvVideoQuality&&Vd(r,this.dashMaxTvVideoQuality),this.isOnDemand&&this.tuning.dash.filterOnDemandQualityList)for(let e of r.video)e.representations=e.representations.sort((e,t)=>t.height-e.height).filter((e,t)=>t%2==0)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:i,audio:a}),this.tracer.log(`updateManifestEnd`,lp(o)),o}.bind(this));setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ap(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`?0:_p()-this.liveStreamEndTimestamp,n=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(n===0),this.manifestUrlString=O(this.manifestUrlString,n,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)}initRepresentations=ip(this.destroyController.signal,async function*(e,t,n){this.tracer.log(`initRepresentationsStart`,lp({initialVideo:e,initialAudio:t,sourceHls:n})),ap(this.manifest),ap(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(`representations_ready`);let r=e=>{this.representationSubscription.add(up(e,`error`).pipe(sp(e=>!!this.element?.played.length)).subscribe(e=>{this.error$.next({id:`VideoSource`,category:U.VIDEO_PIPELINE,message:`Unexpected video source error`,thrown:e})}))};this.source=Re();let i=document.createElement(`source`);if(r(i),i.src=URL.createObjectURL(this.source),this.element.appendChild(i),Ie())if(n){let e=document.createElement(`source`);r(e),e.type=`application/x-mpegurl`,e.src=n.url,this.element.appendChild(e)}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};if(this.bufferManagers=[],pp(e)){let e=this.manifest.streams.video.reduce((e,t)=>[...e,...t.representations],[]);e.length&&(this.videoBufferManager=new Kp(`video`,this.source,e,a),this.bufferManagers.push(this.videoBufferManager))}if(pp(t)){let e=this.manifest.streams.audio.reduce((e,t)=>[...e,...t.representations],[]);this.audioBufferManager=new Kp(`audio`,this.source,e,a),this.bufferManagers.push(this.audioBufferManager)}if(Am.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Am(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(gp(...Mm.map(e=>up(this.element,e))).pipe(hp(e=>this.element?kd(this.element.buffered,this.element.currentTime*1e3):0),cp(),xp(e=>{e>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(gp(up(this.element,`ended`),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(cp()).subscribe(e=>this.liveStreamEndTimestamp=_p())),this.subscription.add(up(this.element,`pause`).subscribe(()=>{let{liveUpdateInterval:e}=this.tuning.dash;this.livePauseWatchdogSubscription=fp(e).subscribe(t=>{let n=me(this.manifestUrlString,2);this.manifestUrlString=O(this.manifestUrlString,n+e,2),this.liveStreamStatus$.getValue()===`active`&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(up(this.element,`play`).subscribe(e=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(op({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hp(({isActiveLive:e,isLowLatency:t})=>e&&t),cp()).subscribe(e=>{this.isManualDecreasePlaybackInLive()||Nf(this.element,1)})),this.representationSubscription.add(op({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(sp(({bufferLength:e,isActiveLive:t,isLowLatency:n})=>t&&n&&!!e)).subscribe(({bufferLength:e})=>this.liveBuffer.next(e))),this.videoBufferManager&&(this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(e=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!e)return;let t=this.liveSeekableDuration$.getValue()-e/1e3;this.liveSeekableDuration$.next(Math.max(t,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+e/1e3)})),this.representationSubscription.add(op({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(sp(({isLive:e})=>e),cp((e,t)=>t.bufferLength<e.bufferLength),hp(({rtt:e,bufferLength:t,segmentServerLatency:n})=>{let r=me(this.manifestUrlString,2);return(e/2+t+n+r)/1e3})).subscribe(this.liveLatency$))),this.representationSubscription.add(op({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:e,isActiveLive:t,isLowLatency:n})=>{if(!n||!t)return;let r=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,i=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,a=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,o=e-r;if(this.isManualDecreasePlaybackInLive())return;let s=1;Math.abs(o)>i&&(s=1+Math.sign(o)*a),Nf(this.element,s)})),this.representationSubscription.add(this.bufferLength$.subscribe(e=>{let t=0;if(e){let e=(this.element?.currentTime??0)*1e3;t=Math.min(...this.bufferManagers.map(t=>t.getLiveSegmentsToLoadState(this.manifest)?.to??e))-e}this.liveLoadBufferLength$.getValue()!==t&&this.liveLoadBufferLength$.next(t)}));let e=0;this.representationSubscription.add(op({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Sp(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:t,bufferLength:n})=>{if(!this.element||this.isUpdatingLive)return;let r=this.element.playbackRate,i=me(this.manifestUrlString,2),a=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,o=Math.min(a,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*r),s=this.tuning.dashCmafLive.normalizedActualBufferOffset*r,c=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*r,l=isFinite(t)?t:n,u=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),d=a<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(d);let f=`none`;if(u?f=`active_low_latency`:this.isLowLatency$.getValue()&&d?(this.bufferManagers.forEach(e=>e.proceedLowLatencyLive()),f=`active_low_latency`):i!==0&&l<o?f=`live_forward_buffering`:l<o+c&&(f=`live_with_target_offset`),isFinite(t)&&(e=t>e?t:e),f===`live_forward_buffering`||f===`live_with_target_offset`){let n=e-(o+s),a=this.normalizeLiveOffset(Math.trunc(i+n/r)),c=Math.abs(a-i),l=0;!t||c<=this.tuning.dashCmafLive.offsetCalculationError?l=i:a>0&&c>this.tuning.dashCmafLive.offsetCalculationError&&(l=a),this.manifestUrlString=O(this.manifestUrlString,l,2)}(f===`live_with_target_offset`||f===`live_forward_buffering`)&&(e=0,await this.updateLive())},e=>{this.error$.next({id:`updateLive`,category:U.VIDEO_PIPELINE,thrown:e,message:`Failed to update live with subscription`})}))}let o=op({allBuffersFull:gp(...this.bufferManagers.map(e=>e.fullyBuffered$)).pipe(hp(()=>this.bufferManagers.every(e=>e.fullyBuffered$.getValue()))),someBufferEnded:gp(...this.bufferManagers.map(e=>e.onLastSegment$)).pipe(hp(()=>this.bufferManagers.some(e=>e.onLastSegment$.getValue())))}).pipe(cp(),hp(({allBuffersFull:e,someBufferEnded:t})=>e&&t),sp(e=>e));if(this.representationSubscription.add(gp(this.forceEnded$,o).subscribe(()=>{if(this.source&&this.source.readyState===`open`&&Array.from(this.source.sourceBuffers).every(e=>!e.updating))try{this.source?.endOfStream()}catch(e){this.error$.next({id:`EndOfStream`,category:U.VIDEO_PIPELINE,message:`Failed to end MediaSource stream`,thrown:e})}})),this.representationSubscription.add(gp(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),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.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!==`open`){let e=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(t=>{e&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState===`open`){t();return}this.error$.next({id:`OpenOfStream`,category:U.VIDEO_PIPELINE,message:`Failed to open MediaSource`,thrown: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})})}if(!this.isLive$.getValue()){let e=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(e=>e.representations).flatMap(e=>{let t=[];return e.duration&&t.push(e.duration),Yu(e.segmentReference)&&e.segmentReference.totalSegmentsDurationMs&&t.push(e.segmentReference.totalSegmentsDurationMs),t})];this.source.duration=Math.max(...e)/1e3}let s=[];this.videoBufferManager&&pp(e)&&s.push(this.videoBufferManager.startWith(e)),this.audioBufferManager&&pp(t)&&s.push(this.audioBufferManager.startWith(t)),yield Promise.all(s),this.state$.setState(`representations_ready`),this.tracer.log(`initRepresentationsEnd`)}.bind(this));initBuffer(){ap(this.element),this.state$.setState(`running`),this.subscription.add(gp(...jm.map(e=>up(this.element,e)),up(window,`online`)).subscribe(()=>this.tick(),e=>{this.error$.next({id:`DashVKPlayer`,category:U.WTF,message:`Internal logic error`,thrown:e})})),this.subscription.add(up(this.element,`progress`).subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(up(this.element,`waiting`).subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&rp(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:e}=this.tuning.dashCmafLive,{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:n,liveStallReinitInterval:r,stallWatchdogInterval:i}=this.tuning.dash,a=this.isLive$.getValue(),o=this.liveStreamStatus$.getValue()===`active`;if(!this.element||this.source?.readyState!==`open`)return;let s=this.currentStallDuration$.getValue();s+=i,this.currentStallDuration$.next(s);let c={timeInWaiting:s},l=_p(),u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let d=this.audioBufferManager?.lastDataObtainedTimestamp??0,f=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,m=this.videoBufferManager&&f<100&&l-u>n,h=this.audioBufferManager&&p<100&&l-d>n;if((!e||o)&&((m||h)&&s>n||s>=t))throw Error(`Stall timeout exceeded: ${s} ms`);if(a&&s%r===0){let t=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!o&&e?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(t),this.updateManifest()):this.seekLive(t).catch(e=>{this.error$.next({id:`stallIntervalCallback`,category:U.VIDEO_PIPELINE,message:`stallIntervalCallback failed`,thrown:e})}),c.liveLastOffset=t}else{let e=this.element.currentTime*1e3;this.videoBufferManager?.maintain(e),this.audioBufferManager?.maintain(e),c.position=e}this.tracer.log(`stallIntervalCallback`,lp(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=fp(this.tuning.dash.stallWatchdogInterval).subscribe(e,e=>{this.error$.next({id:`StallWatchdogCallback`,category:U.NETWORK,message:`Can't restore DASH after stall.`,thrown:e})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,n=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.alwaysAbortPreviousSwitch?r?.switchToWithPreviousAbort(t,n):this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,n):r?.switchTo(t,n):r?.switchToOld(t,n)}async seek(e,t){ap(this.element),this.tuning.audioOnly?ap(this.audioBufferManager):ap(this.videoBufferManager);let n;n=t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(this.videoBufferManager?.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(n),rp(this.element.buffered,n)||await Promise.all([this.videoBufferManager?.abort(),this.audioBufferManager?.abort()]),!mp(this.element)&&(this.videoBufferManager?.maintain(n),this.audioBufferManager?.maintain(n),this.element.currentTime=n/1e3,this.tracer.log(`seek`,lp({requestedPosition:e,forcePrecise:t,position:n})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){pp(this.element)&&pp(this.source)&&pp(e)&&this.source?.readyState===`ended`&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(e=>e.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`)}getForwardBufferRepresentations(e){return e===`video`?this.videoBufferManager?.getForwardBufferRepresentations():this.audioBufferManager?.getForwardBufferRepresentations()}getActiveVideoSegmentProgress(){return this.videoBufferManager?.getActiveSegmentProgress()}getMpdVideoSegmentDuration(){return this.videoBufferManager?.getMpdSegmentDuration()}setBufferTarget(e,t){this.videoBufferManager?.setTarget(e),this.audioBufferManager?.setTarget(t)}getVideoForwardBufferDuration(){return this.videoBufferManager?.getForwardBufferDuration()??0}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=dp(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}tick=()=>{if(!this.element||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=fp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),e=>{this.error$.next({id:`GapWatchdog`,category:U.WTF,message:`Error handling gaps`,thrown:e})}),this.subscription.add(this.gapWatchdogSubscription))};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(),n={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 i=this.element.currentTime*1e3,a=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let e of this.bufferManagers)for(let t of e.gaps)(r&&t.persistent||e.playingRepresentation$.getValue()===t.representation)&&t.from-o<=i&&t.to+o>i&&(this.element.duration*1e3-t.to<this.tuning.endGapTolerance?a.push(1/0):a.push(t.to));if(a.length){let e=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,e===1/0?this.forceEnded$.next():(this.element.currentTime=e/1e3,n={...n,gapEnds:a,jumpTo:e,resultCurrentTime:this.element.currentTime},this.tracer.log(`jumpGap`,lp(n)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}isAnyBufferUpdating(){return!this.source||this.source.readyState!==`open`?!1:Array.from(this.source.sourceBuffers).some(e=>e.updating)}updateSourceDurationFromSegments(){if(!this.source||this.source.readyState!==`open`||this.isLive$.getValue()||!this.tuning.useDurationFromSegments)return;let e=e=>{this.updateDurationError$.next({id:`updateDuration`,category:U.VIDEO_PIPELINE,message:"Duration can`t be updated",thrown:e})};try{if(!this.isAnyBufferUpdating()){this.source.duration=this.calculateDurationFromSegments()/1e3;return}}catch(t){e(t);return}let t=new yp;t.add(gp(...this.bufferManagers.map(e=>e.updateEnd$)).subscribe(()=>{if(!this.isAnyBufferUpdating()){t.unsubscribe();try{this.source&&(this.source.duration=this.calculateDurationFromSegments()/1e3)}catch(t){e(t)}}}))}}class Pm{scene3D;subscription=new $f;volumeSubscription=new $f;videoState=new Dt(`stopped`);allocation;observableVideo=null;player;params;tracer;textTracksManager=null;droppedFramesManager=new qi;stallsManager=new _o;elementSizeManager=new wo;abrManager=new mc;failedVideoTrack;videoTracksMap=new Map;audioTracksMap=new Map;textTracksMap=new Map;videoStreamsMap=new Map;audioStreamsMap=new Map;videoTrackSwitchHistory=new Or;audioTrackSwitchHistory=new Or;constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn(e.source.url)),this.params=e,this.allocation=va(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(`dashProvider`),this.params.output.element$.next(this.allocation.video??void 0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Wr(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 Nm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec,isOnDemand:this.params.isOnDemand||!1,dashMaxTvVideoQuality:this.params.dashMaxTvVideoQuality}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Jf(this.observableVideo)&&(this.observableVideo=Qn(this.allocation.target),this.subscription.add(()=>this.observableVideo?.destroy()));let n=this.constructor.name,r=t=>{e.error$.next({id:n,category:Uf.WTF,message:`${n} internal logic error`,thrown:t})};return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:(e,t)=>this.subscription.add(e.subscribe(t,r))}}subscribe(){let{output:e,desiredState:t,observableVideo:n,genericErrorListener:r,connect:i}=this.getProviderSubscriptionInfo();qf(this.params.failedVideoTrack)&&(this.failedVideoTrack=this.params.failedVideoTrack,this.subscription.add(tp(this.params.tuning.dash.videoTrackBanAfterProviderFail).subscribe(()=>this.failedVideoTrack=null)));let a=this.allocation.video;a&&this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wf(e=>!!e.length),Qf()).subscribe(e=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:a,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e})}));let o=this.params.desiredState.seekState.stateChangeEnded$.pipe(Yf(e=>e.to.state!==`none`),Gf());this.abrManager.init({isSeeked$:o,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,throughputVariance$:this.params.dependencies.throughputEstimator.throughputVariance$,tuning:this.params.tuning,failedVideoTrack:this.params.failedVideoTrack,element:this.allocation.target,abrLogger:this.params.dependencies.abrLogger}),this.stallsManager.init({isSeeked$:o,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$:n.isBuffering$,looped$:n.looped$,playing$:n.playing$,duration:this.allocation.target.duration}),i(n.ended$,e.endedEvent$),i(n.looped$,e.loopedEvent$),i(n.error$,e.error$),i(n.isBuffering$,e.isBuffering$),i(n.currentBuffer$,e.currentBuffer$),i(n.currentBuffer$,e.currentNativeBuffer$),i(n.totalBufferDuration$,e.totalBufferDuration$),i(n.bufferRangeCount$,e.bufferRangeCount$),i(n.playing$,e.firstFrameEvent$),i(n.canplay$,e.canplay$),i(n.playedTime$,e.playedTime$),i(n.inPiP$,e.inPiP$),i(n.inFullscreen$,e.inFullscreen$),i(n.loadedMetadata$,e.loadedMetadataEvent$),i(this.player.error$,e.error$),i(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),i(this.player.updateDurationError$,e.updateDurationError$),i(this.player.fetcherError$,e.fetcherError$),i(this.player.videoLastDataObtainedTimestamp$,e.videoLastDataObtainedTimestamp$),i(this.player.manifestRequested$,e.manifestRequested$),i(this.player.firstBytesManifest$,e.firstBytesManifest$),i(this.player.manifestReceived$,e.manifestReceived$),i(this.player.firstBytesRequested$,e.firstBytesRequested$),i(this.player.firstBytesReceived$,e.firstBytesReceived$),i(this.player.lastConnectionType$,e.httpConnectionType$),i(this.player.lastConnectionReused$,e.httpConnectionReused$),i(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),i(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),i(this.player.isLive$,e.isLive$),i(this.player.lastRequestFirstBytes$.pipe(Wf(qf),Qf()),e.firstBytesEvent$),i(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),i(this.videoState.stateChangeEnded$.pipe(Yf(e=>e.to)),this.params.output.playbackState$),this.subscription.add(n.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wn(this.allocation.target,t.isLooped,r)),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),r)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,r))})),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:n}),this.subscription.add(Tn(this.allocation.target,t.volume,n.volumeState$,r,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(En(this.allocation.target,t.playbackRate,n.playbackRateState$,r)),this.allocation.video&&this.elementSizeManager.connect({video:this.allocation.video,observableVideo:n}),i(Qi(this.allocation.target,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(n.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`),this.scene3D&&this.scene3D.play()},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},r)).add(n.canplay$.subscribe(()=>{this.videoState.getState()===`playing`&&!this.allocation.target.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(n.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:e})=>{if(e===`manifest_ready`){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let e=this.player.getStreams(),t=this.player.getCodecs();if(Bf(e,`Manifest not loaded or empty`),!this.params.tuning.isAudioDisabled){let t=[];for(let n of e.audio){t.push(Ku(n));let e=[];for(let t of n.representations){let r=Uu(t);e.push(r),this.audioTracksMap.set(r,{stream:n,representation:t})}this.audioStreamsMap.set(n,e)}this.params.output.availableAudioStreams$.next(t)}let n=[];for(let t of e.video){n.push(qu(t));let e=[];for(let n of t.representations){let r=Hu({...n,streamId:t.id});r&&(e.push(r),this.videoTracksMap.set(r,{stream:t,representation:n}))}this.videoStreamsMap.set(t,e)}this.params.output.availableVideoStreams$.next(n);for(let t of e.text)for(let e of t.representations){let n=Wu(t,e);this.textTracksMap.set(n,{stream:t,representation:e})}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),t?.video&&this.params.output.availableVideoCodecs$.next(t.video),t?.audio&&this.params.output.availableAudioCodecs$.next(t.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else e===`representations_ready`&&(this.videoState.setState(`ready`),this.player.initBuffer())},r));let s=Xf(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$,Kf(this.allocation.target,`progress`)).pipe(Wf(()=>this.videoTracksMap.size>0||this.params.tuning.audioOnly&&this.audioTracksMap.size>0)),{abrThrottle:c}=this.params.tuning.dash;c&&(s=s.pipe(ep(c))),this.subscription.add(s.subscribe(async()=>{let e=this.player.state$.getState(),n=this.player.state$.getTransition();if(e!==`manifest_ready`&&e!==`running`||n)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let r=this.selectVideoAudioRepresentations();if(!r){if(this.params.tuning.audioOnly&&this.audioStreamsMap.size){let[,[t]]=this.audioStreamsMap.entries().next().value;e===`manifest_ready`&&await this.player.initRepresentations(void 0,t.id,this.params.sourceHls)}return}let[i,a]=r,o=[...this.videoTracksMap.keys()].find(e=>this.videoTracksMap.get(e)?.representation.id===i.id);qf(o)&&(this.stallsManager.lastVideoTrackSelected=o);let s=this.params.desiredState.autoVideoTrackLimits.getTransition();if(s&&this.params.output.autoVideoTrackLimits$.next(s.to),e===`manifest_ready`)await this.player.initRepresentations(i.id,a?.id,this.params.sourceHls);else if(await this.player.switchRepresentation(`video`,i.id),a){let e=!!t.audioStream.getTransition();await this.player.switchRepresentation(`audio`,a.id,e)}},r)),this.subscription.add(Vf({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Xf(Zf([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Yf(e=>e.to)))}).pipe(Yf(({videoState:e,autoVideoTrackState:t})=>e.to!==`stopped`&&t),Gf()).subscribe(e=>this.player.setSmartRepresentationSwitch(e))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:e})=>{this.scene3D&&e&&this.scene3D.pointCameraTo(e.x,e.y)})),this.subscription.add(this.elementSizeManager.subscribe(e=>{this.scene3D&&e&&this.scene3D.setViewportSize(e.width,e.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Gf()).subscribe(t=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.videoStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.videoStream.setState(a.to),e.currentVideoTrack$.next(r),e.currentVideoStream$.next(qu(i)),this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Gf()).subscribe(t=>{let n=[...this.audioTracksMap.entries()].find(([,{representation:e}])=>e.id===t);if(!n){e.currentAudioStream$.next(void 0);return}let[r,{stream:i}]=n,a=this.params.desiredState.audioStream.getTransition();a&&a.to&&a.to.id===i.id&&this.params.desiredState.audioStream.setState(a.to),e.currentAudioStream$.next(Ku(i)),this.player.updateSourceDurationFromSegments()},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(t=>{if(t?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(t),e.is3DVideo$.next(!0)}catch(t){e.warning$.next({id:`DashProvider`,message:`DashProvider could not initialize 3D-scene: ${t}`})}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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Yf(({to:e})=>e===`ready`),Gf()),u=[l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Zf([`init`])];this.params.tuning.dash.useDynamicBufferTarget&&u.push(this.params.dependencies.throughputEstimator.throughput$,e.currentVideoTrack$,n.currentBuffer$),this.subscription.add(Xf(...u).subscribe(()=>this.syncBufferTarget())),this.subscription.add(Xf(l,this.player.state$.stateChangeEnded$,Zf([`init`])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===`ready`)));let d=Xf(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Zf([`init`])).pipe(Hf(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}syncBufferTarget(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.playbackState.getState()===`ready`,n=this.resolveBufferTargetMs(e,t);this.player.setBufferTarget(n,this.resolveAudioBufferTargetMs(e,t))}resolveAudioBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?Math.min(this.player.getVideoForwardBufferDuration()+n.audioBufferAheadOfVideoMs,n.forwardBufferTargetAuto):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}resolveBufferTargetMs(e,t){let{dash:n}=this.params.tuning;return t?n.forwardBufferTargetPreload:e?n.useDynamicBufferTarget?yc({throughputKbps:this.params.dependencies.throughputEstimator.throughput$.getValue(),currentBitrateKbps:this.getCurrentVideoBitrateKbps(),baseTargetMs:n.forwardBufferTargetAuto},n.dynamicBufferTarget):n.forwardBufferTargetAuto:n.forwardBufferTargetManual}getCurrentVideoBitrateKbps(){let e=this.params.output.currentVideoTrack$.getValue();if(Jf(e))return null;let t=this.player.getForwardBufferRepresentations(`video`)?.get(e.id),n=Go(t);return isFinite(n)?n:e.bitrate}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pr:Nr,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Hr,n=this.params.tuning.useNewAutoSelectVideoTrack?Br:Vr,{desiredState:r,output:i}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:e})=>e===o),c=i.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:e})=>e===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let f=kd(this.allocation.target.buffered,this.allocation.target.currentTime*1e3),p;p=this.player.isActiveLive$.getValue()?this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.allocation.target.duration*1e3||1/0)-this.allocation.target.currentTime*1e3,h=Math.min(f/Math.min(p,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),_=[...this.audioStreamsMap.keys()].find(({id:e})=>e===g?.id)??this.audioStreamsMap.keys().next().value,v=0;if(_){if(s&&!a){let t=e(s,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}if(c){let t=e(c,d,this.audioStreamsMap.get(_)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,t?.bitrate??-1/0)}}let y=this.player.isLive$.getValue(),b=this.allocation.target.duration*1e3,x=!y&&Number.isFinite(b)&&b>0?Math.max(0,b-this.allocation.target.currentTime*1e3):void 0,S=this.params.tuning.dash.useAbrPhases?{isLive:y,remainingDurationMs:x,mpdSegmentDurationMs:this.player.getMpdVideoSegmentDuration()}:{};this.abrManager.updateContext({isAuto:a,videoTracks:d,audioTracks:_?this.audioStreamsMap.get(_)??[]:[],currentVideoTrack:c,desiredVideoTrack:s,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:h,forwardBufferDuration:f,forwardBufferTarget:p,forwardVideoBufferRepresentations:this.player.getForwardBufferRepresentations(`video`),forwardAudioBufferRepresentations:this.player.getForwardBufferRepresentations(`audio`),videoSegmentLoadProgress:this.player.getActiveVideoSegmentProgress(),...S});let C=s,w;this.params.tuning.dash.useNewAbr?(C=this.abrManager.autoSelectTrack(`video`),w=_&&this.abrManager.autoSelectTrack(`audio`)):((a||!C)&&(C=n(d,{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:v,forwardBufferHealth:h,current:c,failedVideoTrack:this.failedVideoTrack,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger})),w=_&&t(C,d,this.audioStreamsMap.get(_)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.allocation.target.playbackRate,abrLogger:this.params.dependencies.abrLogger}));let T=this.videoTracksMap.get(C)?.representation,E=w&&this.audioTracksMap.get(w)?.representation;if(T&&E)return[T,E];if(T&&!E&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.allocation.target,this.params.source.url,e)}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===`requested`&&n?.to!==`paused`&&e!==`stopped`&&t!==`stopped`&&this.seek(r.position,r.forcePrecise),t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.player.stop(),this.allocation.target.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`),k(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`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`ready`&&k(this.params.desiredState.playbackState,`ready`);return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):t===`playing`&&this.allocation.target.paused?this.playIfAllowed():n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return zf(e)}}};init3DScene=e=>{if(this.scene3D)return;let t=this.params.container,n=this.allocation.video;if(!t||!n)return;this.scene3D=new eo(t,n,{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 r=this.elementSizeManager.getValue();r&&this.scene3D.setViewportSize(r.width,r.height)};destroy3DScene=()=>{this.scene3D&&=(this.scene3D.destroy(),void 0)};playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:Uf.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Zf(e).subscribe(t,n)):e.then(t,n)}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.abrManager.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),on(this.allocation.target,this.params.tuning),this.tracer.end()}}class Fm extends Pm{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:n}=this.getProviderSubscriptionInfo();n(t.timeUpdate$,e.position$),n(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}import{combine as Im,merge as Lm,filter as Rm,filterChanged as zm,isNullable as Bm,map as Vm,ValueSubject as Hm,isNonNullable as Um}from"@vkontakte/videoplayer-shared";class Wm extends Pm{constructor(e){super(e),this.textTracksManager?.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:n,observableVideo:r,desiredState:i,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$,n.liveBufferTime$),a(this.player.liveSeekableDuration$,n.duration$),a(this.player.liveLatency$,n.liveLatency$);let o=new Hm(1);a(r.playbackRateState$,o),(this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab||this.params.tuning.live.catchupLiveForMutedInactiveTab)&&this.subscription.add(n.elementVisible$.pipe(zm()).subscribe(t=>{let r=n.position$.getValue(),i=n.volume$.getValue(),a=!i.volume||i.muted;!t&&!r&&a?e=!0:t&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(Vm(e=>e.to)).subscribe(this.player.isLowLatency$)).add(Im({liveBufferTime:n.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Vm(({liveBufferTime:e,liveAvailabilityStartTime:n})=>e&&n?e*1e3+n+t:void 0)).subscribe(n.liveTime$)).add(Im({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Lm(r.playbackRateState$,new Hm(1))}).pipe(Rm(({liveStreamStatus:e,liveDuration:t})=>e===`active`&&!!t)).subscribe(({liveDuration:e,playbackRate:r})=>{let i=n.liveBufferTime$.getValue(),a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;a||r<1-o||this.allocation.target.paused||Bm(i)||(t=e-i)})).add(Im({time:n.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Lm(r.playbackRateState$,new Hm(1))}).pipe(zm((e,t)=>this.player.liveStreamStatus$.getValue()===`active`?e.liveDuration===t.liveDuration:e.time===t.time)).subscribe(({time:e,liveDuration:r,playbackRate:i})=>{let a=n.position$.getValue(),{playbackCatchupSpeedup:o}=this.params.tuning.dashCmafLive.lowLatency;if(!a&&!this.allocation.target.paused&&i>=1-o||Bm(e)||Bm(r))return;let s=-1*(r-e-t);n.position$.next(Math.min(s,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(e=>{if(e){let t=Gu(e);this.params.output.availableTextTracks$.next([t])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Rm(e=>Um(e))).subscribe(e=>n.isLiveEnded$.next(e===`unpublished`&&n.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,n=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3)})}}import{fetchPolyfilled as Gm}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as Km}from"@vkontakte/videoplayer-shared";var qm=`X-Playback-Duration`,Jm=async e=>{let t=await Km(e),n=await t.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(n)?.[1];return r?parseInt(r,10):t.headers.has(qm)?parseInt(t.headers.get(qm),10):void 0};import{assertNever as Ym,combine as Xm,debounce as Zm,ErrorCategory as Qm,filter as $m,filterChanged as eh,isNonNullable as th,isNullable as nh,map as rh,merge as ih,observableFrom as ah,Subscription as oh,ValueSubject as sh,VideoQuality as ch}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as lh}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as uh,getExponentialDelay as dh}from"@vkontakte/videoplayer-shared";var fh=e=>{let t=null;if(e.QUALITY&&(t=er(e.QUALITY)),!t&&e.RESOLUTION){let[n,r]=e.RESOLUTION.split(`x`).map(e=>parseInt(e,10));t=uh({width:n,height:r})}return t??null},ph=(e,t,n=!1)=>{let r=e.split(`
|
|
255
255
|
`),i=[],a=[],o=[];for(let e=0;e<r.length;e++){let s=r[e],c=s.match(/^#EXT-X-STREAM-INF:(.+)/),l=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/),u=n&&s.match(/^#EXT-X-MEDIA:TYPE=AUDIO,(.+)/);if(!(!c&&!l&&!u)){if(c){let n=Object.fromEntries(c[1].split(`,`).map(e=>e.split(`=`))),a=n.QUALITY??`stream-${n.BANDWIDTH}`,o=fh(n),s;n.BANDWIDTH&&(s=parseInt(n.BANDWIDTH,10)/1e3||void 0),!s&&n[`AVERAGE-BANDWIDTH`]&&(s=parseInt(n[`AVERAGE-BANDWIDTH`],10)/1e3||void 0);let l=n[`FRAME-RATE`]?parseFloat(n[`FRAME-RATE`]):void 0,u;if(n.RESOLUTION){let[e,t]=n.RESOLUTION.split(`x`).map(e=>parseInt(e,10));e&&t&&(u={width:e,height:t})}let d=new URL(r[++e],t).toString();o&&i.push({id:a,quality:o,url:d,bandwidth:s,size:u,fps:l})}if(l){let e=Object.fromEntries(l[1].split(`,`).map(e=>{let t=e.indexOf(`=`);return[e.substring(0,t),e.substring(t+1)]}).map(([e,t])=>[e,t.replace(/^"|"$/g,``)])),t=e.URI?.replace(/playlist$/,`subtitles.vtt`),n=e.LANGUAGE,r=e.NAME;t&&n&&a.push({type:`internal`,id:n,label:r,language:n,url:t,isAuto:!1})}if(u){let e=Object.fromEntries(u[1].split(`,`).map(e=>{let t=e.indexOf(`=`);return[e.substring(0,t),e.substring(t+1)]}).map(([e,t])=>[e,t.replace(/^"|"$/g,``)])),n=e.URI?new URL(e.URI,t).toString():void 0,r=e.LANGUAGE,i=e.NAME,a=e[`GROUP-ID`],s=e.DEFAULT===`YES`,c=e.CHANNELS?parseInt(e.CHANNELS,10):void 0;n&&r&&o.push({type:`internal`,id:a??r,url:n,language:r,label:i,isDefault:s,channels:c})}}}return{qualityManifests:i,textTracks:a,audioStreams:o}},mh=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),hh=0,gh=async(e,t=e,n,r)=>{let i=await(await lh(e,r)).text();hh+=1;try{let{qualityManifests:e,textTracks:r,audioStreams:a}=ph(i,t,n.audioOnly);if(!n.audioOnly&&!e.length||n.audioOnly&&!a.length)throw Error(`Empty manifest`);return{qualityManifests:e,textTracks:r,audioStreams:a}}catch{if(hh<=n.manifestRetryMaxCount)return await mh(dh(hh-1,{start:n.manifestRetryInterval,max:n.manifestRetryMaxInterval})),gh(e,t,n)}return{qualityManifests:[],textTracks:[],audioStreams:[]}},_h=gh;import{AbortControllerPolyfilled as vh}from"@vkontakte/videoplayer-shared";import{fetchPolyfilled as yh}from"@vkontakte/videoplayer-shared";import{isNonNullable as bh,Subscription as xh,throttle as Sh,ValueSubject as Ch,Subject as wh,ErrorCategory as Th}from"@vkontakte/videoplayer-shared";class Eh{params;subscription=new xh;abortControllers={destroy:new vh,nextManifest:null};prepareUrl=void 0;currentTextTrackData=null;availableTextTracks$=new Ch(null);getCurrentTime$=new Ch(null);error$=new wh;constructor(e,t,n,r,i){this.params={fetchManifestData:n,sourceUrl:r,downloadThreshold:i},this.subscription.add(e.pipe(Sh(1e3)).subscribe(e=>{this.processLiveTime(e)})),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:n}=await this.fetchManifestData();await this.processTextTracks(n,this.params.sourceUrl)}catch(e){this.error(`prepare`,e)}}async processTextTracks(e,t){try{let n=await this.parseTextTracks(e,t);n&&(this.currentTextTrackData=n)}catch(e){this.error(`processTextTracks`,e)}}async parseTextTracks(e,t){for(let n of e){let e=new URL(n.url,t).toString(),r=await(await yh(e,{signal:this.abortControllers.destroy.signal})).text();return{textTrack:n,playlist:this.parsePlaylist(r,e)}}}parsePlaylist(e,t){let n={mediaSequence:0,programDateTime:``,segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:``},r=e.split(`
|
|
256
256
|
`),i=0;for(let e=0;e<r.length;++e){let a=r[e];switch(!0){case a.startsWith(`#EXTINF:`):{let o=r[++e],s=new URL(o,t).toString(),c=Number(this.extractPlaylistRowValue(`#EXTINF:`,a))*1e3;if(n.segments.push({time:{from:i,to:i+c},url:s}),i+=c,!n.segmentStartTime){let e=new Date(n.vkStartTime).valueOf();n.segmentStartTime=new Date(n.programDateTime).valueOf()-e}break}case a.startsWith(`#EXT-X-TARGETDURATION:`):n.targetDuration=Number(this.extractPlaylistRowValue(`#EXT-X-TARGETDURATION:`,a));break;case a.startsWith(`#EXT-X-MEDIA-SEQUENCE:`):n.mediaSequence=Number(this.extractPlaylistRowValue(`#EXT-X-MEDIA-SEQUENCE:`,a));break;case a.startsWith(`#EXT-X-VK-PLAYBACK-DURATION:`):n.vkPlaybackDuration=Number(this.extractPlaylistRowValue(`#EXT-X-VK-PLAYBACK-DURATION:`,a));break;case a.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`):{let e=this.extractPlaylistRowValue(`#EXT-X-PROGRAM-DATE-TIME:`,a);n.programDateTime=e;let t=new Date(e);t.setMilliseconds(0),i=t.valueOf();break}case a.startsWith(`#EXT-X-VK-START-TIME:`):n.vkStartTime=this.extractPlaylistRowValue(`#EXT-X-VK-START-TIME:`,a);break}}return n}extractPlaylistRowValue(e,t){switch(e){case`#EXTINF:`:return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(bh(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:n}=t[0].time,{to:r}=t[t.length-1].time;if(e<n||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new vh;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:Th.WTF,thrown:t,message:e})}}class Dh{subscription=new oh;volumeSubscription=new oh;videoState=new Dt(`stopped`);allocation;params;textTracksManager=null;liveTextManager=null;masterManifest;manifests$=new sh([]);maxSeekBackTime$;liveOffset=new Mn;manifestStartTime$=new sh(void 0);constructor(e){this.params=e,this.allocation=va(e.container,e.tuning),this.params.output.element$.next(this.allocation.video??void 0),this.masterManifest={id:`master`,quality:ch.INVARIANT,url:this.params.source.url};let t=(e,t)=>_h(e,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,audioOnly:this.params.tuning.audioOnly},t);this.allocation.video&&!e.tuning.disableSubtitles&&(this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Eh(this.params.output.liveTime$,this.allocation.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new jn(e.source.url)),t(this.generateLiveUrl()).then(({qualityManifests:e,textTracks:t})=>{e.length===0&&this.params.output.error$.next({id:`HlsLiveProviderInternal:empty_manifest`,category:Qm.WTF,message:`HlsLiveProvider: there are no qualities in manifest`}),this.liveTextManager?.processTextTracks(t,this.params.source.url),this.manifests$.next([this.masterManifest,...e])}).catch(e=>{this.params.output.error$.next({id:`ExtractHlsQualities`,category:Qm.NETWORK,message:`Error fetching manifest and extracting qualities`,thrown:e})}),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(Wr(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new sh(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,n=e.getState(),r=t.getTransition(),i=r?.to?.id??t.getState()?.id??`master`,a=this.manifests$.getValue();if(!a.length)return;let o=n?`master`:i;return n&&!r&&t.startTransitionTo(this.masterManifest),a.find(e=>e.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,n=t=>{e.error$.next({id:`HlsLiveProvider`,category:Qm.WTF,message:`HlsLiveProvider internal logic error`,thrown:t})},r=Qn(this.allocation.target);this.subscription.add(()=>r.destroy());let i=(e,t)=>this.subscription.add(e.subscribe(t,n));i(r.ended$,e.endedEvent$),i(r.error$,e.error$),i(r.isBuffering$,e.isBuffering$),i(r.currentBuffer$,e.currentBuffer$),i(r.currentBuffer$,e.currentNativeBuffer$),i(r.totalBufferDuration$,e.totalBufferDuration$),i(r.bufferRangeCount$,e.bufferRangeCount$),i(r.loadedMetadata$,e.firstBytesEvent$),i(r.loadedMetadata$,e.loadedMetadataEvent$),i(r.playing$,e.firstFrameEvent$),i(r.canplay$,e.canplay$),i(r.playedTime$,e.playedTime$),i(r.inPiP$,e.inPiP$),i(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),n)),this.subscription.add(Tn(this.allocation.target,t.volume,r.volumeState$,n,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),n)):this.volumeSubscription.add(r.volumeState$.subscribe(this.params.output.volume$,n))})),this.subscription.add(En(this.allocation.target,t.playbackRate,r.playbackRateState$,n)),i(Qi(this.allocation.target),e.elementVisible$),this.liveTextManager?(i(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),i(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.allocation.video&&this.textTracksManager.connect(this.allocation.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`)},n)).add(r.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},n)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.videoState.getState()===`playing`&&this.playIfAllowed()},n)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(e=>{e&&this.params.output.availableTextTracks$.next(e)})),this.subscription.add(this.maxSeekBackTime$.pipe(eh(),rh(e=>-e/1e3)).subscribe(this.params.output.duration$,n)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let e=this.params.desiredState.seekState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n&&th(n.to)){let e=n.to.id;this.params.desiredState.videoTrack.setState(n.to);let t=this.manifests$.getValue().find(t=>t.id===e);t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(Wr(t.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),t&&t.from===`changing_manifest`&&this.videoState.setState(t.to),e&&e.state===`requested`&&this.seek(e.position)},n)),this.subscription.add(r.loadedData$.subscribe(()=>{let e=this.allocation.target?.getStartDate?.()?.getTime();this.manifestStartTime$.next(e||void 0)},n)),this.subscription.add(Xm({startTime:this.manifestStartTime$.pipe($m(th)),currentTime:r.timeUpdate$}).subscribe(({startTime:e,currentTime:t})=>this.params.output.liveTime$.next(e+t*1e3),n)),this.subscription.add(this.manifests$.pipe(rh(e=>e.map(({id:e,quality:t,size:n,bandwidth:r,fps:i})=>({id:e,quality:t,size:n,fps:i,bitrate:r})))).subscribe(this.params.output.availableVideoTracks$,n));let a=ih(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ah([`init`])).pipe(Zm(0));this.subscription.add(a.subscribe(this.syncPlayback,n));let o=!1;this.params.tuning.live.catchupLiveForMutedInactiveTab&&this.subscription.add(e.elementVisible$.pipe(eh()).subscribe(t=>{let n=e.position$.getValue(),r=e.volume$.getValue(),i=!r.volume||r.muted;!t&&!n&&i?o=!0:t&&o&&(this.seek(0),o=!1)}))}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),on(this.allocation.target,this.params.tuning)}prepare(){let e=this.selectManifest();if(nh(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||n)&&e.id===this.masterManifest.id){let{max:e,min:i}=t?.to??n??{};for(let[t,n]of[[e,`mq`],[i,`lq`]]){let e=String(parseFloat(t||``));n&&t&&r.searchParams.set(n,e)}}let i=this.params.format===`HLS_LIVE_CMAF`?2:0,a=O(r.toString(),this.liveOffset.getTotalOffset(),i);this.liveTextManager?.prepare(a),this.allocation.target.setAttribute(`src`,a),this.allocation.target.load(),Jm(a).then(e=>{if(!nh(e))this.maxSeekBackTime$.next(e);else{let e=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(nh(e)||!isFinite(e))&&Gm(a).then(e=>e.text()).then(e=>{let t=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(e)?.[1];t&&Jm(new URL(t,a).toString()).then(e=>{nh(e)||this.maxSeekBackTime$.next(e)})}).catch(()=>{})}})}playIfAllowed(){ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState(`paused`),this.liveOffset.pause(),k(this.params.desiredState.playbackState,`paused`,!0))},e=>this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:Qm.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,n=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(n),this.params.output.position$.next(-n/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getTransition();if(t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.allocation.target.removeAttribute(`src`),this.allocation.target.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`),k(this.params.desiredState.playbackState,`stopped`,!0));return}if(this.videoState.getTransition())return;let o=this.params.desiredState.seekState.getState();if(e===`stopped`){this.videoState.startTransitionTo(`ready`),this.prepare();return}if(r||i||a){let e=this.videoState.getState();this.videoState.setState(`changing_manifest`),this.videoState.startTransitionTo(e),this.prepare(),a&&this.params.output.autoVideoTrackLimits$.next(a.to),o.state===`none`&&this.params.desiredState.seekState.setState({state:`requested`,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(n?.to!==`paused`&&o.state===`requested`){this.videoState.startTransitionTo(`ready`),this.seek(o.position&&o.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case`ready`:t===`ready`?k(this.params.desiredState.playbackState,`ready`):t===`paused`?(this.videoState.setState(`paused`),this.liveOffset.pause(),k(this.params.desiredState.playbackState,`paused`)):t===`playing`&&(this.videoState.startTransitionTo(`playing`),this.playIfAllowed());return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.liveOffset.pause(),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:if(t===`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 e=this.liveOffset.getTotalOffset();e>=this.maxSeekBackTime$.getValue()&&(e=0,this.liveOffset.resetTo(e)),this.liveOffset.resume(),this.params.output.position$.next(-e/1e3),this.prepare()}else n?.to===`paused`&&(k(this.params.desiredState.playbackState,`paused`),this.liveOffset.pause());return;case`changing_manifest`:break;default:return Ym(e)}};generateLiveUrl(){let e=O(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 Oh,debounce as kh,ErrorCategory as Ah,fromEvent as jh,isNonNullable as Mh,isNullable as Nh,map as Ph,merge as Fh,observableFrom as Ih,Subscription as Lh,ValueSubject as Rh,VideoQuality as zh}from"@vkontakte/videoplayer-shared";class Bh{subscription=new Lh;volumeSubscription=new Lh;videoState=new Dt(`stopped`);allocation;params;textTracksManager=null;masterManifest;manifests$=new Rh([]);unmuteAfterBrowserResetsHappened=new Rh(!1);constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn(e.source.url)),this.params=e,this.allocation=va(e.container,e.tuning),this.params.output.element$.next(this.allocation.video??void 0),this.masterManifest={id:`master`,quality:zh.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(Wr(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),_h(O(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,audioOnly:this.params.tuning.audioOnly}).then(({qualityManifests:e,textTracks:t})=>{this.params.isOnDemand&&this.params.tuning.hls.filterOnDemandQualityList&&(e=e.sort((e,t)=>{let n=e.size?e.size.height:0;return(t.size?t.size.height:0)-n}).filter((e,t)=>t%2==0)),this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...e]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(t)},e=>this.params.output.error$.next({id:`ExtractHlsQualities`,category:Ah.NETWORK,message:`Error fetching manifest and extracting qualities`,thrown:e})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,n=e.getState(),r=t.getTransition(),i=r?.to?.id??t.getState()?.id??`master`,a=this.manifests$.getValue();if(!a.length)return;let o=n?`master`:i;return n&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(e=>e.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,n=t=>{e.error$.next({id:`HlsProvider`,category:Ah.WTF,message:`HlsProvider internal logic error`,thrown:t})},r=Qn(this.allocation.target);this.subscription.add(()=>r.destroy());let i=(e,t)=>this.subscription.add(e.subscribe(t));if(i(r.timeUpdate$,e.position$),i(r.durationChange$,e.duration$),i(r.ended$,e.endedEvent$),i(r.looped$,e.loopedEvent$),i(r.error$,e.error$),i(r.isBuffering$,e.isBuffering$),i(r.currentBuffer$,e.currentBuffer$),i(r.currentBuffer$,e.currentNativeBuffer$),i(r.totalBufferDuration$,e.totalBufferDuration$),i(r.bufferRangeCount$,e.bufferRangeCount$),i(r.loadedMetadata$,e.firstBytesEvent$),i(r.loadedMetadata$,e.loadedMetadataEvent$),i(r.playing$,e.firstFrameEvent$),i(r.canplay$,e.canplay$),i(r.seeked$,e.seekedEvent$),i(r.playedTime$,e.playedTime$),i(r.inPiP$,e.inPiP$),i(r.inFullscreen$,e.inFullscreen$),i(this.videoState.stateChangeEnded$.pipe(Ph(e=>e.to)),this.params.output.playbackState$),this.subscription.add(wn(this.allocation.target,t.isLooped,n)),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),n)):this.volumeSubscription.add(r.volumeState$.subscribe(this.params.output.volume$,n))})),this.subscription.add(En(this.allocation.target,t.playbackRate,r.playbackRateState$,n)),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Tn(this.allocation.target,t.volume,r.volumeState$,n,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`)},n)).add(r.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},n)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.videoState.getState()===`playing`&&this.playIfAllowed()},n).add(r.loadedMetadata$.subscribe(()=>{let e=this.params.desiredState.seekState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n&&Mh(n.to)){let e=n.to.id;this.params.desiredState.videoTrack.setState(n.to);let t=this.manifests$.getValue().find(t=>t.id===e);t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(Wr(t.url)))}let i=this.params.desiredState.playbackRate.getState();if(i!==this.params.output.element$.getValue()?.playbackRate){let e=this.params.output.element$.getValue();e&&(this.params.desiredState.playbackRate.setState(i),e.playbackRate=i)}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),t&&t.from===`changing_manifest`&&this.videoState.setState(t.to),e.state===`requested`&&this.seek(e.position)},n))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)})),this.subscription.add(this.manifests$.pipe(Ph(e=>e.map(({id:e,quality:t,size:n,bandwidth:r,fps:i})=>({id:e,quality:t,size:n,fps:i,bitrate:r})))).subscribe(this.params.output.availableVideoTracks$,n)),this.allocation.video&&(!A.device.isIOS||!this.params.tuning.useNativeHLSTextTracks)){let{textTracks:e}=this.allocation.video;this.subscription.add(Fh(jh(e,`addtrack`),jh(e,`removetrack`),jh(e,`change`),Ih([`init`])).subscribe(()=>{for(let t=0;t<e.length;t++)e[t].mode=`hidden`},n))}let a=Fh(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ih([`init`])).pipe(kh(0));this.subscription.add(a.subscribe(this.syncPlayback,n))}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.textTracksManager?.destroy(),this.params.output.element$.next(void 0),on(this.allocation.target,this.params.tuning)}prepare(){let e=this.selectManifest();if(Nh(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||n)&&e.id===this.masterManifest.id){let{max:e,min:i}=t?.to??n??{};for(let[t,n]of[[e,`mq`],[i,`lq`]]){let e=String(parseFloat(t||``));n&&t&&r.searchParams.set(n,e)}}this.allocation.target.setAttribute(`src`,r.toString()),this.allocation.target.load()}playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:Ah.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Ih(e).subscribe(t,n)):e.then(t,n)}seek(e){this.params.output.willSeekEvent$.next(),this.allocation.target.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getTransition();if(t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.allocation.target.removeAttribute(`src`),this.allocation.target.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`),k(this.params.desiredState.playbackState,`stopped`,!0));return}if(this.videoState.getTransition())return;let o=this.params.desiredState.seekState.getState();if(e===`stopped`){this.videoState.startTransitionTo(`ready`),this.prepare();return}if(r||i||a){let e=this.videoState.getState();this.videoState.setState(`changing_manifest`),this.videoState.startTransitionTo(e);let{currentTime:t}=this.allocation.target;this.prepare(),a&&this.params.output.autoVideoTrackLimits$.next(a.to),o.state===`none`&&this.params.desiredState.seekState.setState({state:`requested`,position:t*1e3,forcePrecise:!0});return}switch(n?.to!==`paused`&&o.state===`requested`&&this.seek(o.position),e){case`ready`:t===`ready`?k(this.params.desiredState.playbackState,`ready`):t===`paused`?(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`&&(this.videoState.startTransitionTo(`playing`),this.playIfAllowed());return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;case`changing_manifest`:break;default:return Oh(e)}}}import{assertNever as Vh,assertNonNullable as Hh,debounce as Uh,ErrorCategory as Wh,isHigherOrEqual as Gh,isLowerOrEqual as Kh,isNonNullable as qh,merge as Jh,observableFrom as Yh,Subscription as Xh,map as Zh}from"@vkontakte/videoplayer-shared";class Qh{subscription=new Xh;volumeSubscription=new Xh;videoState=new Dt(`stopped`);allocation;trackUrls={};params;textTracksManager=null;constructor(e){e.tuning.disableSubtitles||(this.textTracksManager=new jn),this.params=e,this.allocation=va(e.container,e.tuning),this.params.output.element$.next(this.allocation.video??void 0),Object.entries(this.params.source).reverse().forEach(([e,t],n)=>{let r=n.toString(10);this.trackUrls[r]={track:{quality:e,id:r},url:t}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:e})=>e)),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,n=t=>{e.error$.next({id:`MpegProvider`,category:Wh.WTF,message:`MpegProvider internal logic error`,thrown:t})},r=Qn(this.allocation.target);this.subscription.add(()=>r.destroy());let i=(e,t)=>this.subscription.add(e.subscribe(t,n));i(r.timeUpdate$,e.position$),i(r.durationChange$,e.duration$),i(r.ended$,e.endedEvent$),i(r.looped$,e.loopedEvent$),i(r.error$,e.error$),i(r.isBuffering$,e.isBuffering$),i(r.currentBuffer$,e.currentNativeBuffer$),i(r.currentBuffer$,e.currentBuffer$),i(r.totalBufferDuration$,e.totalBufferDuration$),i(r.bufferRangeCount$,e.bufferRangeCount$),i(r.loadedMetadata$,e.firstBytesEvent$),i(r.loadedMetadata$,e.loadedMetadataEvent$),i(r.playing$,e.firstFrameEvent$),i(r.canplay$,e.canplay$),i(r.seeked$,e.seekedEvent$),i(r.playedTime$,e.playedTime$),i(r.inPiP$,e.inPiP$),i(r.inFullscreen$,e.inFullscreen$),i(this.videoState.stateChangeEnded$.pipe(Zh(e=>e.to)),this.params.output.playbackState$),this.subscription.add(wn(this.allocation.target,t.isLooped,n)),Oo({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Tn(this.allocation.target,t.volume,r.volumeState$,n,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),n)):this.volumeSubscription.add(r.volumeState$.subscribe(this.params.output.volume$,n))})),this.subscription.add(En(this.allocation.target,t.playbackRate,r.playbackRateState$,n)),i(Qi(this.allocation.target),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(`playing`),k(t.playbackState,`playing`)},n)).add(r.pause$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)},n)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`);let e=this.params.desiredState.videoTrack.getTransition();if(e&&qh(e.to)){this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to.id].track);let t=this.params.desiredState.playbackRate.getState();if(t!==this.params.output.element$.getValue()?.playbackRate){let e=this.params.output.element$.getValue();e&&(this.params.desiredState.playbackRate.setState(t),e.playbackRate=t)}}this.videoState.getState()===`playing`&&!this.allocation.target.ended&&this.playIfAllowed()},n)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState(`paused`),k(t.playbackState,`paused`)})),this.allocation.video&&this.textTracksManager?.connect(this.allocation.video,t,e);let a=Jh(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Yh([`init`])).pipe(Uh(0));this.subscription.add(a.subscribe(this.syncPlayback,n))}destroy(){this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.textTracksManager?.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),on(this.allocation.target,this.params.tuning)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Hh(e,`MpegProvider: track is not selected`);let{url:t}=this.trackUrls[e];Hh(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Wc(t)),this.allocation.target.setAttribute(`src`,t),this.allocation.target.load(),this.params.output.hostname$.next(Wr(t))}playIfAllowed(){let e=ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}),t=e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},n=e=>{this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:Wh.DOM,thrown:e})};this.params.tuning.ignoreForcePlayResultWhenProviderChanged?this.subscription.add(Yh(e).subscribe(t,n)):e.then(t,n)}seek(e){this.params.output.willSeekEvent$.next(),this.allocation.target.currentTime=e/1e3}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition();if(t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.allocation.target.removeAttribute(`src`),this.allocation.target.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`),k(this.params.desiredState.playbackState,`stopped`,!0));return}if(this.videoState.getTransition())return;let r=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(r&&e!==`ready`&&!i){this.handleQualityLimitTransition(r.to);return}if(e===`stopped`){this.videoState.startTransitionTo(`ready`),this.prepare();return}if(i){let{currentTime:e}=this.allocation.target;this.prepare(),a.state===`none`&&this.params.desiredState.seekState.setState({state:`requested`,position:e*1e3,forcePrecise:!0});return}switch(n?.to!==`paused`&&a.state===`requested`&&this.seek(a.position),e){case`ready`:t===`ready`?k(this.params.desiredState.playbackState,`ready`):t===`paused`?(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`&&(this.videoState.startTransitionTo(`playing`),this.playIfAllowed());return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return Vh(e)}};handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=e=>{this.params.output.currentVideoTrack$.next(e),this.params.desiredState.videoTrack.startTransitionTo(e)},n=e=>{t(Br(a,{container:this.allocation.video?.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:e,abrLogger:this.params.dependencies.abrLogger}))},r=this.params.output.currentVideoTrack$.getValue()?.quality,i=!!(e.max||e.min),a=Object.values(this.trackUrls).map(e=>e.track);if(!r||!i||Cr(e,a[0].quality,a.at(-1)?.quality)){n();return}let o=e.max?Kh(r,e.max):!0,s=e.min?Gh(r,e.min):!0;o&&s||n(e)}}import{assertNever as $h,debounce as eg,merge as tg,observableFrom as ng,Subscription as rg,map as ig,ValueSubject as ag,ErrorCategory as og,VideoQuality as sg}from"@vkontakte/videoplayer-shared";import{ErrorCategory as cg}from"@vkontakte/videoplayer-shared";var lg=[`stun:videostun.mycdn.me:80`],ug=1e3,dg=3,fg=()=>null;class pg{options;ws=null;peerConnection=null;serverUrl=``;streamKey=``;stream=null;signalingType=`JOIN`;retryTimeout;retryCount=0;externalStartCallback=fg;externalStopCallback=fg;externalErrorCallback=fg;constructor(e,t){this.options=this.normalizeOptions(t);let n=e.split(`/`);this.serverUrl=n.slice(0,n.length-1).join(`/`),this.streamKey=n[n.length-1]}onStart(e){try{this.externalStartCallback=e}catch(e){this.handleSystemError(e)}}onStop(e){try{this.externalStopCallback=e}catch(e){this.handleSystemError(e)}}onError(e){try{this.externalErrorCallback=e}catch(e){this.handleSystemError(e)}}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(e){this.handleRTCError(e)}}onSocketError(e){try{this.externalErrorCallback(Error(e.toString()))}catch(e){this.handleRTCError(e)}}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(e){this.handleRTCError(e)}}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(e){this.handleRTCError(e)}}async handleLogin(){try{let e={iceServers:[{urls:lg}]};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(e){this.handleRTCError(e)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(e){this.handleRTCError(e)}}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:cg.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 Error(`Can not create offer - no peer connection instance `);let t=await this.peerConnection.createOffer(e),n=t.sdp||``;if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(n))throw Error(`No h264 codec support error`);return t}handleRTCError(e){try{this.externalErrorCallback(e||Error(`RTC connection error`))}catch(e){this.handleSystemError(e)}}handleNetworkError(){try{this.externalErrorCallback(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 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,null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),ug)}normalizeOptions(e={}){let t={stunServerList:lg,maxRetryNumber:dg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}class mg{subscription;volumeSubscription;params;log;allocation;videoState=new Dt(`stopped`);liveStreamClient;maxSeekBackTime$=new ag(0);constructor(e){this.subscription=new rg,this.volumeSubscription=new rg,this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`WebRTCLiveProvider`),this.allocation=va(e.container,e.tuning),this.liveStreamClient=new pg(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.volumeSubscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),on(this.allocation.target,this.params.tuning)}subscribe(){let{output:e,desiredState:t}=this.params,n=t=>{e.error$.next({id:`WebRTCLiveProvider`,category:og.WTF,message:`WebRTCLiveProvider internal logic error`,thrown:t})};this.subscription.add(tg(this.videoState.stateChangeStarted$.pipe(ig(e=>({transition:e,type:`start`}))),this.videoState.stateChangeEnded$.pipe(ig(e=>({transition:e,type:`end`})))).subscribe(({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})}));let r=Qn(this.allocation.target);this.subscription.add(()=>r.destroy());let i=(e,t)=>this.subscription.add(e.subscribe(t,n));i(r.timeUpdate$,e.liveTime$),i(r.ended$,e.endedEvent$),i(r.looped$,e.loopedEvent$),i(r.playedTime$,e.playedTime$),i(r.error$,e.error$),i(r.isBuffering$,e.isBuffering$),i(r.currentBuffer$,e.currentBuffer$),i(r.currentBuffer$,e.currentNativeBuffer$),i(r.totalBufferDuration$,e.totalBufferDuration$),i(r.bufferRangeCount$,e.bufferRangeCount$),i(Qi(this.allocation.target),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(t=>{e.duration$.next(t===1/0?0:t)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`)},n)).add(r.pause$.subscribe(()=>{this.videoState.setState(`paused`)},n)).add(r.playing$.subscribe(()=>{this.videoState.setState(`playing`)},n)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Tn(this.allocation.target,t.volume,r.volumeState$,n,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(i=>{this.volumeSubscription.unsubscribe(),i?this.volumeSubscription.add(t.volume.stateChangeStarted$.subscribe(({to:t})=>e.volume$.next(t),n)):this.volumeSubscription.add(r.volumeState$.subscribe(e.volume$,n))})),this.subscription.add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.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 $h(n.to)}},n)).add(tg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ng([`init`])).pipe(eg(0)).subscribe(this.syncPlayback.bind(this),n)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),n)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),n))}onLiveStreamStart(e){this.params.output.element$.next(this.allocation.video??void 0),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(Wr(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:sg.INVARIANT}),this.allocation.target.srcObject=e,k(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:og.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ci(this.allocation.target,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`,!0))},e=>this.params.output.error$.next({id:`ForcePlay`,message:`play() failed even with workarounds`,category:og.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition();if(t===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.allocation.target.pause(),this.allocation.target.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`),k(this.params.desiredState.playbackState,`stopped`,!0));return}if(this.videoState.getTransition())return;let r=this.params.desiredState.videoTrack.getTransition();if(e===`stopped`){this.videoState.startTransitionTo(`ready`),this.prepare();return}if(r){this.prepare();return}switch(e){case`ready`:t===`paused`?(this.videoState.setState(`paused`),k(this.params.desiredState.playbackState,`paused`)):t===`playing`&&(this.videoState.startTransitionTo(`playing`),this.playIfAllowed());return;case`playing`:t===`paused`?(this.videoState.startTransitionTo(`paused`),this.allocation.target.paused?this.videoState.setState(`paused`):this.allocation.target.pause()):n?.to===`playing`&&k(this.params.desiredState.playbackState,`playing`);return;case`paused`:t===`playing`?(this.videoState.startTransitionTo(`playing`),this.playIfAllowed()):n?.to===`paused`&&k(this.params.desiredState.playbackState,`paused`);return;default:return $h(e)}}}class hg{length;array;index;iterator;current;constructor(e){this.array=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 Error(`Iterable is completed`);return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}all(){return this.array}}import{assertNever as gg,assertNonNullable as _g,ErrorCategory as vg,filter as yg,isNonNullable as bg,isNullable as xg,map as Sg,merge as Cg,once as wg,Subject as q,Subscription as Tg,ValueSubject as J,flattenObject as Eg,devNull as Dg,getWindow as Og}from"@vkontakte/videoplayer-shared";import{Observable as kg,map as Ag,Subscription as jg,Subject as Mg,now as Ng,combine as Pg}from"@vkontakte/videoplayer-shared";var Fg=e=>new kg(t=>{let n=new jg,r=e.desiredPlaybackState$.stateChangeStarted$.pipe(Ag(({from:e,to:t})=>`${e}-${t}`)),i=e.desiredPlaybackState$.stateChangeEnded$,a=e.providerChanged$.pipe(Ag(({type:e})=>e!==void 0)),o=Pg({providerChanged:e.providerChanged$.pipe(Ag(({type:e})=>e!==void 0)),videoLastDataObtainedTimestamp:e.videoLastDataObtainedTimestamp$.pipe(Ag(e=>e??0)),stateChangeStarted:e.desiredPlaybackState$.stateChangeStarted$}).pipe(Ag(({providerChanged:t,videoLastDataObtainedTimestamp:n,stateChangeStarted:r})=>{let i=Ng()-n;return t||r?.to!==`playing`||i<e.playbackHangupNoDataThreshold})),s=e.useDelayedPlaybackHangupWithData?o:a,c=new Mg,l=0,u=`unknown`;return n.add(r.subscribe(t=>{l&&window.clearTimeout(l),u=t,l=window.setTimeout(()=>c.next(t),e.maxTransitionInterval),L({m:`hangup.set`,l:t,id:l})})),n.add(i.subscribe(()=>{L({m:`hangup.cl`,id:l}),window.clearTimeout(l),u=`unknown`,l=0})),n.add(s.subscribe(t=>{l&&(L({m:`hangup.rs.0`,id:l}),window.clearTimeout(l),l=0,t&&(l=window.setTimeout(()=>c.next(u),e.maxTransitionInterval),L({m:`hangup.rs.1`,id:l})))})),n.add(c.subscribe(t)),()=>{window.clearTimeout(l),n.unsubscribe()}});import{AbortControllerPolyfilled as Ig}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Lg,Subscription as Rg,combine as zg,filter as Bg,once as Vg}from"@vkontakte/videoplayer-shared";import{getWindow as Hg}from"@vkontakte/videoplayer-shared";function Ug(){let e=Hg();return new(e.AudioContext||e.webkitAudioContext)}class Wg{providerOutput;provider$;volumeMultiplierError$;volumeMultiplier;static errorId=`VolumeMultiplierManager`;destroyController=new Ig;subscriptions=new Rg;audioContext=null;gainNode=null;mediaElementSource=null;constructor(e,t,n,r){this.providerOutput=e,this.provider$=t,this.volumeMultiplierError$=n,this.volumeMultiplier=r,this.subscriptions.add(this.provider$.pipe(Bg(e=>!!e.type),Vg()).subscribe(({type:e})=>this.subscribe(e)))}subscribe(e){A.browser.isSafari&&e!==`MPEG`||this.subscriptions.add(zg({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Bg(({playbackState:e,video:t,volume:{muted:n,volume:r}})=>e===`playing`&&!!t&&!n&&!!r),Vg()).subscribe(({video:e})=>{this.initAudioContextOnce(e).then(e=>{e||this.destroy()}).catch(e=>{this.handleError(e),this.destroy()})}))}static isSupported(){return`AudioContext`in window&&`GainNode`in window&&`MediaElementAudioSourceNode`in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,n=Ug();this.audioContext=n;let r=n.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(n.destination),n.state===`suspended`&&(await n.resume(),this.destroyController.signal.aborted))return!1;let i=n.createMediaElementSource(e);return this.mediaElementSource=i,i.connect(r),!0}cleanup(){this.mediaElementSource&&=(this.mediaElementSource.disconnect(),null),this.gainNode&&=(this.gainNode.disconnect(),null),this.audioContext&&=(this.audioContext.state!==`closed`&&this.audioContext.close(),null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:Wg.errorId,category:Lg.VIDEO_PIPELINE,message:e?.message??`${Wg.errorId} exception`,thrown:e})}}import{ErrorCategory as Gg}from"@vkontakte/videoplayer-shared";import{flattenObject as Kg,isNullable as qg}from"@vkontakte/videoplayer-shared";var Jg=e=>{let t=e.data?.code;return typeof t==`number`?t:null};class Yg{deps;static heuristicName=`MediaErrorHeuristic`;constructor(e){this.deps=e}analyze(e){if(e.origin!==`mediaError`)return null;let t=Jg(e);if(qg(t))return null;let{deps:n}=this,r=n.getCurrentVideoTrack(),i=n.getInitiatedAt(),a=performance.now(),o=n.getAccumulatedPlayingTime(),s=n.getReinitHistory(),c=s.reachedPlaying.length>0;if(n.tracer.log(Yg.heuristicName,Kg({mediaErrorCode:t,age_ms:Math.round(a-i),bufferLength_s:n.getBufferLength(),bufferAhead_s:n.getBufferAhead(),bufferRangeCount:n.getBufferRangeCount(),quality:r?.quality,reinitPlayingHistory:s.reachedPlaying,reinitHappenedDelta:s.deltas,accumulatedPlayingTime_ms:Math.round(o),position:n.getPosition(),errorId:e.id,videoCodec:n.getVideoCodec(),audioCodec:n.getAudioCodec(),visibilityState:n.getVisibilityState()})),t===4)return{action:`switch_provider`,reason:`MediaError#4: source not supported (${e.id})`};if(t===3&&c){if(o===0)return{action:`switch_provider`,reason:`MediaError#3 after reinit without reaching playing — reinit is useless`};if(o<n.tuning.mayday.playingUnstableThresholdMs)return{action:`switch_provider`,reason:`MediaError#3 with ${n.tuning.mayday.playingUnstableThresholdMs}ms total playing — provider unstable`}}return null}}import{ErrorCategory as Xg}from"@vkontakte/videoplayer-shared";class Zg{_deps;static heuristicName=`FetcherErrorHeuristic`;constructor(e){this._deps=e}analyze(e){if(e.origin!==`segment_fetcher`||e.category===Xg.FATAL&&!e.canBeRecoverable)return null;let t=`Fetcher error: ${e.id}`;return e.canBeRecoverable?{action:`switch_provider`,reason:t}:{action:`failover_host`,reason:t}}}import{isNullable as Qg,isNonNullable as $g,getWindow as e_}from"@vkontakte/videoplayer-shared";function t_(e,t){let{providerOutput:n,maydayStatistics:r}=e;return{tuning:e.tuning,getFallbackContext:e.getFallbackContext,tracer:t,getPosition:()=>n.position$.getValue(),getCurrentVideoTrack:()=>n.currentVideoTrack$.getValue(),getInitiatedAt:()=>r.getInitiatedAt(),getBufferLength:()=>{let e=n.totalBufferDuration$.getValue();return $g(e)?e/1e3:0},getBufferAhead:()=>{let e=n.currentNativeBuffer$.getValue(),t=n.position$.getValue();return $g(e)?Math.max(e.to-t,0):0},getBufferRangeCount:()=>n.bufferRangeCount$.getValue()??0,getReinitHistory:()=>r.getReinitHistory(),getAccumulatedPlayingTime:()=>r.getAccumulatedPlayingTime(),getVideoCodec:()=>{let e=n.currentVideoTrack$.getValue()?.streamId;if(!Qg(e))return n.availableVideoStreams$.getValue().find(t=>t.id===e)?.codec},getAudioCodec:()=>n.currentAudioStream$.getValue()?.codec,getVisibilityState:()=>e_().document.visibilityState}}var n_=[Yg,Zg];class r_{deps;heuristics=[];tracer;providerFailures=0;failoverUrlIndex;constructor(e){this.deps=e,this.tracer=e.tracer.createComponentTracer(`Mayday`);let t=t_(e,this.tracer),n=e.tuning.mayday.heuristics;this.heuristics=n_.filter(e=>n.includes(e.heuristicName)).map(e=>new e(t))}get currentFailoverUrlIndex(){return this.failoverUrlIndex}getRecommendation(e){for(let t of this.heuristics){let n=t.analyze(e);if(n){let e=this.validateRecommendation(n);return this.applyStateChange(e),e}}let t=this.validateRecommendation(this.computeFallbackRecommendation(e));return this.applyStateChange(t),t}validateRecommendation(e){return e.action===`switch_codec`&&!this.deps.getFallbackContext().canSwitchCodec?{action:`switch_provider`,reason:`${e.reason} — no more codecs available`}:e.action===`failover_host`&&!this.hasAvailableFailoverHost()?{action:`switch_provider`,reason:`${e.reason} — no failover hosts available`}:e}hasAvailableFailoverHost(){return this.deps.failoverHosts.length>0&&(this.failoverUrlIndex===void 0||this.failoverUrlIndex<this.deps.failoverHosts.length-1)}computeFallbackRecommendation(e){let t=this.deps.getFallbackContext(),n=this.deps.tuning.dash.useFailoverHostsOnAllProviderCrash||e.category===Gg.NETWORK,r=e.category===Gg.FATAL,i=this.hasAvailableFailoverHost(),a=this.providerFailures<this.deps.tuning.providerErrorLimit&&!r,o=i&&!r&&(n&&t.hasProviderStarted||!a);return a?{action:`reinit`,reason:`Provider error, reinit attempt ${this.providerFailures+1}/${this.deps.tuning.providerErrorLimit}`}:o?{action:`failover_host`,reason:`Switching to failover host`}:t.canSwitchCodec?{action:`switch_codec`,reason:`Switching to next video codec`}:{action:`switch_provider`,reason:`All recovery options exhausted`}}applyStateChange(e){switch(e.action){case`reinit`:this.providerFailures++;break;case`failover_host`:this.failoverUrlIndex=this.failoverUrlIndex===void 0?0:this.failoverUrlIndex+1;break;case`switch_provider`:this.providerFailures=0,this.failoverUrlIndex=void 0;break;default:break}}reset(){for(let e of this.heuristics)e.reset?.()}destroy(){for(let e of this.heuristics)e.destroy?.();this.tracer.end()}}import{isNullable as i_,isNonNullable as a_,Subscription as o_}from"@vkontakte/videoplayer-shared";class s_{deps;providerInitiatedAt=0;reinitTimestamps=[];reinitReachedPlaying=[];playingStartTime;accumulatedPlayingTime=0;firstFrameReceived=!1;subscription=new o_;constructor(e){this.deps=e,this.providerInitiatedAt=performance.now(),this.subscription.add(this.deps.firstFrameEvent$.subscribe(()=>{this.firstFrameReceived||(this.firstFrameReceived=!0,this.deps.playbackState$.getValue()===`playing`&&(this.playingStartTime=performance.now()))})).add(this.deps.playbackState$.subscribe(e=>{this.firstFrameReceived&&(e===`playing`?i_(this.playingStartTime)&&(this.playingStartTime=performance.now()):a_(this.playingStartTime)&&(this.accumulatedPlayingTime+=performance.now()-this.playingStartTime,this.playingStartTime=void 0))}))}recordReinit(){this.reinitReachedPlaying.push(this.firstFrameReceived),this.reinitTimestamps.push(performance.now()),this.firstFrameReceived=!1,this.accumulatedPlayingTime=0,this.playingStartTime=void 0}recordProviderSwitch(){this.providerInitiatedAt=performance.now(),this.reinitTimestamps=[],this.reinitReachedPlaying=[],this.playingStartTime=void 0,this.accumulatedPlayingTime=0,this.firstFrameReceived=!1}getInitiatedAt(){return this.providerInitiatedAt}getAccumulatedPlayingTime(){let e=this.accumulatedPlayingTime;return a_(this.playingStartTime)&&(e+=performance.now()-this.playingStartTime),e}getReinitHistory(){return{reachedPlaying:[...this.reinitReachedPlaying,this.firstFrameReceived],deltas:this.reinitTimestamps.map((e,t)=>Math.round(e-(t===0?this.providerInitiatedAt:this.reinitTimestamps[t-1])))}}destroy(){this.subscription.unsubscribe()}}var c_={chunkDuration:5e3,maxParallelRequests:5};class l_{current$=new J({type:void 0});providerError$=new q;noAvailableProvidersError$=new q;volumeMultiplierError$=new q;providerOutput={position$:new J(0),duration$:new J(1/0),playedTime$:new J(0),volume$:new J({muted:!1,volume:1}),availableVideoStreams$:new J([]),currentVideoStream$:new J(void 0),availableVideoTracks$:new J([]),currentVideoTrack$:new J(void 0),availableVideoCodecs$:new J([]),availableAudioStreams$:new J([]),currentAudioStream$:new J(void 0),availableAudioTracks$:new J([]),availableAudioCodecs$:new J([]),currentVideoSegmentLength$:new J(0),currentAudioSegmentLength$:new J(0),isAudioAvailable$:new J(!0),autoVideoTrackLimitingAvailable$:new J(!1),autoVideoTrackLimits$:new J(void 0),currentBuffer$:new J(void 0),currentNativeBuffer$:new J(void 0),totalBufferDuration$:new J(void 0),bufferRangeCount$:new J(void 0),videoLastDataObtainedTimestamp$:new J(void 0),isBuffering$:new J(!0),updateDurationError$:new q,error$:new q,fetcherError$:new q,fetcherRecoverableError$:new q,warning$:new q,willSeekEvent$:new q,soundProhibitedEvent$:new q,seekedEvent$:new q,loopedEvent$:new q,endedEvent$:new q,manifestRequested$:new q,firstBytesManifest$:new q,manifestReceived$:new q,firstBytesRequested$:new q,firstBytesReceived$:new q,firstBytesEvent$:new q,loadedMetadataEvent$:new q,firstFrameEvent$:new q,canplay$:new q,isLive$:new J(void 0),isLiveEnded$:new J(null),canPlayLiveTailBuffer$:new J(!1),isLowLatency$:new J(!1),canChangePlaybackSpeed$:new J(!0),liveTime$:new J(void 0),liveBufferTime$:new J(void 0),liveLatency$:new J(void 0),severeStallOccurred$:new q,availableTextTracks$:new J([]),currentTextTrack$:new J(void 0),hostname$:new J(void 0),httpConnectionType$:new J(void 0),httpConnectionReused$:new J(void 0),httpConnectionMetrics$:new J(void 0),httpDownloadMetrics$:new J(void 0),inPiP$:new J(!1),inFullscreen$:new J(!1),element$:new J(void 0),elementVisible$:new J(!0),availableSources$:new J(void 0),is3DVideo$:new J(!1),playbackState$:new J(``),getCurrentTime$:new J(null)};subscription=new Tg;screenFormatsIterator;chromecastFormatsIterator;videoCodecsIterator;log;tracer;params;currentProviderStarted=!1;currentFailedVideoTrack=null;volumeMultiplierManager=null;dashMaxTvVideoQuality=null;mayday;maydayStatistics;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`ProviderContainer`),this.tracer=e.dependencies.tracer.createComponentTracer(`ProviderContainer`);let t=$e([...ra(this.params.tuning),...na(this.params.tuning)],this.params.tuning.disableHlsOnDesktop).filter(t=>bg(e.sources[t])),{forceFormat:n,formatsToAvoid:r}=this.params.tuning,i=[];i=n?[n]:r.length?[...t.filter(e=>!r.includes(e)),...t.filter(e=>r.includes(e))]:t,this.log({message:`Selected formats: ${i.join(` > `)}`}),this.tracer.log(`Selected formats`,Eg(i),!0),this.screenFormatsIterator=new hg(i);let a=[...ia(!0),...ia(!1)];this.chromecastFormatsIterator=new hg(a.filter(t=>bg(e.sources[t]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:s}}=this.params;s&&o!==1&&Wg.isSupported()&&(this.volumeMultiplierManager=new Wg(this.providerOutput,this.current$,this.volumeMultiplierError$,o)),this.maydayStatistics=new s_(this.providerOutput),this.mayday=new r_({tuning:this.params.tuning,failoverHosts:this.params.failoverHosts??[],providerOutput:this.providerOutput,maydayStatistics:this.maydayStatistics,getFallbackContext:()=>this.getFallbackContext(),tracer:this.params.dependencies.tracer})}getFallbackContext(){return{hasProviderStarted:this.currentProviderStarted,canSwitchCodec:this.params.tuning.dash.codecsPrioritizeEnabled&&!!this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()}}init(){L.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new hg(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.mayday.destroy(),this.maydayStatistics.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(xg(t)){this.handleNoFormatsError(e);return}let n;try{n=this.createProvider(e,t),this.currentFailedVideoTrack=null}catch(e){this.providerError$.next({id:`ProviderNotConstructed`,category:vg.WTF,message:`Failed to create provider`,thrown:e})}n?this.current$.next({type:t,provider:n,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log(`reinitProvider`),this.maydayStatistics.recordReinit(),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log(`switchToNextProvider`,{destination:e}),this.maydayStatistics.recordProviderSwitch(),this.destroyProvider(),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(),this.mayday.reset();let t=this.providerOutput.position$.getValue()*1e3,n=this.params.desiredState.seekState.getState(),r=n.state!==`none`;if(this.params.desiredState.seekState.setState({state:`requested`,position:r?n.position:t,forcePrecise:r?n.forcePrecise:!1}),e.scene3D){let t=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:t.x,y:t.y})}let i=this.providerOutput.isBuffering$;i.getValue()||i.next(!0)}handleMaydayRecommendation(e,t){switch(this.tracer.log(`handleMaydayRecommendation`,{action:e.action,reason:e.reason}),e.action){case`reinit`:this.reinitProvider();break;case`failover_host`:this.reinitProvider();break;case`switch_codec`:this.switchToNextVideoCodec();break;case`switch_provider`:this.switchToNextProvider(t);break}}applyErrorSideEffects(e,t){let n=this.providerOutput.currentVideoTrack$.getValue(),r=this.params.tuning.dash.useFailoverHostsOnAllProviderCrash||e.category===vg.NETWORK;this.dashMaxTvVideoQuality=this.params.tuning.dash.dashMaxTvVideoQuality?zd(e,t,n?.quality):null,this.currentFailedVideoTrack=this.params.tuning.dash.useNewFailoverLogic?n:null,this.params.tuning.dropUrlCacheWhenProviderCrashed&&!r&&Em()}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 gg(e)}}createScreenProvider(e){let{sources:t,container:n,desiredState:r,panelSize:i}=this.params,a=this.providerOutput,o={container:n,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:i,skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$};switch(e){case`DASH_SEP`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_ONDEMAND`:case`DASH_STREAMS`:{let n=this.applyFailoverHost(t[e]),r=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);_g(n);let{useDashProviderVirtual:i,useDashProviderVirtualMobile:a}=this.params.tuning,{isMobile:s}=A.device;return!s&&i||s&&a?new af({...o,failedVideoTrack:this.currentFailedVideoTrack,source:n,sourceHls:r,forceVideoCodec:this.videoCodecsIterator?.getValue(),isOnDemand:e===`DASH_ONDEMAND`,dashMaxTvVideoQuality:this.dashMaxTvVideoQuality}):new Fm({...o,failedVideoTrack:this.currentFailedVideoTrack,source:n,sourceHls:r,forceVideoCodec:this.videoCodecsIterator?.getValue(),isOnDemand:e===`DASH_ONDEMAND`,dashMaxTvVideoQuality:this.dashMaxTvVideoQuality})}case`DASH_LIVE_CMAF`:{let n=this.applyFailoverHost(t[e]);return _g(n),this.params.tuning.useDashProviderVirtual&&!A.device.isMobile||this.params.tuning.useDashProviderVirtualMobile&&A.device.isMobile?new Rf({...o,source:n}):new Wm({...o,source:n})}case`HLS`:case`HLS_ONDEMAND`:case`HLS_FMP4`:{let n=this.applyFailoverHost(t[e]);return _g(n),new Bh({...o,source:n,isOnDemand:e===`HLS_ONDEMAND`})}case`HLS_LIVE`:case`HLS_LIVE_CMAF`:{let n=this.applyFailoverHost(t[e]);return _g(n),new Dh({...o,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case`MPEG`:{let n=this.applyFailoverHost(t[e]);return _g(n),new Qh({...o,source:n})}case`DASH_LIVE`:{let n=this.applyFailoverHost(t[e]);return _g(n),new Sa({...o,source:n,config:{...c_,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case`WEB_RTC_LIVE`:{let i=this.applyFailoverHost(t[e]);return _g(i),new mg({container:n,source:i,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})}case`DASH`:case`DASH_LIVE_WEBM`:throw Error(`${e} is no longer supported`);default:return gg(e)}}createChromecastProvider(e){let{sources:t,desiredState:n,meta:r,container:i}=this.params,a={meta:r,container:i,source:t,format:e,desiredState:n,output:this.providerOutput,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof St){let{chromecastConnector:e}=this.params.dependencies.chromecastInitializer;return _g(e),new nt({...a,chromecastConnector:e})}let o=this.params.dependencies.chromecastInitializer.connection$.getValue();return _g(o),new Ht({...a,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 gg(e)}}skipFormat(e){switch(e){case`SCREEN`:return this.screenFormatsIterator.next();case`CHROMECAST`:return this.chromecastFormatsIterator.next();default:return gg(e)}}handleNoFormatsError(e){switch(e){case`SCREEN`:this.noAvailableProvidersError$.next({forced:this.params.tuning.forceFormat,input:Object.keys(this.params.sources),supported:this.screenFormatsIterator.all()}),this.current$.next({type:void 0});return;case`CHROMECAST`:this.params.dependencies.chromecastInitializer.disconnect();return;default:return gg(e)}}applyFailoverHost(e){let t=this.mayday.currentFailoverUrlIndex;if(t===void 0)return e;let n=this.params.failoverHosts[t];if(!n)return e;let r=e=>{let t=new URL(e);return t.host=n,t.toString()};if(e===void 0)return e;if(`type`in e){if(e.type===`raw`)return e;if(e.type===`url`)return{...e,url:r(e.url)}}return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,r(t)]))}initProviderErrorHandling(){let e=new Tg;e.add(Cg(this.providerOutput.error$.pipe(yg(e=>!this.params.tuning.ignoreAudioRendererError||!e.message||!/AUDIO_RENDERER_ERROR/gi.test(e.message))),Fg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,playbackHangupNoDataThreshold:this.params.tuning.playbackHangupNoDataThreshold,useDelayedPlaybackHangupWithData:this.params.tuning.useDelayedPlaybackHangupWithData,position$:this.providerOutput.position$,videoLastDataObtainedTimestamp$:this.providerOutput.videoLastDataObtainedTimestamp$,providerChanged$:this.current$}).pipe(Sg(e=>({id:`ProviderHangup:${e}`,category:vg.WTF,message:`A ${e} transition failed to complete within reasonable time`,origin:`hangup`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),this.params.handleNetworkRecoverableErrorAsProviderError&&e.add(this.providerOutput.fetcherRecoverableError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{this.currentProviderStarted=!1;let t=this.params.desiredState.playbackState.transitionEnded$.pipe(yg(({to:e})=>e===`playing`),wg()).subscribe(()=>this.currentProviderStarted=!0);e.add(t)}));let t=()=>{let e=L.drain(),{logDashLiveDebug:t,sendDashLiveDebug:n}=this.params.tuning;if(t&&Og().console.log(`===== DASH_LIVE DEBUG START ====
|
|
257
257
|
`,e.map(({time:e,data:t,stack:n})=>`${e}: ${JSON.stringify(t)}${n?`
|