@vkontakte/videoplayer-core 2.0.103 → 2.0.104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +73 -27
- package/es2015.esm.js +72 -26
- package/es2018.cjs.js +73 -27
- package/es2018.esm.js +72 -26
- package/esnext.cjs.js +75 -29
- package/esnext.esm.js +73 -27
- package/evergreen.esm.js +73 -27
- package/package.json +7 -7
- package/types/enums/AndroidPreferredFormat.d.ts +8 -0
- package/types/enums/WebmCodecStrategy.d.ts +7 -0
- package/types/env.d.ts +1 -0
- package/types/index.d.ts +12 -0
- package/types/player/Player.d.ts +173 -0
- package/{index.d.ts → types/player/types.d.ts} +64 -391
- package/types/player/utils/optimisticPosition.d.ts +12 -0
- package/types/player/utils/selectContainer.d.ts +3 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +31 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +23 -0
- package/types/providers/ChromecastProvider/index.d.ts +33 -0
- package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +37 -0
- package/types/providers/DashLiveProvider/index.d.ts +2 -0
- package/types/providers/DashLiveProvider/types.d.ts +21 -0
- package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +25 -0
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +143 -0
- package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +33 -0
- package/types/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +42 -0
- package/types/providers/DashProvider/baseDashProvider.d.ts +52 -0
- package/types/providers/DashProvider/consts.d.ts +1 -0
- package/types/providers/DashProvider/dashCmafLiveProvider.d.ts +8 -0
- package/types/providers/DashProvider/dashProvider.d.ts +6 -0
- package/types/providers/DashProvider/index.d.ts +2 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +103 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +51 -0
- package/types/providers/DashProvider/lib/parsers/mpd.d.ts +3 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxModel.d.ts +20 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxParser.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +26 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/box.d.ts +79 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/fullBox.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/isobmff.d.ts +12 -0
- package/types/providers/DashProvider/lib/parsers/webm/ebml.d.ts +76 -0
- package/types/providers/DashProvider/lib/parsers/webm/webm.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +75 -0
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +18 -0
- package/types/providers/DashProvider/lib/types.d.ts +156 -0
- package/types/providers/DashProvider/lib/utils.d.ts +14 -0
- package/types/providers/HlsJsProvider/index.d.ts +24 -0
- package/types/providers/HlsLiveProvider/index.d.ts +30 -0
- package/types/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +3 -0
- package/types/providers/HlsProvider/index.d.ts +21 -0
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +21 -0
- package/types/providers/MpegProvider/index.d.ts +20 -0
- package/types/providers/ProviderContainer/index.d.ts +42 -0
- package/types/providers/ProviderContainer/types.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/playbackHangup.d.ts +12 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +188 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +60 -0
- package/types/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +9 -0
- package/types/providers/types.d.ts +83 -0
- package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +44 -0
- package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +30 -0
- package/types/providers/utils/HTMLVideoElement/clear.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/destroy.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/forcePlay.d.ts +7 -0
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +25 -0
- package/types/providers/utils/HTMLVideoElement/pool.d.ts +2 -0
- package/types/providers/utils/HTMLVideoElement/surface.d.ts +2 -0
- package/types/providers/utils/LiveOffset/index.d.ts +14 -0
- package/types/providers/utils/LiveOffset/types.d.ts +10 -0
- package/types/providers/utils/addQuicParam.d.ts +2 -0
- package/types/providers/utils/extractConnectionHeaders.d.ts +6 -0
- package/types/providers/utils/generateLiveUrl.d.ts +9 -0
- package/types/providers/utils/okQualityStringToVideoQuality.d.ts +3 -0
- package/types/providers/utils/parseFps.d.ts +1 -0
- package/types/providers/utils/syncDesiredState.d.ts +12 -0
- package/types/providers/utils/syncPlaybackState.d.ts +4 -0
- package/types/utils/3d/Camera3D.d.ts +14 -0
- package/types/utils/3d/CameraRotationManager.d.ts +62 -0
- package/types/utils/3d/Scene3D.d.ts +132 -0
- package/types/utils/3d/types.d.ts +25 -0
- package/types/utils/StateMachine/StateMachine.d.ts +19 -0
- package/types/utils/StateMachine/types.d.ts +60 -0
- package/types/utils/StatefulIterator/index.d.ts +13 -0
- package/types/utils/ThroughputEstimator.d.ts +25 -0
- package/types/utils/addScript.d.ts +2 -0
- package/types/utils/autoSelectVideoTrack.d.ts +26 -0
- package/types/utils/buffer/getBufferedRangeForPosition.d.ts +3 -0
- package/types/utils/buffer/getForwardBufferDuration.d.ts +3 -0
- package/types/utils/buffer/getTotalBufferDuration.d.ts +3 -0
- package/types/utils/buffer/isPositionBuffered.d.ts +3 -0
- package/types/utils/changePlaybackRate.d.ts +2 -0
- package/types/utils/hostnameFromUrl.d.ts +2 -0
- package/types/utils/isInPiP.d.ts +1 -0
- package/types/utils/link.d.ts +2 -0
- package/types/utils/mediaSource.d.ts +8 -0
- package/types/utils/observeElementVisibility.d.ts +3 -0
- package/types/utils/playbackTelemetry.d.ts +12 -0
- package/types/utils/setStateWithSubscribe.d.ts +3 -0
- package/types/utils/smoothedValue/baseSmoothedValue.d.ts +18 -0
- package/types/utils/smoothedValue/emaAndMaSmoothedValue.d.ts +7 -0
- package/types/utils/smoothedValue/emaTopExtremumValue.d.ts +10 -0
- package/types/utils/smoothedValue/smoothedValueFactory.d.ts +6 -0
- package/types/utils/smoothedValue/twoEmaSmoothedValue.d.ts +8 -0
- package/types/utils/smoothedValue/types.d.ts +26 -0
- package/types/utils/smoothedValue/utils.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +164 -0
- package/types/utils/videoFormat.d.ts +2 -0
package/es2015.esm.js
CHANGED
|
@@ -1,46 +1,92 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.104
|
|
3
|
+
* Mon, 24 Jun 2024 13:01:09 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as y,Subject as L,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as K,fromEvent as D,assertNever as H,merge as F,tap as Mi,map as $,observableFrom as Ge,filterChanged as pe,assertNonNullable as P,debounce as rt,getHighestQuality as Eu,timeout as $u,getCurrentBrowser as Fa,CurrentClientBrowser as Td,combine as Ue,once as we,mapTo as Rs,filter as fe,VideoQuality as De,now as le,assertNotEmptyArray as Au,videoSizeToQuality as Mt,isInvariantQuality as Bt,isHigher as fi,isLower as As,isHigherOrEqual as ca,isLowerOrEqual as Cs,interval as Ci,Observable as Va,videoQualityToHeight as wu,abortable as Re,getExponentialDelay as ws,throttle as ku,observeElementSize as Pu,isIOS as _u,CurrentClientDevice as Iu,safeStorage as fr,fillWithDefault as Ru,Logger as Cu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as VT,Subject as UT,Subscription as HT,ValueSubject as GT,VideoQuality as jT}from"@vkontakte/videoplayer-shared/es2015.esm.js";const Lu="2.0.103";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var Ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var ye;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ye||(ye={}));var ha;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ha||(ha={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var dt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip",i.INVISIBLE="invisible"})(dt||(dt={}));function te(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(c){try{d(s.next(c))}catch(l){n(l)}}function u(c){try{d(s.throw(c))}catch(l){n(l)}}function d(c){c.done?a(c.value):r(c.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function Ce(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(v,m){a.push([h,f,v,m])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(v){l(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,c):l(a[0][2],h)}function d(h){o("next",h)}function c(h){o("throw",h)}function l(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Du=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class xu{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ye.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new y(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Du("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(D(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.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 H(r.sessionState)}})).add(F(D(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Ge([s.getCastState()])).pipe(pe(),$(Ou),Mi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),c=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Ou=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return H(i)}};var pr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Us(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var je=function(i){try{return!!i()}catch(e){return!0}},Mu=je,Hs=!Mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Ed=Hs,$d=Function.prototype,fa=$d.call,Bu=Ed&&$d.bind.bind(fa,fa),Ye=Ed?Bu:function(i){return function(){return fa.apply(i,arguments)}},Ad=Ye,Nu=Ad({}.toString),Fu=Ad("".slice),Ui=function(i){return Fu(Nu(i),8,-1)},Vu=Ye,Uu=je,Hu=Ui,mr=Object,Gu=Vu("".split),ju=Uu(function(){return!mr("z").propertyIsEnumerable(0)})?function(i){return Hu(i)=="String"?Gu(i,""):mr(i)}:mr,Hi=function(i){return i==null},Yu=Hi,qu=TypeError,Ua=function(i){if(Yu(i))throw qu("Can't call method on "+i);return i},Wu=ju,zu=Ua,Gi=function(i){return Wu(zu(i))},Si={},ss=function(i){return i&&i.Math==Math&&i},Ee=ss(typeof globalThis=="object"&&globalThis)||ss(typeof window=="object"&&window)||ss(typeof self=="object"&&self)||ss(typeof pr=="object"&&pr)||function(){return this}()||pr||Function("return this")(),pa=typeof document=="object"&&document.all,Qu=typeof pa=="undefined"&&pa!==void 0,wd={all:pa,IS_HTMLDDA:Qu},kd=wd,Ku=kd.all,ge=kd.IS_HTMLDDA?function(i){return typeof i=="function"||i===Ku}:function(i){return typeof i=="function"},Ju=Ee,Xu=ge,Rn=Ju.WeakMap,Zu=Xu(Rn)&&/native code/.test(String(Rn)),Cn=ge,Pd=wd,ec=Pd.all,pt=Pd.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Cn(i)||i===ec}:function(i){return typeof i=="object"?i!==null:Cn(i)},tc=je,$t=!tc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Vt={},ic=Ee,Ln=pt,ma=ic.document,sc=Ln(ma)&&Ln(ma.createElement),Ha=function(i){return sc?ma.createElement(i):{}},rc=$t,ac=je,nc=Ha,_d=!rc&&!ac(function(){return Object.defineProperty(nc("div"),"a",{get:function(){return 7}}).a!=7}),oc=$t,dc=je,Id=oc&&dc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),lc=pt,uc=String,cc=TypeError,mt=function(i){if(lc(i))return i;throw cc(uc(i)+" is not an object")},hc=Hs,rs=Function.prototype.call,Oe=hc?rs.bind(rs):function(){return rs.apply(rs,arguments)},Ga={},vr=Ga,gr=Ee,fc=ge,Dn=function(i){return fc(i)?i:void 0},Ut=function(i,e){return arguments.length<2?Dn(vr[i])||Dn(gr[i]):vr[i]&&vr[i][e]||gr[i]&&gr[i][e]},pc=Ye,Gs=pc({}.isPrototypeOf),js=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Rd=Ee,Sr=js,xn=Rd.process,On=Rd.Deno,Mn=xn&&xn.versions||On&&On.version,Bn=Mn&&Mn.v8,ze,Ls;Bn&&(ze=Bn.split("."),Ls=ze[0]>0&&ze[0]<4?1:+(ze[0]+ze[1]));!Ls&&Sr&&(ze=Sr.match(/Edge\/(\d+)/),(!ze||ze[1]>=74)&&(ze=Sr.match(/Chrome\/(\d+)/),ze&&(Ls=+ze[1])));var Cd=Ls,Nn=Cd,mc=je,vc=Ee,gc=vc.String,Ld=!!Object.getOwnPropertySymbols&&!mc(function(){var i=Symbol();return!gc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Nn&&Nn<41}),Sc=Ld,Dd=Sc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",bc=Ut,yc=ge,Tc=Gs,Ec=Dd,$c=Object,xd=Ec?function(i){return typeof i=="symbol"}:function(i){var e=bc("Symbol");return yc(e)&&Tc(e.prototype,$c(i))},Ac=String,Ys=function(i){try{return Ac(i)}catch(e){return"Object"}},wc=ge,kc=Ys,Pc=TypeError,Ht=function(i){if(wc(i))return i;throw Pc(kc(i)+" is not a function")},_c=Ht,Ic=Hi,qs=function(i,e){var t=i[e];return Ic(t)?void 0:_c(t)},br=Oe,yr=ge,Tr=pt,Rc=TypeError,Cc=function(i,e){var t,s;if(e==="string"&&yr(t=i.toString)&&!Tr(s=br(t,i))||yr(t=i.valueOf)&&!Tr(s=br(t,i))||e!=="string"&&yr(t=i.toString)&&!Tr(s=br(t,i)))return s;throw Rc("Can't convert object to primitive value")},Od={exports:{}},Lc=!0,Fn=Ee,Dc=Object.defineProperty,xc=function(i,e){try{Dc(Fn,i,{value:e,configurable:!0,writable:!0})}catch(t){Fn[i]=e}return e},Oc=Ee,Mc=xc,Vn="__core-js_shared__",Bc=Oc[Vn]||Mc(Vn,{}),ja=Bc,Un=ja;(Od.exports=function(i,e){return Un[i]||(Un[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Md=Od.exports,Nc=Ua,Fc=Object,Ws=function(i){return Fc(Nc(i))},Vc=Ye,Uc=Ws,Hc=Vc({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return Hc(Uc(e),t)},Gc=Ye,jc=0,Yc=Math.random(),qc=Gc(1 .toString),Bd=function(i){return"Symbol("+(i===void 0?"":i)+")_"+qc(++jc+Yc,36)},Wc=Ee,zc=Md,Hn=nt,Qc=Bd,Kc=Ld,Jc=Dd,li=Wc.Symbol,Er=zc("wks"),Xc=Jc?li.for||li:li&&li.withoutSetter||Qc,_e=function(i){return Hn(Er,i)||(Er[i]=Kc&&Hn(li,i)?li[i]:Xc("Symbol."+i)),Er[i]},Zc=Oe,Gn=pt,jn=xd,eh=qs,th=Cc,ih=_e,sh=TypeError,rh=ih("toPrimitive"),ah=function(i,e){if(!Gn(i)||jn(i))return i;var t=eh(i,rh),s;if(t){if(e===void 0&&(e="default"),s=Zc(t,i,e),!Gn(s)||jn(s))return s;throw sh("Can't convert object to primitive value")}return e===void 0&&(e="number"),th(i,e)},nh=ah,oh=xd,Ya=function(i){var e=nh(i,"string");return oh(e)?e:e+""},dh=$t,lh=_d,uh=Id,as=mt,Yn=Ya,ch=TypeError,$r=Object.defineProperty,hh=Object.getOwnPropertyDescriptor,Ar="enumerable",wr="configurable",kr="writable";Vt.f=dh?uh?function(e,t,s){if(as(e),t=Yn(t),as(s),typeof e=="function"&&t==="prototype"&&"value"in s&&kr in s&&!s[kr]){var r=hh(e,t);r&&r[kr]&&(e[t]=s.value,s={configurable:wr in s?s[wr]:r[wr],enumerable:Ar in s?s[Ar]:r[Ar],writable:!1})}return $r(e,t,s)}:$r:function(e,t,s){if(as(e),t=Yn(t),as(s),lh)try{return $r(e,t,s)}catch(r){}if("get"in s||"set"in s)throw ch("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var zs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},fh=$t,ph=Vt,mh=zs,ji=fh?function(i,e,t){return ph.f(i,e,mh(1,t))}:function(i,e,t){return i[e]=t,i},vh=Md,gh=Bd,qn=vh("keys"),qa=function(i){return qn[i]||(qn[i]=gh(i))},Wa={},Sh=Zu,Nd=Ee,bh=pt,yh=ji,Pr=nt,_r=ja,Th=qa,Eh=Wa,Wn="Object already initialized",va=Nd.TypeError,$h=Nd.WeakMap,Ds,Bi,xs,Ah=function(i){return xs(i)?Bi(i):Ds(i,{})},wh=function(i){return function(e){var t;if(!bh(e)||(t=Bi(e)).type!==i)throw va("Incompatible receiver, "+i+" required");return t}};if(Sh||_r.state){var Ze=_r.state||(_r.state=new $h);Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ds=function(i,e){if(Ze.has(i))throw va(Wn);return e.facade=i,Ze.set(i,e),e},Bi=function(i){return Ze.get(i)||{}},xs=function(i){return Ze.has(i)}}else{var ei=Th("state");Eh[ei]=!0,Ds=function(i,e){if(Pr(i,ei))throw va(Wn);return e.facade=i,yh(i,ei,e),e},Bi=function(i){return Pr(i,ei)?i[ei]:{}},xs=function(i){return Pr(i,ei)}}var Fd={set:Ds,get:Bi,has:xs,enforce:Ah,getterFor:wh},kh=Hs,Vd=Function.prototype,zn=Vd.apply,Qn=Vd.call,Ud=typeof Reflect=="object"&&Reflect.apply||(kh?Qn.bind(zn):function(){return Qn.apply(zn,arguments)}),Ph=Ui,_h=Ye,Hd=function(i){if(Ph(i)==="Function")return _h(i)},za={},Gd={},jd={}.propertyIsEnumerable,Yd=Object.getOwnPropertyDescriptor,Ih=Yd&&!jd.call({1:2},1);Gd.f=Ih?function(e){var t=Yd(this,e);return!!t&&t.enumerable}:jd;var Rh=$t,Ch=Oe,Lh=Gd,Dh=zs,xh=Gi,Oh=Ya,Mh=nt,Bh=_d,Kn=Object.getOwnPropertyDescriptor;za.f=Rh?Kn:function(e,t){if(e=xh(e),t=Oh(t),Bh)try{return Kn(e,t)}catch(s){}if(Mh(e,t))return Dh(!Ch(Lh.f,e,t),e[t])};var Nh=je,Fh=ge,Vh=/#|\.prototype\./,Yi=function(i,e){var t=Hh[Uh(i)];return t==jh?!0:t==Gh?!1:Fh(e)?Nh(e):!!e},Uh=Yi.normalize=function(i){return String(i).replace(Vh,".").toLowerCase()},Hh=Yi.data={},Gh=Yi.NATIVE="N",jh=Yi.POLYFILL="P",qd=Yi,Jn=Hd,Yh=Ht,qh=Hs,Wh=Jn(Jn.bind),Qs=function(i,e){return Yh(i),e===void 0?i:qh?Wh(i,e):function(){return i.apply(e,arguments)}},ns=Ee,zh=Ud,Qh=Hd,Kh=ge,Jh=za.f,Xh=qd,ti=Ga,Zh=Qs,ii=ji,Xn=nt,ef=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return zh(i,this,arguments)};return e.prototype=i.prototype,e},Ke=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?ns:r?ns[t]:(ns[t]||{}).prototype,o=s?ti:ti[t]||ii(ti,t,{})[t],u=o.prototype,d,c,l,h,f,v,m,g,S;for(h in e)d=Xh(s?h:t+(r?".":"#")+h,i.forced),c=!d&&n&&Xn(n,h),v=o[h],c&&(i.dontCallGetSet?(S=Jh(n,h),m=S&&S.value):m=n[h]),f=c&&m?m:e[h],!(c&&typeof v==typeof f)&&(i.bind&&c?g=Zh(f,ns):i.wrap&&c?g=ef(f):a&&Kh(f)?g=Qh(f):g=f,(i.sham||f&&f.sham||v&&v.sham)&&ii(g,"sham",!0),ii(o,h,g),a&&(l=t+"Prototype",Xn(ti,l)||ii(ti,l,{}),ii(ti[l],h,f),i.real&&u&&(d||!u[h])&&ii(u,h,f)))},ga=$t,tf=nt,Wd=Function.prototype,sf=ga&&Object.getOwnPropertyDescriptor,Qa=tf(Wd,"name"),rf=Qa&&function(){}.name==="something",af=Qa&&(!ga||ga&&sf(Wd,"name").configurable),nf={EXISTS:Qa,PROPER:rf,CONFIGURABLE:af},zd={},of=Math.ceil,df=Math.floor,lf=Math.trunc||function(e){var t=+e;return(t>0?df:of)(t)},uf=lf,Ka=function(i){var e=+i;return e!==e||e===0?0:uf(e)},cf=Ka,hf=Math.max,ff=Math.min,pf=function(i,e){var t=cf(i);return t<0?hf(t+e,0):ff(t,e)},mf=Ka,vf=Math.min,gf=function(i){return i>0?vf(mf(i),9007199254740991):0},Sf=gf,Ja=function(i){return Sf(i.length)},bf=Gi,yf=pf,Tf=Ja,Zn=function(i){return function(e,t,s){var r=bf(e),a=Tf(r),n=yf(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},Ef={includes:Zn(!0),indexOf:Zn(!1)},$f=Ye,Ir=nt,Af=Gi,wf=Ef.indexOf,kf=Wa,eo=$f([].push),Pf=function(i,e){var t=Af(i),s=0,r=[],a;for(a in t)!Ir(kf,a)&&Ir(t,a)&&eo(r,a);for(;e.length>s;)Ir(t,a=e[s++])&&(~wf(r,a)||eo(r,a));return r},Qd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_f=Pf,If=Qd,Rf=Object.keys||function(e){return _f(e,If)},Cf=$t,Lf=Id,Df=Vt,xf=mt,Of=Gi,Mf=Rf;zd.f=Cf&&!Lf?Object.defineProperties:function(e,t){xf(e);for(var s=Of(t),r=Mf(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],s[o]);return e};var Bf=Ut,Kd=Bf("document","documentElement"),Nf=mt,Ff=zd,to=Qd,Vf=Wa,Uf=Kd,Hf=Ha,Gf=qa,io=">",so="<",Sa="prototype",ba="script",Jd=Gf("IE_PROTO"),Rr=function(){},Xd=function(i){return so+ba+io+i+so+"/"+ba+io},ro=function(i){i.write(Xd("")),i.close();var e=i.parentWindow.Object;return i=null,e},jf=function(){var i=Hf("iframe"),e="java"+ba+":",t;return i.style.display="none",Uf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Xd("document.F=Object")),t.close(),t.F},os,ks=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&os?ro(os):jf():ro(os);for(var i=to.length;i--;)delete ks[Sa][to[i]];return ks()};Vf[Jd]=!0;var Zd=Object.create||function(e,t){var s;return e!==null?(Rr[Sa]=Nf(e),s=new Rr,Rr[Sa]=null,s[Jd]=e):s=ks(),t===void 0?s:Ff.f(s,t)},Yf=je,qf=!Yf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Wf=nt,zf=ge,Qf=Ws,Kf=qa,Jf=qf,ao=Kf("IE_PROTO"),ya=Object,Xf=ya.prototype,el=Jf?ya.getPrototypeOf:function(i){var e=Qf(i);if(Wf(e,ao))return e[ao];var t=e.constructor;return zf(t)&&e instanceof t?t.prototype:e instanceof ya?Xf:null},Zf=ji,Xa=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Zf(i,e,t),i},ep=je,tp=ge,ip=pt,sp=Zd,no=el,rp=Xa,ap=_e,Ta=ap("iterator"),tl=!1,ht,Cr,Lr;[].keys&&(Lr=[].keys(),"next"in Lr?(Cr=no(no(Lr)),Cr!==Object.prototype&&(ht=Cr)):tl=!0);var np=!ip(ht)||ep(function(){var i={};return ht[Ta].call(i)!==i});np?ht={}:ht=sp(ht);tp(ht[Ta])||rp(ht,Ta,function(){return this});var il={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:tl},op=_e,dp=op("toStringTag"),sl={};sl[dp]="z";var Za=String(sl)==="[object z]",lp=Za,up=ge,Ps=Ui,cp=_e,hp=cp("toStringTag"),fp=Object,pp=Ps(function(){return arguments}())=="Arguments",mp=function(i,e){try{return i[e]}catch(t){}},qi=lp?Ps:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=mp(e=fp(i),hp))=="string"?t:pp?Ps(e):(s=Ps(e))=="Object"&&up(e.callee)?"Arguments":s},vp=Za,gp=qi,Sp=vp?{}.toString:function(){return"[object "+gp(this)+"]"},bp=Za,yp=Vt.f,Tp=ji,Ep=nt,$p=Sp,Ap=_e,oo=Ap("toStringTag"),en=function(i,e,t,s){if(i){var r=t?i:i.prototype;Ep(r,oo)||yp(r,oo,{configurable:!0,value:e}),s&&!bp&&Tp(r,"toString",$p)}},wp=il.IteratorPrototype,kp=Zd,Pp=zs,_p=en,Ip=Si,Rp=function(){return this},Cp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=kp(wp,{next:Pp(+!s,t)}),_p(i,r,!1,!0),Ip[r]=Rp,i},Lp=Ke,Dp=Oe,rl=nf,xp=Cp,Op=el,Mp=en,lo=Xa,Bp=_e,uo=Si,al=il,Np=rl.PROPER;rl.CONFIGURABLE;al.IteratorPrototype;var ds=al.BUGGY_SAFARI_ITERATORS,Dr=Bp("iterator"),co="keys",ls="values",ho="entries",Fp=function(){return this},Vp=function(i,e,t,s,r,a,n){xp(t,e,s);var o=function(S){if(S===r&&h)return h;if(!ds&&S in c)return c[S];switch(S){case co:return function(){return new t(this,S)};case ls:return function(){return new t(this,S)};case ho:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,c=i.prototype,l=c[Dr]||c["@@iterator"]||r&&c[r],h=!ds&&l||o(r),f=e=="Array"&&c.entries||l,v,m,g;if(f&&(v=Op(f.call(new i)),v!==Object.prototype&&v.next&&(Mp(v,u,!0,!0),uo[u]=Fp)),Np&&r==ls&&l&&l.name!==ls&&(d=!0,h=function(){return Dp(l,this)}),r)if(m={values:o(ls),keys:a?h:o(co),entries:o(ho)},n)for(g in m)(ds||d||!(g in c))&&lo(c,g,m[g]);else Lp({target:e,proto:!0,forced:ds||d},m);return n&&c[Dr]!==h&&lo(c,Dr,h,{name:r}),uo[e]=h,m},Up=function(i,e){return{value:i,done:e}},Hp=Gi,fo=Si,nl=Fd;Vt.f;var Gp=Vp,us=Up,ol="Array Iterator",jp=nl.set,Yp=nl.getterFor(ol);Gp(Array,"Array",function(i,e){jp(this,{type:ol,target:Hp(i),index:0,kind:e})},function(){var i=Yp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,us(void 0,!0)):t=="keys"?us(s,!1):t=="values"?us(e[s],!1):us([s,e[s]],!1)},"values");fo.Arguments=fo.Array;var qp=_e,Wp=Si,zp=qp("iterator"),Qp=Array.prototype,Kp=function(i){return i!==void 0&&(Wp.Array===i||Qp[zp]===i)},Jp=qi,po=qs,Xp=Hi,Zp=Si,em=_e,tm=em("iterator"),dl=function(i){if(!Xp(i))return po(i,tm)||po(i,"@@iterator")||Zp[Jp(i)]},im=Oe,sm=Ht,rm=mt,am=Ys,nm=dl,om=TypeError,dm=function(i,e){var t=arguments.length<2?nm(i):e;if(sm(t))return rm(im(t,i));throw om(am(i)+" is not iterable")},lm=Oe,mo=mt,um=qs,cm=function(i,e,t){var s,r;mo(i);try{if(s=um(i,"return"),!s){if(e==="throw")throw t;return t}s=lm(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return mo(s),t},hm=Qs,fm=Oe,pm=mt,mm=Ys,vm=Kp,gm=Ja,vo=Gs,Sm=dm,bm=dl,go=cm,ym=TypeError,_s=function(i,e){this.stopped=i,this.result=e},So=_s.prototype,tn=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=hm(e,s),d,c,l,h,f,v,m,g=function(E){return d&&go(d,"normal",E),new _s(!0,E)},S=function(E){return r?(pm(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)d=i.iterator;else if(n)d=i;else{if(c=bm(i),!c)throw ym(mm(i)+" is not iterable");if(vm(c)){for(l=0,h=gm(i);h>l;l++)if(f=S(i[l]),f&&vo(So,f))return f;return new _s(!1)}d=Sm(i,c)}for(v=a?i.next:d.next;!(m=fm(v,d)).done;){try{f=S(m.value)}catch(E){go(d,"throw",E)}if(typeof f=="object"&&f&&vo(So,f))return f}return new _s(!1)},Tm=Ya,Em=Vt,$m=zs,Am=function(i,e,t){var s=Tm(e);s in i?Em.f(i,s,$m(0,t)):i[s]=t},wm=Ke,km=tn,Pm=Am;wm({target:"Object",stat:!0},{fromEntries:function(e){var t={};return km(e,function(s,r){Pm(t,s,r)},{AS_ENTRIES:!0}),t}});var _m=Ga,Im=_m.Object.fromEntries,Rm={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Cm=Rm,Lm=Ee,Dm=qi,xm=ji,bo=Si,Om=_e,yo=Om("toStringTag");for(var xr in Cm){var To=Lm[xr],Or=To&&To.prototype;Or&&Dm(Or)!==yo&&xm(Or,yo,xr),bo[xr]=bo.Array}var Mm=Im,Bm=Mm,Nm=Bm,Fm=Nm,Os=Us(Fm),Vm=Ui,Ks=typeof process!="undefined"&&Vm(process)=="process",Um=Vt,Hm=function(i,e,t){return Um.f(i,e,t)},Gm=Ut,jm=Hm,Ym=_e,qm=$t,Eo=Ym("species"),Wm=function(i){var e=Gm(i);qm&&e&&!e[Eo]&&jm(e,Eo,{configurable:!0,get:function(){return this}})},zm=Gs,Qm=TypeError,Km=function(i,e){if(zm(e,i))return i;throw Qm("Incorrect invocation")},Jm=Ye,Xm=ge,Ea=ja,Zm=Jm(Function.toString);Xm(Ea.inspectSource)||(Ea.inspectSource=function(i){return Zm(i)});var ll=Ea.inspectSource,ev=Ye,tv=je,ul=ge,iv=qi,sv=Ut,rv=ll,cl=function(){},av=[],hl=sv("Reflect","construct"),sn=/^\s*(?:class|function)\b/,nv=ev(sn.exec),ov=!sn.exec(cl),_i=function(e){if(!ul(e))return!1;try{return hl(cl,av,e),!0}catch(t){return!1}},fl=function(e){if(!ul(e))return!1;switch(iv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ov||!!nv(sn,rv(e))}catch(t){return!0}};fl.sham=!0;var dv=!hl||tv(function(){var i;return _i(_i.call)||!_i(Object)||!_i(function(){i=!0})||i})?fl:_i,lv=dv,uv=Ys,cv=TypeError,hv=function(i){if(lv(i))return i;throw cv(uv(i)+" is not a constructor")},$o=mt,fv=hv,pv=Hi,mv=_e,vv=mv("species"),pl=function(i,e){var t=$o(i).constructor,s;return t===void 0||pv(s=$o(t)[vv])?e:fv(s)},gv=Ye,Sv=gv([].slice),bv=TypeError,yv=function(i,e){if(i<e)throw bv("Not enough arguments");return i},Tv=js,ml=/(?:ipad|iphone|ipod).*applewebkit/i.test(Tv),xe=Ee,Ev=Ud,$v=Qs,Ao=ge,Av=nt,vl=je,wo=Kd,wv=Sv,ko=Ha,kv=yv,Pv=ml,_v=Ks,$a=xe.setImmediate,Aa=xe.clearImmediate,Iv=xe.process,Mr=xe.Dispatch,Rv=xe.Function,Po=xe.MessageChannel,Cv=xe.String,Br=0,Li={},_o="onreadystatechange",Ni,Rt,Nr,Fr;vl(function(){Ni=xe.location});var rn=function(i){if(Av(Li,i)){var e=Li[i];delete Li[i],e()}},Vr=function(i){return function(){rn(i)}},Io=function(i){rn(i.data)},Ro=function(i){xe.postMessage(Cv(i),Ni.protocol+"//"+Ni.host)};(!$a||!Aa)&&($a=function(e){kv(arguments.length,1);var t=Ao(e)?e:Rv(e),s=wv(arguments,1);return Li[++Br]=function(){Ev(t,void 0,s)},Rt(Br),Br},Aa=function(e){delete Li[e]},_v?Rt=function(i){Iv.nextTick(Vr(i))}:Mr&&Mr.now?Rt=function(i){Mr.now(Vr(i))}:Po&&!Pv?(Nr=new Po,Fr=Nr.port2,Nr.port1.onmessage=Io,Rt=$v(Fr.postMessage,Fr)):xe.addEventListener&&Ao(xe.postMessage)&&!xe.importScripts&&Ni&&Ni.protocol!=="file:"&&!vl(Ro)?(Rt=Ro,xe.addEventListener("message",Io,!1)):_o in ko("script")?Rt=function(i){wo.appendChild(ko("script"))[_o]=function(){wo.removeChild(this),rn(i)}}:Rt=function(i){setTimeout(Vr(i),0)});var gl={set:$a,clear:Aa},Sl=function(){this.head=null,this.tail=null};Sl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var bl=Sl,Lv=js,Dv=/ipad|iphone|ipod/i.test(Lv)&&typeof Pebble!="undefined",xv=js,Ov=/web0s(?!.*chrome)/i.test(xv),Nt=Ee,Co=Qs,Mv=za.f,Ur=gl.set,Bv=bl,Nv=ml,Fv=Dv,Vv=Ov,Hr=Ks,Lo=Nt.MutationObserver||Nt.WebKitMutationObserver,Do=Nt.document,xo=Nt.process,cs=Nt.Promise,Oo=Mv(Nt,"queueMicrotask"),wa=Oo&&Oo.value,si,Gr,jr,hs,Mo;if(!wa){var fs=new Bv,ps=function(){var i,e;for(Hr&&(i=xo.domain)&&i.exit();e=fs.get();)try{e()}catch(t){throw fs.head&&si(),t}i&&i.enter()};!Nv&&!Hr&&!Vv&&Lo&&Do?(Gr=!0,jr=Do.createTextNode(""),new Lo(ps).observe(jr,{characterData:!0}),si=function(){jr.data=Gr=!Gr}):!Fv&&cs&&cs.resolve?(hs=cs.resolve(void 0),hs.constructor=cs,Mo=Co(hs.then,hs),si=function(){Mo(ps)}):Hr?si=function(){xo.nextTick(ps)}:(Ur=Co(Ur,Nt),si=function(){Ur(ps)}),wa=function(i){fs.head||si(),fs.add(i)}}var Uv=wa,Hv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},an=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Gv=Ee,bi=Gv.Promise,yl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",jv=yl,Yv=Ks,qv=!jv&&!Yv&&typeof window=="object"&&typeof document=="object",Wv=Ee,Di=bi,zv=ge,Qv=qd,Kv=ll,Jv=_e,Xv=qv,Zv=yl,Yr=Cd,Bo=Di&&Di.prototype,eg=Jv("species"),ka=!1,Tl=zv(Wv.PromiseRejectionEvent),tg=Qv("Promise",function(){var i=Kv(Di),e=i!==String(Di);if(!e&&Yr===66||!(Bo.catch&&Bo.finally))return!0;if(!Yr||Yr<51||!/native code/.test(i)){var t=new Di(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[eg]=s,ka=t.then(function(){})instanceof s,!ka)return!0}return!e&&(Xv||Zv)&&!Tl}),Wi={CONSTRUCTOR:tg,REJECTION_EVENT:Tl,SUBCLASSING:ka},yi={},No=Ht,ig=TypeError,sg=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw ig("Bad Promise constructor");e=s,t=r}),this.resolve=No(e),this.reject=No(t)};yi.f=function(i){return new sg(i)};var rg=Ke,Ms=Ks,Et=Ee,zi=Oe,ag=Xa,ng=en,og=Wm,dg=Ht,Pa=ge,lg=pt,ug=Km,cg=pl,El=gl.set,nn=Uv,hg=Hv,fg=an,pg=bl,$l=Fd,_a=bi,on=Wi,Al=yi,Js="Promise",wl=on.CONSTRUCTOR,mg=on.REJECTION_EVENT;on.SUBCLASSING;var qr=$l.getterFor(Js),vg=$l.set,gg=_a&&_a.prototype,ui=_a,Wr=gg,kl=Et.TypeError,Ia=Et.document,dn=Et.process,Ra=Al.f,Sg=Ra,bg=!!(Ia&&Ia.createEvent&&Et.dispatchEvent),Pl="unhandledrejection",yg="rejectionhandled",Fo=0,_l=1,Tg=2,ln=1,Il=2,ms,Vo,Eg,Rl=function(i){var e;return lg(i)&&Pa(e=i.then)?e:!1},Cl=function(i,e){var t=e.value,s=e.state==_l,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,c;try{r?(s||(e.rejection===Il&&Ag(e),e.rejection=ln),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===i.promise?n(kl("Promise-chain cycle")):(d=Rl(u))?zi(d,u,a,n):a(u)):n(t)}catch(l){o&&!c&&o.exit(),n(l)}},Ll=function(i,e){i.notified||(i.notified=!0,nn(function(){for(var t=i.reactions,s;s=t.get();)Cl(s,i);i.notified=!1,e&&!i.rejection&&$g(i)}))},Dl=function(i,e,t){var s,r;bg?(s=Ia.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Et.dispatchEvent(s)):s={promise:e,reason:t},!mg&&(r=Et["on"+i])?r(s):i===Pl&&hg("Unhandled promise rejection",t)},$g=function(i){zi(El,Et,function(){var e=i.facade,t=i.value,s=Uo(i),r;if(s&&(r=fg(function(){Ms?dn.emit("unhandledRejection",t,e):Dl(Pl,e,t)}),i.rejection=Ms||Uo(i)?Il:ln,r.error))throw r.value})},Uo=function(i){return i.rejection!==ln&&!i.parent},Ag=function(i){zi(El,Et,function(){var e=i.facade;Ms?dn.emit("rejectionHandled",e):Dl(yg,e,i.value)})},ci=function(i,e,t){return function(s){i(e,s,t)}},pi=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Tg,Ll(i,!0))},Ca=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw kl("Promise can't be resolved itself");var s=Rl(e);s?nn(function(){var r={done:!1};try{zi(s,e,ci(Ca,r,i),ci(pi,r,i))}catch(a){pi(r,a,i)}}):(i.value=e,i.state=_l,Ll(i,!1))}catch(r){pi({done:!1},r,i)}}};wl&&(ui=function(e){ug(this,Wr),dg(e),zi(ms,this);var t=qr(this);try{e(ci(Ca,t),ci(pi,t))}catch(s){pi(t,s)}},Wr=ui.prototype,ms=function(e){vg(this,{type:Js,done:!1,notified:!1,parent:!1,reactions:new pg,rejection:!1,state:Fo,value:void 0})},ms.prototype=ag(Wr,"then",function(e,t){var s=qr(this),r=Ra(cg(this,ui));return s.parent=!0,r.ok=Pa(e)?e:!0,r.fail=Pa(t)&&t,r.domain=Ms?dn.domain:void 0,s.state==Fo?s.reactions.add(r):nn(function(){Cl(r,s)}),r.promise}),Vo=function(){var i=new ms,e=qr(i);this.promise=i,this.resolve=ci(Ca,e),this.reject=ci(pi,e)},Al.f=Ra=function(i){return i===ui||i===Eg?new Vo(i):Sg(i)});rg({global:!0,constructor:!0,wrap:!0,forced:wl},{Promise:ui});ng(ui,Js,!1,!0);og(Js);var wg=_e,xl=wg("iterator"),Ol=!1;try{var kg=0,Ho={next:function(){return{done:!!kg++}},return:function(){Ol=!0}};Ho[xl]=function(){return this},Array.from(Ho,function(){throw 2})}catch(i){}var Pg=function(i,e){if(!e&&!Ol)return!1;var t=!1;try{var s={};s[xl]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},_g=bi,Ig=Pg,Rg=Wi.CONSTRUCTOR,Ml=Rg||!Ig(function(i){_g.all(i).then(void 0,function(){})}),Cg=Ke,Lg=Oe,Dg=Ht,xg=yi,Og=an,Mg=tn,Bg=Ml;Cg({target:"Promise",stat:!0,forced:Bg},{all:function(e){var t=this,s=xg.f(t),r=s.resolve,a=s.reject,n=Og(function(){var o=Dg(t.resolve),u=[],d=0,c=1;Mg(e,function(l){var h=d++,f=!1;c++,Lg(o,t,l).then(function(v){f||(f=!0,u[h]=v,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),s.promise}});var Ng=Ke,Fg=Wi.CONSTRUCTOR,Go=bi;Go&&Go.prototype;Ng({target:"Promise",proto:!0,forced:Fg,real:!0},{catch:function(i){return this.then(void 0,i)}});var Vg=Ke,Ug=Oe,Hg=Ht,Gg=yi,jg=an,Yg=tn,qg=Ml;Vg({target:"Promise",stat:!0,forced:qg},{race:function(e){var t=this,s=Gg.f(t),r=s.reject,a=jg(function(){var n=Hg(t.resolve);Yg(e,function(o){Ug(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Wg=Ke,zg=Oe,Qg=yi,Kg=Wi.CONSTRUCTOR;Wg({target:"Promise",stat:!0,forced:Kg},{reject:function(e){var t=Qg.f(this);return zg(t.reject,void 0,e),t.promise}});var Jg=mt,Xg=pt,Zg=yi,Bl=function(i,e){if(Jg(i),Xg(e)&&e.constructor===i)return e;var t=Zg.f(i),s=t.resolve;return s(e),t.promise},eS=Ke,tS=Ut,iS=Lc,sS=bi,rS=Wi.CONSTRUCTOR,aS=Bl,nS=tS("Promise"),oS=!rS;eS({target:"Promise",stat:!0,forced:iS},{resolve:function(e){return aS(oS&&this===nS?sS:this,e)}});var dS=Ke,La=bi,lS=je,uS=Ut,cS=ge,hS=pl,jo=Bl,fS=La&&La.prototype,pS=!!La&&lS(function(){fS.finally.call({then:function(){}},function(){})});dS({target:"Promise",proto:!0,real:!0,forced:pS},{finally:function(i){var e=hS(this,uS("Promise")),t=cS(i);return this.then(t?function(s){return jo(e,i()).then(function(){return s})}:i,t?function(s){return jo(e,i()).then(function(){throw s})}:i)}});var mS=Ut,un=mS,vS=un,gS=vS("Promise","finally"),SS=gS,bS=SS,yS=bS,TS=yS,cn=Us(TS),Se;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Se||(Se={}));var Qe=(i,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Se.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:H(t)}return i};const Yo=(i,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class he{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=F(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=F(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||_(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const ES=i=>{switch(i){case b.MPEG:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return H(i)}};var U;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const $S=5,AS=5,wS=500,qo=7e3;class kS{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new he(U.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==U.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case U.PLAYING:case U.PAUSED:case U.READY:break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PLAYING:{switch(s){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PAUSED:{switch(s){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}default:H(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ES(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const 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);const e=new re;this.subscription.add(e),this.subscription.add(F(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(rt(wS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-a)>$S)&&r.next(o),a=o})),e.add(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<AS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.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:H(n)}}),t(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(D(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=F(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(rt(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===U.READY&&this.videoState.setState(U.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const c=s[e];P(c);const l=Eu(Object.keys(c));P(l);const h=c[l];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const c=s[e];P(c),r=c.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:{const c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const c=s[e];P(c),r=Qe(c.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:c,thrown:l}),l}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add($u(qo).subscribe(()=>a(`timeout(${qo})`)))});cn(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const hn=i=>{i.removeAttribute("src"),i.load()},PS=i=>{try{i.pause(),i.playbackRate=0,hn(i),i.remove()}catch(e){console.error(e)}};class _S{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Da=window.WeakMap?new WeakMap:new _S,Gt=i=>{let e=i.querySelector("video");const t=!!e;return e?hn(e):(e=document.createElement("video"),i.appendChild(e)),Da.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},jt=i=>{const e=Da.get(i);Da.delete(i),e?hn(i):PS(i)},ut=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new re;return r&&d.add(r.subscribe(c=>{const l=i.getState();s(c,l)&&i.setState(c)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},a)),d},Qi=(i,e,t)=>ut(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),Yt=(i,e,t,s)=>ut(e,()=>({muted:i.muted,volume:i.volume}),r=>{_(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),Ti=(i,e,t,s)=>ut(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),IS=i=>["__",i.language,i.label].join("|"),RS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class At{constructor(){this.available$=new L,this.current$=new y(void 0),this.error$=new L,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(ut(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ut(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ut(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ut(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(D(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(F(D(e,"addtrack"),D(e,"removetrack"),Ge(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),pe((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(F(D(e,"change"),Ge(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),pe()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(D(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,c,l,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((l=(c=o.target)===null||c===void 0?void 0:c.cues)!==null&&l!==void 0?l:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(D(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(At.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:IS(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(K(e)||!RS(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");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){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.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)}}class fn{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Nl=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Wo=i=>{const e=Nl(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},CS=i=>{const e=Nl(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},LS=3;var DS=(i,e,t=LS)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const qt=i=>{const e=A=>D(i,A).pipe(Rs(void 0)),s=F(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>D(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),pe()),r=F(D(i,"progress"),D(i,"timeupdate")).pipe($(()=>DS(i.buffered,i.currentTime))),n=Fa().browser===Td.Safari?Ue({play:e("play").pipe(we()),playing:e("playing")}).pipe(Rs(void 0)):e("playing"),o=D(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=D(i,"ratechange").pipe($(()=>i.playbackRate)),d=D(i,"error").pipe(fe(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),c=D(i,"timeupdate").pipe($(()=>i.currentTime)),l=new L,h=.3;let f;c.subscribe(A=>{i.loop&&_(f)&&_(A)&&f>=i.duration-h&&A<=h&&l.next(f),f=A});const v=D(i,"enterpictureinpicture"),m=D(i,"leavepictureinpicture"),g=new y(CS(i));v.subscribe(()=>g.next(!0)),m.subscribe(()=>g.next(!1));const S=new y(Wo(i));return D(i,"fullscreenchange").pipe($(()=>Wo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(fe(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:D(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Xs=i=>{switch(i){case"mobile":return De.Q_144P;case"lowest":return De.Q_240P;case"low":return De.Q_360P;case"sd":case"medium":return De.Q_480P;case"hd":case"high":return De.Q_720P;case"fullhd":case"full":return De.Q_1080P;case"quadhd":case"quad":return De.Q_1440P;case"ultrahd":case"ultra":return De.Q_2160P}},xS=Ke,OS=Ws,MS=Ja,BS=Ka;xS({target:"Array",proto:!0},{at:function(e){var t=OS(this),s=MS(t),r=BS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var NS=un,FS=NS("Array","at"),VS=FS,US=VS,HS=US,GS=HS,lt=Us(GS);let pn=!1,ct={};const jS=i=>{pn=i},YS=()=>{ct={}},qS=i=>{i(ct)},vs=(i,e)=>{var t;pn&&(ct.meta=(t=ct.meta)!==null&&t!==void 0?t:{},ct.meta[i]=e)};class tt{constructor(e){this.name=e}next(e){var t,s;if(!pn)return;ct.series=(t=ct.series)!==null&&t!==void 0?t:{};const r=(s=ct.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ct.series[this.name]=r}}var xt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(xt||(xt={}));const WS=new tt("best_bitrate"),zS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class QS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const KS='Assertion "ABR Tracks is empty array" failed',Zs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{var h,f,v,m,g;Au(i,KS);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&Mt(E),w=s.considerPlaybackRate&&_(o)?o:1,k=i.filter(N=>!Bt(N.quality)).sort((N,R)=>fi(N.quality,R.quality)?-1:1),q=(f=lt(k,-1))===null||f===void 0?void 0:f.quality,W=(v=lt(k,0))===null||v===void 0?void 0:v.quality,J=K(r)||_(r.min)&&_(r.max)&&As(r.max,r.min)||_(r.min)&&W&&fi(r.min,W)||_(r.max)&&q&&As(r.max,q),j=w*zS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),X={},B=k.filter(N=>(A?As(N.quality,A):!0)?(_(t)&&isFinite(t)&&_(N.bitrate)?t-a>=N.bitrate*j:!0)?s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!Bt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&fi(N.quality,u.quality)?(X[N.quality]=xt.Buffer,!1):!!c&&ca(N.quality,c)?(X[N.quality]=xt.DroppedFramesLimit,!1):J||(K(r.max)||Cs(N.quality,r.max))&&(K(r.min)||ca(N.quality,r.min))?!0:(X[N.quality]=xt.FitsQualityLimits,!1):(X[N.quality]=xt.FitsThroughput,!1):(X[N.quality]=xt.FitsContainer,!1))[0];B&&B.bitrate&&WS.next(B.bitrate);const x=(m=B!=null?B:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];x.quality!==((g=d==null?void 0:d.last)===null||g===void 0?void 0:g.quality)&&l({message:`
|
|
6
|
+
var mv=Object.create;var zs=Object.defineProperty,bv=Object.defineProperties,gv=Object.getOwnPropertyDescriptor,vv=Object.getOwnPropertyDescriptors,Sv=Object.getOwnPropertyNames,ol=Object.getOwnPropertySymbols,yv=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty,Tv=Object.prototype.propertyIsEnumerable;var Ne=Math.pow,ul=(i,e,t)=>e in i?zs(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,k=(i,e)=>{for(var t in e||(e={}))ll.call(e,t)&&ul(i,t,e[t]);if(ol)for(var t of ol(e))Tv.call(e,t)&&ul(i,t,e[t]);return i},B=(i,e)=>bv(i,vv(e));var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Iv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Sv(e))!ll.call(i,a)&&a!==t&&zs(i,a,{get:()=>e[a],enumerable:!(r=gv(e,a))||r.enumerable});return i};var Fe=(i,e,t)=>(t=i!=null?mv(yv(i)):{},Iv(e||!i||!i.__esModule?zs(t,"default",{value:i,enumerable:!0}):t,i));var R=(i,e,t)=>new Promise((r,a)=>{var s=u=>{try{o(t.next(u))}catch(l){a(l)}},n=u=>{try{o(t.throw(u))}catch(l){a(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(i,e)).next())}),Ev=function(i,e){this[0]=i,this[1]=e},J=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Ev,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},a=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(i,e),s[Symbol.asyncIterator]=()=>s,a("next"),a("throw"),a("return"),s};var me=m((IL,gl)=>{"use strict";gl.exports=function(i){try{return!!i()}catch(e){return!0}}});var Or=m((EL,vl)=>{"use strict";var $v=me();vl.exports=!$v(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ne=m((xL,Tl)=>{"use strict";var Sl=Or(),yl=Function.prototype,en=yl.call,Cv=Sl&&yl.bind.bind(en,en);Tl.exports=Sl?Cv:function(i){return function(){return en.apply(i,arguments)}}});var rr=m((PL,El)=>{"use strict";var Il=ne(),Dv=Il({}.toString),Mv=Il("".slice);El.exports=function(i){return Mv(Dv(i),8,-1)}});var Pl=m((wL,xl)=>{"use strict";var Ov=ne(),Bv=me(),Vv=rr(),tn=Object,_v=Ov("".split);xl.exports=Bv(function(){return!tn("z").propertyIsEnumerable(0)})?function(i){return Vv(i)=="String"?_v(i,""):tn(i)}:tn});var ir=m((kL,wl)=>{"use strict";wl.exports=function(i){return i==null}});var ca=m((AL,kl)=>{"use strict";var Nv=ir(),Fv=TypeError;kl.exports=function(i){if(Nv(i))throw Fv("Can't call method on "+i);return i}});var ar=m((RL,Al)=>{"use strict";var qv=Pl(),Uv=ca();Al.exports=function(i){return qv(Uv(i))}});var rn=m((LL,Rl)=>{"use strict";Rl.exports=function(){}});var Rt=m(($L,Ll)=>{"use strict";Ll.exports={}});var X=m(($l,Cl)=>{"use strict";var da=function(i){return i&&i.Math==Math&&i};Cl.exports=da(typeof globalThis=="object"&&globalThis)||da(typeof window=="object"&&window)||da(typeof self=="object"&&self)||da(typeof global=="object"&&global)||function(){return this}()||$l||Function("return this")()});var sn=m((CL,Dl)=>{"use strict";var an=typeof document=="object"&&document.all,Hv=typeof an=="undefined"&&an!==void 0;Dl.exports={all:an,IS_HTMLDDA:Hv}});var G=m((DL,Ol)=>{"use strict";var Ml=sn(),jv=Ml.all;Ol.exports=Ml.IS_HTMLDDA?function(i){return typeof i=="function"||i===jv}:function(i){return typeof i=="function"}});var _l=m((ML,Vl)=>{"use strict";var Gv=X(),Yv=G(),Bl=Gv.WeakMap;Vl.exports=Yv(Bl)&&/native code/.test(String(Bl))});var qe=m((OL,ql)=>{"use strict";var Nl=G(),Fl=sn(),Wv=Fl.all;ql.exports=Fl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Nl(i)||i===Wv}:function(i){return typeof i=="object"?i!==null:Nl(i)}});var Ue=m((BL,Ul)=>{"use strict";var Qv=me();Ul.exports=!Qv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var pa=m((VL,jl)=>{"use strict";var zv=X(),Hl=qe(),nn=zv.document,Kv=Hl(nn)&&Hl(nn.createElement);jl.exports=function(i){return Kv?nn.createElement(i):{}}});var on=m((_L,Gl)=>{"use strict";var Jv=Ue(),Xv=me(),Zv=pa();Gl.exports=!Jv&&!Xv(function(){return Object.defineProperty(Zv("div"),"a",{get:function(){return 7}}).a!=7})});var un=m((NL,Yl)=>{"use strict";var eS=Ue(),tS=me();Yl.exports=eS&&tS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Le=m((FL,Wl)=>{"use strict";var rS=qe(),iS=String,aS=TypeError;Wl.exports=function(i){if(rS(i))return i;throw aS(iS(i)+" is not an object")}});var oe=m((qL,Ql)=>{"use strict";var sS=Or(),ha=Function.prototype.call;Ql.exports=sS?ha.bind(ha):function(){return ha.apply(ha,arguments)}});var fa=m((UL,zl)=>{"use strict";zl.exports={}});var We=m((HL,Jl)=>{"use strict";var ln=fa(),cn=X(),nS=G(),Kl=function(i){return nS(i)?i:void 0};Jl.exports=function(i,e){return arguments.length<2?Kl(ln[i])||Kl(cn[i]):ln[i]&&ln[i][e]||cn[i]&&cn[i][e]}});var Br=m((jL,Xl)=>{"use strict";var oS=ne();Xl.exports=oS({}.isPrototypeOf)});var Vr=m((GL,Zl)=>{"use strict";Zl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var pn=m((YL,sc)=>{"use strict";var ac=X(),dn=Vr(),ec=ac.process,tc=ac.Deno,rc=ec&&ec.versions||tc&&tc.version,ic=rc&&rc.v8,$e,ma;ic&&($e=ic.split("."),ma=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ma&&dn&&($e=dn.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=dn.match(/Chrome\/(\d+)/),$e&&(ma=+$e[1])));sc.exports=ma});var hn=m((WL,oc)=>{"use strict";var nc=pn(),uS=me(),lS=X(),cS=lS.String;oc.exports=!!Object.getOwnPropertySymbols&&!uS(function(){var i=Symbol();return!cS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&nc&&nc<41})});var fn=m((QL,uc)=>{"use strict";var dS=hn();uc.exports=dS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=m((zL,lc)=>{"use strict";var pS=We(),hS=G(),fS=Br(),mS=fn(),bS=Object;lc.exports=mS?function(i){return typeof i=="symbol"}:function(i){var e=pS("Symbol");return hS(e)&&fS(e.prototype,bS(i))}});var _r=m((KL,cc)=>{"use strict";var gS=String;cc.exports=function(i){try{return gS(i)}catch(e){return"Object"}}});var Qe=m((JL,dc)=>{"use strict";var vS=G(),SS=_r(),yS=TypeError;dc.exports=function(i){if(vS(i))return i;throw yS(SS(i)+" is not a function")}});var Nr=m((XL,pc)=>{"use strict";var TS=Qe(),IS=ir();pc.exports=function(i,e){var t=i[e];return IS(t)?void 0:TS(t)}});var fc=m((ZL,hc)=>{"use strict";var bn=oe(),gn=G(),vn=qe(),ES=TypeError;hc.exports=function(i,e){var t,r;if(e==="string"&&gn(t=i.toString)&&!vn(r=bn(t,i))||gn(t=i.valueOf)&&!vn(r=bn(t,i))||e!=="string"&&gn(t=i.toString)&&!vn(r=bn(t,i)))return r;throw ES("Can't convert object to primitive value")}});var Ce=m((e$,mc)=>{"use strict";mc.exports=!0});var vc=m((t$,gc)=>{"use strict";var bc=X(),xS=Object.defineProperty;gc.exports=function(i,e){try{xS(bc,i,{value:e,configurable:!0,writable:!0})}catch(t){bc[i]=e}return e}});var ba=m((r$,yc)=>{"use strict";var PS=X(),wS=vc(),Sc="__core-js_shared__",kS=PS[Sc]||wS(Sc,{});yc.exports=kS});var Sn=m((i$,Ic)=>{"use strict";var AS=Ce(),Tc=ba();(Ic.exports=function(i,e){return Tc[i]||(Tc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:AS?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Fr=m((a$,Ec)=>{"use strict";var RS=ca(),LS=Object;Ec.exports=function(i){return LS(RS(i))}});var De=m((s$,xc)=>{"use strict";var $S=ne(),CS=Fr(),DS=$S({}.hasOwnProperty);xc.exports=Object.hasOwn||function(e,t){return DS(CS(e),t)}});var yn=m((n$,Pc)=>{"use strict";var MS=ne(),OS=0,BS=Math.random(),VS=MS(1 .toString);Pc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+VS(++OS+BS,36)}});var te=m((o$,kc)=>{"use strict";var _S=X(),NS=Sn(),wc=De(),FS=yn(),qS=hn(),US=fn(),sr=_S.Symbol,Tn=NS("wks"),HS=US?sr.for||sr:sr&&sr.withoutSetter||FS;kc.exports=function(i){return wc(Tn,i)||(Tn[i]=qS&&wc(sr,i)?sr[i]:HS("Symbol."+i)),Tn[i]}});var $c=m((u$,Lc)=>{"use strict";var jS=oe(),Ac=qe(),Rc=mn(),GS=Nr(),YS=fc(),WS=te(),QS=TypeError,zS=WS("toPrimitive");Lc.exports=function(i,e){if(!Ac(i)||Rc(i))return i;var t=GS(i,zS),r;if(t){if(e===void 0&&(e="default"),r=jS(t,i,e),!Ac(r)||Rc(r))return r;throw QS("Can't convert object to primitive value")}return e===void 0&&(e="number"),YS(i,e)}});var ga=m((l$,Cc)=>{"use strict";var KS=$c(),JS=mn();Cc.exports=function(i){var e=KS(i,"string");return JS(e)?e:e+""}});var Lt=m(Mc=>{"use strict";var XS=Ue(),ZS=on(),ey=un(),va=Le(),Dc=ga(),ty=TypeError,In=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,En="enumerable",xn="configurable",Pn="writable";Mc.f=XS?ey?function(e,t,r){if(va(e),t=Dc(t),va(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Pn in r&&!r[Pn]){var a=ry(e,t);a&&a[Pn]&&(e[t]=r.value,r={configurable:xn in r?r[xn]:a[xn],enumerable:En in r?r[En]:a[En],writable:!1})}return In(e,t,r)}:In:function(e,t,r){if(va(e),t=Dc(t),va(r),ZS)try{return In(e,t,r)}catch(a){}if("get"in r||"set"in r)throw ty("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var qr=m((d$,Oc)=>{"use strict";Oc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((p$,Bc)=>{"use strict";var iy=Ue(),ay=Lt(),sy=qr();Bc.exports=iy?function(i,e,t){return ay.f(i,e,sy(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=m((h$,_c)=>{"use strict";var ny=Sn(),oy=yn(),Vc=ny("keys");_c.exports=function(i){return Vc[i]||(Vc[i]=oy(i))}});var ya=m((f$,Nc)=>{"use strict";Nc.exports={}});var Rn=m((m$,Uc)=>{"use strict";var uy=_l(),qc=X(),ly=qe(),cy=$t(),wn=De(),kn=ba(),dy=Sa(),py=ya(),Fc="Object already initialized",An=qc.TypeError,hy=qc.WeakMap,Ta,Ur,Ia,fy=function(i){return Ia(i)?Ur(i):Ta(i,{})},my=function(i){return function(e){var t;if(!ly(e)||(t=Ur(e)).type!==i)throw An("Incompatible receiver, "+i+" required");return t}};uy||kn.state?(Me=kn.state||(kn.state=new hy),Me.get=Me.get,Me.has=Me.has,Me.set=Me.set,Ta=function(i,e){if(Me.has(i))throw An(Fc);return e.facade=i,Me.set(i,e),e},Ur=function(i){return Me.get(i)||{}},Ia=function(i){return Me.has(i)}):(Ct=dy("state"),py[Ct]=!0,Ta=function(i,e){if(wn(i,Ct))throw An(Fc);return e.facade=i,cy(i,Ct,e),e},Ur=function(i){return wn(i,Ct)?i[Ct]:{}},Ia=function(i){return wn(i,Ct)});var Me,Ct;Uc.exports={set:Ta,get:Ur,has:Ia,enforce:fy,getterFor:my}});var Ln=m((b$,Yc)=>{"use strict";var by=Or(),Gc=Function.prototype,Hc=Gc.apply,jc=Gc.call;Yc.exports=typeof Reflect=="object"&&Reflect.apply||(by?jc.bind(Hc):function(){return jc.apply(Hc,arguments)})});var $n=m((g$,Wc)=>{"use strict";var gy=rr(),vy=ne();Wc.exports=function(i){if(gy(i)==="Function")return vy(i)}});var Jc=m(Kc=>{"use strict";var Qc={}.propertyIsEnumerable,zc=Object.getOwnPropertyDescriptor,Sy=zc&&!Qc.call({1:2},1);Kc.f=Sy?function(e){var t=zc(this,e);return!!t&&t.enumerable}:Qc});var Cn=m(Zc=>{"use strict";var yy=Ue(),Ty=oe(),Iy=Jc(),Ey=qr(),xy=ar(),Py=ga(),wy=De(),ky=on(),Xc=Object.getOwnPropertyDescriptor;Zc.f=yy?Xc:function(e,t){if(e=xy(e),t=Py(t),ky)try{return Xc(e,t)}catch(r){}if(wy(e,t))return Ey(!Ty(Iy.f,e,t),e[t])}});var Dn=m((y$,ed)=>{"use strict";var Ay=me(),Ry=G(),Ly=/#|\.prototype\./,Hr=function(i,e){var t=Cy[$y(i)];return t==My?!0:t==Dy?!1:Ry(e)?Ay(e):!!e},$y=Hr.normalize=function(i){return String(i).replace(Ly,".").toLowerCase()},Cy=Hr.data={},Dy=Hr.NATIVE="N",My=Hr.POLYFILL="P";ed.exports=Hr});var jr=m((T$,rd)=>{"use strict";var td=$n(),Oy=Qe(),By=Or(),Vy=td(td.bind);rd.exports=function(i,e){return Oy(i),e===void 0?i:By?Vy(i,e):function(){return i.apply(e,arguments)}}});var Te=m((I$,ad)=>{"use strict";var Ea=X(),_y=Ln(),Ny=$n(),Fy=G(),qy=Cn().f,Uy=Dn(),nr=fa(),Hy=jr(),or=$t(),id=De(),jy=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return _y(i,this,arguments)};return e.prototype=i.prototype,e};ad.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Ea:a?Ea[t]:(Ea[t]||{}).prototype,o=r?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,v,S;for(p in e)l=Uy(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&id(n,p),f=o[p],c&&(i.dontCallGetSet?(S=qy(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(c&&typeof f==typeof h)&&(i.bind&&c?v=Hy(h,Ea):i.wrap&&c?v=jy(h):s&&Fy(h)?v=Ny(h):v=h,(i.sham||h&&h.sham||f&&f.sham)&&or(v,"sham",!0),or(o,p,v),s&&(d=t+"Prototype",id(nr,d)||or(nr,d,{}),or(nr[d],p,h),i.real&&u&&(l||!u[p])&&or(u,p,h)))}});var od=m((E$,nd)=>{"use strict";var Mn=Ue(),Gy=De(),sd=Function.prototype,Yy=Mn&&Object.getOwnPropertyDescriptor,On=Gy(sd,"name"),Wy=On&&function(){}.name==="something",Qy=On&&(!Mn||Mn&&Yy(sd,"name").configurable);nd.exports={EXISTS:On,PROPER:Wy,CONFIGURABLE:Qy}});var ld=m((x$,ud)=>{"use strict";var zy=Math.ceil,Ky=Math.floor;ud.exports=Math.trunc||function(e){var t=+e;return(t>0?Ky:zy)(t)}});var xa=m((P$,cd)=>{"use strict";var Jy=ld();cd.exports=function(i){var e=+i;return e!==e||e===0?0:Jy(e)}});var pd=m((w$,dd)=>{"use strict";var Xy=xa(),Zy=Math.max,eT=Math.min;dd.exports=function(i,e){var t=Xy(i);return t<0?Zy(t+e,0):eT(t,e)}});var fd=m((k$,hd)=>{"use strict";var tT=xa(),rT=Math.min;hd.exports=function(i){return i>0?rT(tT(i),9007199254740991):0}});var Pa=m((A$,md)=>{"use strict";var iT=fd();md.exports=function(i){return iT(i.length)}});var vd=m((R$,gd)=>{"use strict";var aT=ar(),sT=pd(),nT=Pa(),bd=function(i){return function(e,t,r){var a=aT(e),s=nT(a),n=sT(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};gd.exports={includes:bd(!0),indexOf:bd(!1)}});var Td=m((L$,yd)=>{"use strict";var oT=ne(),Bn=De(),uT=ar(),lT=vd().indexOf,cT=ya(),Sd=oT([].push);yd.exports=function(i,e){var t=uT(i),r=0,a=[],s;for(s in t)!Bn(cT,s)&&Bn(t,s)&&Sd(a,s);for(;e.length>r;)Bn(t,s=e[r++])&&(~lT(a,s)||Sd(a,s));return a}});var Vn=m(($$,Id)=>{"use strict";Id.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xd=m((C$,Ed)=>{"use strict";var dT=Td(),pT=Vn();Ed.exports=Object.keys||function(e){return dT(e,pT)}});var wd=m(Pd=>{"use strict";var hT=Ue(),fT=un(),mT=Lt(),bT=Le(),gT=ar(),vT=xd();Pd.f=hT&&!fT?Object.defineProperties:function(e,t){bT(e);for(var r=gT(t),a=vT(t),s=a.length,n=0,o;s>n;)mT.f(e,o=a[n++],r[o]);return e}});var _n=m((M$,kd)=>{"use strict";var ST=We();kd.exports=ST("document","documentElement")});var Un=m((O$,Md)=>{"use strict";var yT=Le(),TT=wd(),Ad=Vn(),IT=ya(),ET=_n(),xT=pa(),PT=Sa(),Rd=">",Ld="<",Fn="prototype",qn="script",Cd=PT("IE_PROTO"),Nn=function(){},Dd=function(i){return Ld+qn+Rd+i+Ld+"/"+qn+Rd},$d=function(i){i.write(Dd("")),i.close();var e=i.parentWindow.Object;return i=null,e},wT=function(){var i=xT("iframe"),e="java"+qn+":",t;return i.style.display="none",ET.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Dd("document.F=Object")),t.close(),t.F},wa,ka=function(){try{wa=new ActiveXObject("htmlfile")}catch(e){}ka=typeof document!="undefined"?document.domain&&wa?$d(wa):wT():$d(wa);for(var i=Ad.length;i--;)delete ka[Fn][Ad[i]];return ka()};IT[Cd]=!0;Md.exports=Object.create||function(e,t){var r;return e!==null?(Nn[Fn]=yT(e),r=new Nn,Nn[Fn]=null,r[Cd]=e):r=ka(),t===void 0?r:TT.f(r,t)}});var Bd=m((B$,Od)=>{"use strict";var kT=me();Od.exports=!kT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var jn=m((V$,_d)=>{"use strict";var AT=De(),RT=G(),LT=Fr(),$T=Sa(),CT=Bd(),Vd=$T("IE_PROTO"),Hn=Object,DT=Hn.prototype;_d.exports=CT?Hn.getPrototypeOf:function(i){var e=LT(i);if(AT(e,Vd))return e[Vd];var t=e.constructor;return RT(t)&&e instanceof t?t.prototype:e instanceof Hn?DT:null}});var ur=m((_$,Nd)=>{"use strict";var MT=$t();Nd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:MT(i,e,t),i}});var Qn=m((N$,Ud)=>{"use strict";var OT=me(),BT=G(),VT=qe(),_T=Un(),Fd=jn(),NT=ur(),FT=te(),qT=Ce(),Wn=FT("iterator"),qd=!1,ze,Gn,Yn;[].keys&&(Yn=[].keys(),"next"in Yn?(Gn=Fd(Fd(Yn)),Gn!==Object.prototype&&(ze=Gn)):qd=!0);var UT=!VT(ze)||OT(function(){var i={};return ze[Wn].call(i)!==i});UT?ze={}:qT&&(ze=_T(ze));BT(ze[Wn])||NT(ze,Wn,function(){return this});Ud.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:qd}});var Aa=m((F$,jd)=>{"use strict";var HT=te(),jT=HT("toStringTag"),Hd={};Hd[jT]="z";jd.exports=String(Hd)==="[object z]"});var lr=m((q$,Gd)=>{"use strict";var GT=Aa(),YT=G(),Ra=rr(),WT=te(),QT=WT("toStringTag"),zT=Object,KT=Ra(function(){return arguments}())=="Arguments",JT=function(i,e){try{return i[e]}catch(t){}};Gd.exports=GT?Ra:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=JT(e=zT(i),QT))=="string"?t:KT?Ra(e):(r=Ra(e))=="Object"&&YT(e.callee)?"Arguments":r}});var Wd=m((U$,Yd)=>{"use strict";var XT=Aa(),ZT=lr();Yd.exports=XT?{}.toString:function(){return"[object "+ZT(this)+"]"}});var La=m((H$,zd)=>{"use strict";var eI=Aa(),tI=Lt().f,rI=$t(),iI=De(),aI=Wd(),sI=te(),Qd=sI("toStringTag");zd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;iI(a,Qd)||tI(a,Qd,{configurable:!0,value:e}),r&&!eI&&rI(a,"toString",aI)}}});var Jd=m((j$,Kd)=>{"use strict";var nI=Qn().IteratorPrototype,oI=Un(),uI=qr(),lI=La(),cI=Rt(),dI=function(){return this};Kd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=oI(nI,{next:uI(+!r,t)}),lI(i,a,!1,!0),cI[a]=dI,i}});var Zd=m((G$,Xd)=>{"use strict";var pI=ne(),hI=Qe();Xd.exports=function(i,e,t){try{return pI(hI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var tp=m((Y$,ep)=>{"use strict";var fI=G(),mI=String,bI=TypeError;ep.exports=function(i){if(typeof i=="object"||fI(i))return i;throw bI("Can't set "+mI(i)+" as a prototype")}});var zn=m((W$,rp)=>{"use strict";var gI=Zd(),vI=Le(),SI=tp();rp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=gI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return vI(a),SI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var hp=m((Q$,pp)=>{"use strict";var yI=Te(),TI=oe(),$a=Ce(),cp=od(),II=G(),EI=Jd(),ip=jn(),ap=zn(),xI=La(),PI=$t(),Kn=ur(),wI=te(),sp=Rt(),dp=Qn(),kI=cp.PROPER,AI=cp.CONFIGURABLE,np=dp.IteratorPrototype,Ca=dp.BUGGY_SAFARI_ITERATORS,Gr=wI("iterator"),op="keys",Yr="values",up="entries",lp=function(){return this};pp.exports=function(i,e,t,r,a,s,n){EI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!Ca&&S in c)return c[S];switch(S){case op:return function(){return new t(this,S)};case Yr:return function(){return new t(this,S)};case up:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[Gr]||c["@@iterator"]||a&&c[a],p=!Ca&&d||o(a),h=e=="Array"&&c.entries||d,f,b,v;if(h&&(f=ip(h.call(new i)),f!==Object.prototype&&f.next&&(!$a&&ip(f)!==np&&(ap?ap(f,np):II(f[Gr])||Kn(f,Gr,lp)),xI(f,u,!0,!0),$a&&(sp[u]=lp))),kI&&a==Yr&&d&&d.name!==Yr&&(!$a&&AI?PI(c,"name",Yr):(l=!0,p=function(){return TI(d,this)})),a)if(b={values:o(Yr),keys:s?p:o(op),entries:o(up)},n)for(v in b)(Ca||l||!(v in c))&&Kn(c,v,b[v]);else yI({target:e,proto:!0,forced:Ca||l},b);return(!$a||n)&&c[Gr]!==p&&Kn(c,Gr,p,{name:a}),sp[e]=p,b}});var mp=m((z$,fp)=>{"use strict";fp.exports=function(i,e){return{value:i,done:e}}});var Xn=m((K$,yp)=>{"use strict";var RI=ar(),Jn=rn(),bp=Rt(),vp=Rn(),LI=Lt().f,$I=hp(),Da=mp(),CI=Ce(),DI=Ue(),Sp="Array Iterator",MI=vp.set,OI=vp.getterFor(Sp);yp.exports=$I(Array,"Array",function(i,e){MI(this,{type:Sp,target:RI(i),index:0,kind:e})},function(){var i=OI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Da(void 0,!0)):t=="keys"?Da(r,!1):t=="values"?Da(e[r],!1):Da([r,e[r]],!1)},"values");var gp=bp.Arguments=bp.Array;Jn("keys");Jn("values");Jn("entries");if(!CI&&DI&&gp.name!=="values")try{LI(gp,"name",{value:"values"})}catch(i){}});var Ip=m((J$,Tp)=>{"use strict";var BI=te(),VI=Rt(),_I=BI("iterator"),NI=Array.prototype;Tp.exports=function(i){return i!==void 0&&(VI.Array===i||NI[_I]===i)}});var Zn=m((X$,xp)=>{"use strict";var FI=lr(),Ep=Nr(),qI=ir(),UI=Rt(),HI=te(),jI=HI("iterator");xp.exports=function(i){if(!qI(i))return Ep(i,jI)||Ep(i,"@@iterator")||UI[FI(i)]}});var wp=m((Z$,Pp)=>{"use strict";var GI=oe(),YI=Qe(),WI=Le(),QI=_r(),zI=Zn(),KI=TypeError;Pp.exports=function(i,e){var t=arguments.length<2?zI(i):e;if(YI(t))return WI(GI(t,i));throw KI(QI(i)+" is not iterable")}});var Rp=m((eC,Ap)=>{"use strict";var JI=oe(),kp=Le(),XI=Nr();Ap.exports=function(i,e,t){var r,a;kp(i);try{if(r=XI(i,"return"),!r){if(e==="throw")throw t;return t}r=JI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return kp(r),t}});var Oa=m((tC,Dp)=>{"use strict";var ZI=jr(),eE=oe(),tE=Le(),rE=_r(),iE=Ip(),aE=Pa(),Lp=Br(),sE=wp(),nE=Zn(),$p=Rp(),oE=TypeError,Ma=function(i,e){this.stopped=i,this.result=e},Cp=Ma.prototype;Dp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ZI(e,r),l,c,d,p,h,f,b,v=function(g){return l&&$p(l,"normal",g),new Ma(!0,g)},S=function(g){return a?(tE(g),o?u(g[0],g[1],v):u(g[0],g[1])):o?u(g,v):u(g)};if(s)l=i.iterator;else if(n)l=i;else{if(c=nE(i),!c)throw oE(rE(i)+" is not iterable");if(iE(c)){for(d=0,p=aE(i);p>d;d++)if(h=S(i[d]),h&&Lp(Cp,h))return h;return new Ma(!1)}l=sE(i,c)}for(f=s?i.next:l.next;!(b=eE(f,l)).done;){try{h=S(b.value)}catch(g){$p(l,"throw",g)}if(typeof h=="object"&&h&&Lp(Cp,h))return h}return new Ma(!1)}});var Op=m((rC,Mp)=>{"use strict";var uE=ga(),lE=Lt(),cE=qr();Mp.exports=function(i,e,t){var r=uE(e);r in i?lE.f(i,r,cE(0,t)):i[r]=t}});var Bp=m(()=>{"use strict";var dE=Te(),pE=Oa(),hE=Op();dE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pE(e,function(r,a){hE(t,r,a)},{AS_ENTRIES:!0}),t}})});var _p=m((sC,Vp)=>{"use strict";Xn();Bp();var fE=fa();Vp.exports=fE.Object.fromEntries});var Fp=m((nC,Np)=>{"use strict";Np.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Hp=m(()=>{"use strict";Xn();var mE=Fp(),bE=X(),gE=lr(),vE=$t(),qp=Rt(),SE=te(),Up=SE("toStringTag");for(Ba in mE)eo=bE[Ba],Va=eo&&eo.prototype,Va&&gE(Va)!==Up&&vE(Va,Up,Ba),qp[Ba]=qp.Array;var eo,Va,Ba});var Gp=m((lC,jp)=>{"use strict";var yE=_p();Hp();jp.exports=yE});var _a=m((cC,Yp)=>{"use strict";var TE=Gp();Yp.exports=TE});var Wp=m(()=>{"use strict"});var Wr=m((hC,Qp)=>{"use strict";var IE=rr();Qp.exports=typeof process!="undefined"&&IE(process)=="process"});var Kp=m((fC,zp)=>{"use strict";var EE=Lt();zp.exports=function(i,e,t){return EE.f(i,e,t)}});var Zp=m((mC,Xp)=>{"use strict";var xE=We(),PE=Kp(),wE=te(),kE=Ue(),Jp=wE("species");Xp.exports=function(i){var e=xE(i);kE&&e&&!e[Jp]&&PE(e,Jp,{configurable:!0,get:function(){return this}})}});var th=m((bC,eh)=>{"use strict";var AE=Br(),RE=TypeError;eh.exports=function(i,e){if(AE(e,i))return i;throw RE("Incorrect invocation")}});var ro=m((gC,rh)=>{"use strict";var LE=ne(),$E=G(),to=ba(),CE=LE(Function.toString);$E(to.inspectSource)||(to.inspectSource=function(i){return CE(i)});rh.exports=to.inspectSource});var uh=m((vC,oh)=>{"use strict";var DE=ne(),ME=me(),ih=G(),OE=lr(),BE=We(),VE=ro(),ah=function(){},_E=[],sh=BE("Reflect","construct"),io=/^\s*(?:class|function)\b/,NE=DE(io.exec),FE=!io.exec(ah),Qr=function(e){if(!ih(e))return!1;try{return sh(ah,_E,e),!0}catch(t){return!1}},nh=function(e){if(!ih(e))return!1;switch(OE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return FE||!!NE(io,VE(e))}catch(t){return!0}};nh.sham=!0;oh.exports=!sh||ME(function(){var i;return Qr(Qr.call)||!Qr(Object)||!Qr(function(){i=!0})||i})?nh:Qr});var ch=m((SC,lh)=>{"use strict";var qE=uh(),UE=_r(),HE=TypeError;lh.exports=function(i){if(qE(i))return i;throw HE(UE(i)+" is not a constructor")}});var ao=m((yC,ph)=>{"use strict";var dh=Le(),jE=ch(),GE=ir(),YE=te(),WE=YE("species");ph.exports=function(i,e){var t=dh(i).constructor,r;return t===void 0||GE(r=dh(t)[WE])?e:jE(r)}});var fh=m((TC,hh)=>{"use strict";var QE=ne();hh.exports=QE([].slice)});var bh=m((IC,mh)=>{"use strict";var zE=TypeError;mh.exports=function(i,e){if(i<e)throw zE("Not enough arguments");return i}});var so=m((EC,gh)=>{"use strict";var KE=Vr();gh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(KE)});var mo=m((xC,wh)=>{"use strict";var be=X(),JE=Ln(),XE=jr(),vh=G(),ZE=De(),Ph=me(),Sh=_n(),ex=fh(),yh=pa(),tx=bh(),rx=so(),ix=Wr(),po=be.setImmediate,ho=be.clearImmediate,ax=be.process,no=be.Dispatch,sx=be.Function,Th=be.MessageChannel,nx=be.String,oo=0,zr={},Ih="onreadystatechange",Kr,Dt,uo,lo;Ph(function(){Kr=be.location});var fo=function(i){if(ZE(zr,i)){var e=zr[i];delete zr[i],e()}},co=function(i){return function(){fo(i)}},Eh=function(i){fo(i.data)},xh=function(i){be.postMessage(nx(i),Kr.protocol+"//"+Kr.host)};(!po||!ho)&&(po=function(e){tx(arguments.length,1);var t=vh(e)?e:sx(e),r=ex(arguments,1);return zr[++oo]=function(){JE(t,void 0,r)},Dt(oo),oo},ho=function(e){delete zr[e]},ix?Dt=function(i){ax.nextTick(co(i))}:no&&no.now?Dt=function(i){no.now(co(i))}:Th&&!rx?(uo=new Th,lo=uo.port2,uo.port1.onmessage=Eh,Dt=XE(lo.postMessage,lo)):be.addEventListener&&vh(be.postMessage)&&!be.importScripts&&Kr&&Kr.protocol!=="file:"&&!Ph(xh)?(Dt=xh,be.addEventListener("message",Eh,!1)):Ih in yh("script")?Dt=function(i){Sh.appendChild(yh("script"))[Ih]=function(){Sh.removeChild(this),fo(i)}}:Dt=function(i){setTimeout(co(i),0)});wh.exports={set:po,clear:ho}});var bo=m((PC,Ah)=>{"use strict";var kh=function(){this.head=null,this.tail=null};kh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Ah.exports=kh});var Lh=m((wC,Rh)=>{"use strict";var ox=Vr();Rh.exports=/ipad|iphone|ipod/i.test(ox)&&typeof Pebble!="undefined"});var Ch=m((kC,$h)=>{"use strict";var ux=Vr();$h.exports=/web0s(?!.*chrome)/i.test(ux)});var Fh=m((AC,Nh)=>{"use strict";var Mt=X(),Dh=jr(),lx=Cn().f,go=mo().set,cx=bo(),dx=so(),px=Lh(),hx=Ch(),vo=Wr(),Mh=Mt.MutationObserver||Mt.WebKitMutationObserver,Oh=Mt.document,Bh=Mt.process,Na=Mt.Promise,Vh=lx(Mt,"queueMicrotask"),To=Vh&&Vh.value,cr,So,yo,Fa,_h;To||(Jr=new cx,Xr=function(){var i,e;for(vo&&(i=Bh.domain)&&i.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&cr(),t}i&&i.enter()},!dx&&!vo&&!hx&&Mh&&Oh?(So=!0,yo=Oh.createTextNode(""),new Mh(Xr).observe(yo,{characterData:!0}),cr=function(){yo.data=So=!So}):!px&&Na&&Na.resolve?(Fa=Na.resolve(void 0),Fa.constructor=Na,_h=Dh(Fa.then,Fa),cr=function(){_h(Xr)}):vo?cr=function(){Bh.nextTick(Xr)}:(go=Dh(go,Mt),cr=function(){go(Xr)}),To=function(i){Jr.head||cr(),Jr.add(i)});var Jr,Xr;Nh.exports=To});var Uh=m((RC,qh)=>{"use strict";qh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var qa=m((LC,Hh)=>{"use strict";Hh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m(($C,jh)=>{"use strict";var fx=X();jh.exports=fx.Promise});var Io=m((CC,Gh)=>{"use strict";Gh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Wh=m((DC,Yh)=>{"use strict";var mx=Io(),bx=Wr();Yh.exports=!mx&&!bx&&typeof window=="object"&&typeof document=="object"});var dr=m((MC,Kh)=>{"use strict";var gx=X(),Zr=Ot(),vx=G(),Sx=Dn(),yx=ro(),Tx=te(),Ix=Wh(),Ex=Io(),xx=Ce(),Eo=pn(),Qh=Zr&&Zr.prototype,Px=Tx("species"),xo=!1,zh=vx(gx.PromiseRejectionEvent),wx=Sx("Promise",function(){var i=yx(Zr),e=i!==String(Zr);if(!e&&Eo===66||xx&&!(Qh.catch&&Qh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(i)){var t=new Zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Px]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(Ix||Ex)&&!zh});Kh.exports={CONSTRUCTOR:wx,REJECTION_EVENT:zh,SUBCLASSING:xo}});var pr=m((OC,Xh)=>{"use strict";var Jh=Qe(),kx=TypeError,Ax=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw kx("Bad Promise constructor");e=r,t=a}),this.resolve=Jh(e),this.reject=Jh(t)};Xh.exports.f=function(i){return new Ax(i)}});var vf=m(()=>{"use strict";var Rx=Te(),Lx=Ce(),Ga=Wr(),ct=X(),br=oe(),Zh=ur(),ef=zn(),$x=La(),Cx=Zp(),Dx=Qe(),ja=G(),Mx=qe(),Ox=th(),Bx=ao(),nf=mo().set,Ro=Fh(),Vx=Uh(),_x=qa(),Nx=bo(),of=Rn(),Ya=Ot(),Lo=dr(),uf=pr(),Wa="Promise",lf=Lo.CONSTRUCTOR,Fx=Lo.REJECTION_EVENT,qx=Lo.SUBCLASSING,Po=of.getterFor(Wa),Ux=of.set,hr=Ya&&Ya.prototype,Bt=Ya,Ua=hr,cf=ct.TypeError,wo=ct.document,$o=ct.process,ko=uf.f,Hx=ko,jx=!!(wo&&wo.createEvent&&ct.dispatchEvent),df="unhandledrejection",Gx="rejectionhandled",tf=0,pf=1,Yx=2,Co=1,hf=2,Ha,rf,Wx,af,ff=function(i){var e;return Mx(i)&&ja(e=i.then)?e:!1},mf=function(i,e){var t=e.value,r=e.state==pf,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===hf&&zx(e),e.rejection=Co),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(cf("Promise-chain cycle")):(l=ff(u))?br(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},bf=function(i,e){i.notified||(i.notified=!0,Ro(function(){for(var t=i.reactions,r;r=t.get();)mf(r,i);i.notified=!1,e&&!i.rejection&&Qx(i)}))},gf=function(i,e,t){var r,a;jx?(r=wo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),ct.dispatchEvent(r)):r={promise:e,reason:t},!Fx&&(a=ct["on"+i])?a(r):i===df&&Vx("Unhandled promise rejection",t)},Qx=function(i){br(nf,ct,function(){var e=i.facade,t=i.value,r=sf(i),a;if(r&&(a=_x(function(){Ga?$o.emit("unhandledRejection",t,e):gf(df,e,t)}),i.rejection=Ga||sf(i)?hf:Co,a.error))throw a.value})},sf=function(i){return i.rejection!==Co&&!i.parent},zx=function(i){br(nf,ct,function(){var e=i.facade;Ga?$o.emit("rejectionHandled",e):gf(Gx,e,i.value)})},fr=function(i,e,t){return function(r){i(e,r,t)}},mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Yx,bf(i,!0))},Ao=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw cf("Promise can't be resolved itself");var r=ff(e);r?Ro(function(){var a={done:!1};try{br(r,e,fr(Ao,a,i),fr(mr,a,i))}catch(s){mr(a,s,i)}}):(i.value=e,i.state=pf,bf(i,!1))}catch(a){mr({done:!1},a,i)}}};if(lf&&(Bt=function(e){Ox(this,Ua),Dx(e),br(Ha,this);var t=Po(this);try{e(fr(Ao,t),fr(mr,t))}catch(r){mr(t,r)}},Ua=Bt.prototype,Ha=function(e){Ux(this,{type:Wa,done:!1,notified:!1,parent:!1,reactions:new Nx,rejection:!1,state:tf,value:void 0})},Ha.prototype=Zh(Ua,"then",function(e,t){var r=Po(this),a=ko(Bx(this,Bt));return r.parent=!0,a.ok=ja(e)?e:!0,a.fail=ja(t)&&t,a.domain=Ga?$o.domain:void 0,r.state==tf?r.reactions.add(a):Ro(function(){mf(a,r)}),a.promise}),rf=function(){var i=new Ha,e=Po(i);this.promise=i,this.resolve=fr(Ao,e),this.reject=fr(mr,e)},uf.f=ko=function(i){return i===Bt||i===Wx?new rf(i):Hx(i)},!Lx&&ja(Ya)&&hr!==Object.prototype)){af=hr.then,qx||Zh(hr,"then",function(e,t){var r=this;return new Bt(function(a,s){br(af,r,a,s)}).then(e,t)},{unsafe:!0});try{delete hr.constructor}catch(i){}ef&&ef(hr,Ua)}Rx({global:!0,constructor:!0,wrap:!0,forced:lf},{Promise:Bt});$x(Bt,Wa,!1,!0);Cx(Wa)});var Ef=m((_C,If)=>{"use strict";var Kx=te(),yf=Kx("iterator"),Tf=!1;try{Sf=0,Do={next:function(){return{done:!!Sf++}},return:function(){Tf=!0}},Do[yf]=function(){return this},Array.from(Do,function(){throw 2})}catch(i){}var Sf,Do;If.exports=function(i,e){if(!e&&!Tf)return!1;var t=!1;try{var r={};r[yf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Mo=m((NC,xf)=>{"use strict";var Jx=Ot(),Xx=Ef(),Zx=dr().CONSTRUCTOR;xf.exports=Zx||!Xx(function(i){Jx.all(i).then(void 0,function(){})})});var Pf=m(()=>{"use strict";var eP=Te(),tP=oe(),rP=Qe(),iP=pr(),aP=qa(),sP=Oa(),nP=Mo();eP({target:"Promise",stat:!0,forced:nP},{all:function(e){var t=this,r=iP.f(t),a=r.resolve,s=r.reject,n=aP(function(){var o=rP(t.resolve),u=[],l=0,c=1;sP(e,function(d){var p=l++,h=!1;c++,tP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var kf=m(()=>{"use strict";var oP=Te(),uP=Ce(),lP=dr().CONSTRUCTOR,Bo=Ot(),cP=We(),dP=G(),pP=ur(),wf=Bo&&Bo.prototype;oP({target:"Promise",proto:!0,forced:lP,real:!0},{catch:function(i){return this.then(void 0,i)}});!uP&&dP(Bo)&&(Oo=cP("Promise").prototype.catch,wf.catch!==Oo&&pP(wf,"catch",Oo,{unsafe:!0}));var Oo});var Af=m(()=>{"use strict";var hP=Te(),fP=oe(),mP=Qe(),bP=pr(),gP=qa(),vP=Oa(),SP=Mo();hP({target:"Promise",stat:!0,forced:SP},{race:function(e){var t=this,r=bP.f(t),a=r.reject,s=gP(function(){var n=mP(t.resolve);vP(e,function(o){fP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Rf=m(()=>{"use strict";var yP=Te(),TP=oe(),IP=pr(),EP=dr().CONSTRUCTOR;yP({target:"Promise",stat:!0,forced:EP},{reject:function(e){var t=IP.f(this);return TP(t.reject,void 0,e),t.promise}})});var Vo=m((QC,Lf)=>{"use strict";var xP=Le(),PP=qe(),wP=pr();Lf.exports=function(i,e){if(xP(i),PP(e)&&e.constructor===i)return e;var t=wP.f(i),r=t.resolve;return r(e),t.promise}});var Df=m(()=>{"use strict";var kP=Te(),AP=We(),$f=Ce(),RP=Ot(),Cf=dr().CONSTRUCTOR,LP=Vo(),$P=AP("Promise"),CP=$f&&!Cf;kP({target:"Promise",stat:!0,forced:$f||Cf},{resolve:function(e){return LP(CP&&this===$P?RP:this,e)}})});var Mf=m(()=>{"use strict";vf();Pf();kf();Af();Rf();Df()});var _f=m(()=>{"use strict";var DP=Te(),MP=Ce(),Qa=Ot(),OP=me(),Bf=We(),Vf=G(),BP=ao(),Of=Vo(),VP=ur(),No=Qa&&Qa.prototype,_P=!!Qa&&OP(function(){No.finally.call({then:function(){}},function(){})});DP({target:"Promise",proto:!0,real:!0,forced:_P},{finally:function(i){var e=BP(this,Bf("Promise")),t=Vf(i);return this.then(t?function(r){return Of(e,i()).then(function(){return r})}:i,t?function(r){return Of(e,i()).then(function(){throw r})}:i)}});!MP&&Vf(Qa)&&(_o=Bf("Promise").prototype.finally,No.finally!==_o&&VP(No,"finally",_o,{unsafe:!0}));var _o});var za=m((tD,Nf)=>{"use strict";var NP=We();Nf.exports=NP});var qf=m((rD,Ff)=>{"use strict";Wp();Mf();_f();var FP=za();Ff.exports=FP("Promise","finally")});var Hf=m((iD,Uf)=>{"use strict";var qP=qf();Uf.exports=qP});var Ka=m((aD,jf)=>{"use strict";var UP=Hf();jf.exports=UP});var fm=m(()=>{"use strict";var fw=Te(),mw=Fr(),bw=Pa(),gw=xa(),vw=rn();fw({target:"Array",proto:!0},{at:function(e){var t=mw(this),r=bw(t),a=gw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});vw("at")});var bm=m((hM,mm)=>{"use strict";fm();var Sw=za();mm.exports=Sw("Array","at")});var vm=m((fM,gm)=>{"use strict";var yw=bm();gm.exports=yw});var Za=m((mM,Sm)=>{"use strict";var Tw=vm();Sm.exports=Tw});var Jm=m(()=>{"use strict"});var Xm=m(()=>{"use strict"});var eb=m((oV,Zm)=>{"use strict";var wk=qe(),kk=rr(),Ak=te(),Rk=Ak("match");Zm.exports=function(i){var e;return wk(i)&&((e=i[Rk])!==void 0?!!e:kk(i)=="RegExp")}});var rb=m((uV,tb)=>{"use strict";var Lk=lr(),$k=String;tb.exports=function(i){if(Lk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return $k(i)}});var ab=m((lV,ib)=>{"use strict";var Ck=Le();ib.exports=function(){var i=Ck(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var ob=m((cV,nb)=>{"use strict";var Dk=oe(),Mk=De(),Ok=Br(),Bk=ab(),sb=RegExp.prototype;nb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in sb)&&!Mk(i,"flags")&&Ok(sb,i)?Dk(Bk,i):e}});var lb=m((dV,ub)=>{"use strict";var pu=ne(),Vk=Fr(),_k=Math.floor,cu=pu("".charAt),Nk=pu("".replace),du=pu("".slice),Fk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qk=/\$([$&'`]|\d{1,2})/g;ub.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=qk;return a!==void 0&&(a=Vk(a),u=Fk),Nk(s,u,function(l,c){var d;switch(cu(c,0)){case"$":return"$";case"&":return i;case"`":return du(e,0,t);case"'":return du(e,n);case"<":d=a[du(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=_k(p/10);return h===0?l:h<=o?r[h-1]===void 0?cu(c,1):r[h-1]+cu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var fb=m(()=>{"use strict";var Uk=Te(),Hk=oe(),hu=ne(),cb=ca(),jk=G(),Gk=ir(),Yk=eb(),Er=rb(),Wk=Nr(),Qk=ob(),zk=lb(),Kk=te(),Jk=Ce(),Xk=Kk("replace"),Zk=TypeError,hb=hu("".indexOf),eA=hu("".replace),db=hu("".slice),tA=Math.max,pb=function(i,e,t){return t>i.length?-1:e===""?t:hb(i,e,t)};Uk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cb(this),a,s,n,o,u,l,c,d,p,h=0,f=0,b="";if(!Gk(e)){if(a=Yk(e),a&&(s=Er(cb(Qk(e))),!~hb(s,"g")))throw Zk("`.replaceAll` does not allow non-global regexes");if(n=Wk(e,Xk),n)return Hk(n,e,r,t);if(Jk&&a)return eA(Er(r),e,t)}for(o=Er(r),u=Er(e),l=jk(t),l||(t=Er(t)),c=u.length,d=tA(1,c),h=pb(o,u,0);h!==-1;)p=l?Er(t(u,h,o)):zk(u,o,h,[],void 0,t),b+=db(o,f,h)+p,f=h+c,h=pb(o,u,h+d);return f<o.length&&(b+=db(o,f)),b}})});var bb=m((fV,mb)=>{"use strict";Jm();Xm();fb();var rA=za();mb.exports=rA("String","replaceAll")});var vb=m((mV,gb)=>{"use strict";var iA=bb();gb.exports=iA});var yb=m((bV,Sb)=>{"use strict";var aA=vb();Sb.exports=aA});var cl="__VERSION__";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),At=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(At||{});var oa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(oa||{}),Ks=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ks||{});var Js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Js||{});import{assertNever as bl,assertNonNullable as xv,isNonNullable as ua,ValueSubject as Xs,Subject as Pv,Subscription as wv,merge as kv,observableFrom as Av,fromEvent as pl,map as hl,tap as fl,filterChanged as Rv,isNullable as Zs,ErrorCategory as ml}from"@vkontakte/videoplayer-shared";var dl=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var la=class{constructor(e){this.connection$=new Xs(void 0);this.castState$=new Xs("NOT_AVAILABLE");this.errorEvent$=new Pv;this.realCastState$=new Xs("NOT_AVAILABLE");this.subscription=new wv;var s;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 r=ua((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ml.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ua(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Zs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Zs(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(pl(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.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 bl(a.sessionState)}})).add(kv(pl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),hl(a=>a.castState)),Av([r.getCastState()])).pipe(Rv(),hl(Lv),fl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=ua(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();xv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(Zs(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?ua(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ml.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Lv=i=>{switch(i){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 bl(i)}};var Vg=Fe(_a(),1);var em=Fe(Ka(),1);import{assertNever as Gf}from"@vkontakte/videoplayer-shared";var re=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Gf(t)}return i},Fo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Gf(e)}};var E=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as HP,Subject as Ja,merge as Yf}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Ja;this.transitionEnded$=new Ja;this.transitionUpdated$=new Ja;this.forceChanged$=new Ja;this.stateChangeStarted$=Yf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Yf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||HP(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as jP}from"@vkontakte/videoplayer-shared";var Wf=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":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 jP(i)}};import{assertNever as gr,assertNonNullable as Vt,debounce as Qf,ErrorCategory as zf,fromEvent as _t,isNonNullable as Kf,map as Jf,merge as Xf,observableFrom as GP,Subject as YP,Subscription as qo,timeout as WP,getHighestQuality as QP}from"@vkontakte/videoplayer-shared";var zP=5,KP=5,JP=500,Zf=7e3,ei=class{constructor(e){this.subscription=new qo;this.loadMediaTimeoutSubscription=new qo;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:gr(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:gr(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:gr(e)}break}default:gr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wf(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 qo;this.subscription.add(e),this.subscription.add(Xf(this.videoState.stateChangeStarted$.pipe(Jf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Jf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new YP;e.add(a.pipe(Qf(JP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>zP)&&a.next(o),s=o})),e.add(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<KP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:gr(n)}}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Xf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,GP(["init"])).pipe(Qf(0));t(r,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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Vt(c);let d=QP(Object.keys(c));Vt(d);let p=c[d];Vt(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Vt(c),r=c.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let c=t[e];Vt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Vt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Vt(c),r=re(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:zf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return gr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Kf(o)&&(n.metadata.title=o),Kf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(WP(Zf).subscribe(()=>s(`timeout(${Zf})`)))});(0,em.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:zf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ti=i=>{i.removeAttribute("src"),i.load()};var tm=i=>{try{i.pause(),i.playbackRate=0,ti(i),i.remove()}catch(e){console.error(e)}};var Uo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ho=window.WeakMap?new WeakMap:new Uo,ue=i=>{let e=i.querySelector("video"),t=!!e;return e?ti(e):(e=document.createElement("video"),i.appendChild(e)),Ho.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},le=i=>{let e=Ho.get(i);Ho.delete(i),e?ti(i):tm(i)};import{assertNonNullable as ri,isNonNullable as je,isNullable as ew,fromEvent as vr,merge as rm,observableFrom as im,filterChanged as am,map as ii,Subject as sm,Subscription as tw,ValueSubject as rw,ErrorCategory as iw}from"@vkontakte/videoplayer-shared";import{isNonNullable as jo,isNullable as XP,Subscription as ZP}from"@vkontakte/videoplayer-shared";var Xa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=XP(a),l=new ZP;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},He=(i,e,t)=>Xa(e,()=>i.loop,r=>{jo(r)&&(i.loop=r)},{onError:t}),ce=(i,e,t,r)=>Xa(e,()=>({muted:i.muted,volume:i.volume}),a=>{jo(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ie=(i,e,t,r)=>Xa(e,()=>i.playbackRate,a=>{jo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),dt=Xa;var aw=i=>["__",i.language,i.label].join("|"),sw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Go=class i{constructor(){this.available$=new sm;this.current$=new rw(void 0);this.error$=new sm;this.subscription=new tw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:iw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{je(s)&&this.setInternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ii(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{je(s)&&this.setExternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ii(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(dt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ri(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(rm(vr(e,"addtrack"),vr(e,"removetrack"),im(["init"])).pipe(ii(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),am((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(rm(vr(e,"change"),im(["init"])).pipe(ii(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ii(r=>r&&this.htmlTextTrackToITextTrack(r).id),am()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add(vr(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;je(t.align)&&(a.align=t.align),je(t.position)&&(a.position=t.position),je(t.size)&&(a.size=t.size),je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:aw(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(a))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ew(e)||!sw(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){ri(this.video);let t=document.createElement("track");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){ri(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},Ee=Go;var Je=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var nm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Yo=i=>{let e=nm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},om=i=>{let e=nm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as pt,merge as lm,filterChanged as ow,isNonNullable as cm,Subject as uw,filter as dm,mapTo as pm,combine as lw,once as cw,ErrorCategory as dw,ValueSubject as hm,getCurrentBrowser as pw,CurrentClientBrowser as hw}from"@vkontakte/videoplayer-shared";var nw=3,um=(i,e,t=nw)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var de=i=>{let e=y=>xe(i,y).pipe(pm(void 0)),r=lm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(pt(y=>y.type==="ended"?i.readyState<2:i.readyState<3),ow()),a=lm(xe(i,"progress"),xe(i,"timeupdate")).pipe(pt(()=>um(i.buffered,i.currentTime))),n=pw().browser===hw.Safari?lw({play:e("play").pipe(cw()),playing:e("playing")}).pipe(pm(void 0)):e("playing"),o=xe(i,"volumechange").pipe(pt(()=>({muted:i.muted,volume:i.volume}))),u=xe(i,"ratechange").pipe(pt(()=>i.playbackRate)),l=xe(i,"error").pipe(dm(()=>!!(i.error||i.played.length)),pt(()=>{var T;let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:dw.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(T=i.error)!=null?T:void 0}})),c=xe(i,"timeupdate").pipe(pt(()=>i.currentTime)),d=new uw,p=.3,h;c.subscribe(y=>{i.loop&&cm(h)&&cm(y)&&h>=i.duration-p&&y<=p&&d.next(h),h=y});let f=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),v=new hm(om(i));f.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new hm(Yo(i));return xe(i,"fullscreenchange").pipe(pt(()=>Yo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(dm(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:xe(i,"durationchange").pipe(pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ht}from"@vkontakte/videoplayer-shared";var ft=i=>{switch(i){case"mobile":return ht.Q_144P;case"lowest":return ht.Q_240P;case"low":return ht.Q_360P;case"sd":case"medium":return ht.Q_480P;case"hd":case"high":return ht.Q_720P;case"fullhd":case"full":return ht.Q_1080P;case"quadhd":case"quad":return ht.Q_1440P;case"ultrahd":case"ultra":return ht.Q_2160P}};var Jo=Fe(Za(),1);import{isNonNullable as mt,isNullable as Qo,now as Pm,isHigher as zo,isHigherOrEqual as Em,isInvariantQuality as xm,isLower as Ko,isLowerOrEqual as Iw,videoSizeToQuality as Ew,assertNotEmptyArray as xw}from"@vkontakte/videoplayer-shared";var Wo=!1,Xe={},ym=i=>{Wo=i},Tm=()=>{Xe={}},Im=i=>{i(Xe)},ai=(i,e)=>{var t;Wo&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[i]=e)},ae=class{constructor(e){this.name=e}next(e){var r,a;if(!Wo)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(a=Xe.series[this.name])!=null?a:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var Pw=new ae("best_bitrate"),ww=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,es=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Pm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},kw='Assertion "ABR Tracks is empty array" failed',Aw=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var H,L,w,U,z;xw(i,kw);let p=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&Ew(h),b=r.considerPlaybackRate&&mt(o)?o:1,v=i.filter(A=>!xm(A.quality)).sort((A,x)=>zo(A.quality,x.quality)?-1:1),S=(L=(0,Jo.default)(v,-1))==null?void 0:L.quality,g=(w=(0,Jo.default)(v,0))==null?void 0:w.quality,y=Qo(a)||mt(a.min)&&mt(a.max)&&Ko(a.max,a.min)||mt(a.min)&&g&&zo(a.min,g)||mt(a.max)&&S&&Ko(a.max,S),T=b*ww(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},D=v.filter(A=>(f?Ko(A.quality,f):!0)?(mt(t)&&isFinite(t)&&mt(A.bitrate)?t-s>=A.bitrate*T:!0)?r.lazyQualitySwitch&&mt(r.minBufferToSwitchUp)&&u&&!xm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&zo(A.quality,u.quality)?(I[A.quality]="Buffer",!1):!!c&&Em(A.quality,c)?(I[A.quality]="DroppedFramesLimit",!1):y||(Qo(a.max)||Iw(A.quality,a.max))&&(Qo(a.min)||Em(A.quality,a.min))?!0:(I[A.quality]="FitsQualityLimits",!1):(I[A.quality]="FitsThroughput",!1):(I[A.quality]="FitsContainer",!1))[0];D&&D.bitrate&&Pw.next(D.bitrate);let $=(U=D!=null?D:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];$.quality!==((z=l==null?void 0:l.last)==null?void 0:z.quality)&&d({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${i.map(
|
|
8
|
+
${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(
|
|
12
|
+
${Object.entries(r!=null?r:{}).map(([A,x])=>`${A}: ${x}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${f},
|
|
17
17
|
throughput: ${t},
|
|
18
|
-
reserve: ${
|
|
18
|
+
reserve: ${s},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
20
|
+
playbackRateFactor: ${b},
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
23
|
-
minBufferToSwitchUp: ${
|
|
22
|
+
bitrateFactor: ${T},
|
|
23
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${c},
|
|
25
|
-
limitsAreInvalid: ${
|
|
26
|
-
maxQualityLimit: ${
|
|
27
|
-
minQualityLimit: ${
|
|
25
|
+
limitsAreInvalid: ${y},
|
|
26
|
+
maxQualityLimit: ${a==null?void 0:a.max},
|
|
27
|
+
minQualityLimit: ${a==null?void 0:a.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(I).map(([A,x])=>`${A}: ${x}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),N}return d==null||d.recordSwitch(x),x};var at=i=>new URL(i).hostname,G;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));const zo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Wt=i=>te(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!zo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return zo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function ke(){return le()}function Fl(i){return ke()-i}function Qo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function JS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Is(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,c,l,h=!1,f="arraybuffer",v=7e3,m=2e3,g=()=>{if(u)return;P(c);const B=Fl(c);let x;if(B<m){x=m-B,setTimeout(g,x);return}m*=2,m>v&&(m=v),n&&n.abort(),n=new r,q()};const S=B=>(a=B,ee),E=B=>(l=B,ee),A=()=>(f="json",ee),w=()=>{if(!u){if(--d>=0){g(),s&&s();return}u=!0,l&&l(),t&&t()}},k=B=>(h=B,ee),q=()=>{c=ke(),n=new r,n.open("get",i);let B=0,x,ae=0;const N=()=>(P(c),Math.max(c,Math.max(x||0,ae||0)));if(a&&n.addEventListener("progress",R=>{const Z=ke();a.updateChunk&&R.loaded>B&&(a.updateChunk(N(),R.loaded-B),B=R.loaded,x=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&a){const Z=n.response.byteLength-B;Z&&a.updateChunk&&a.updateChunk(N(),Z)}n.responseType==="json"&&!Object.values(n.response).length?w():(l&&l(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const R=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=ke(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=f,n.send(),ee},ee={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:B=>(d=B,ee),withRetryInterval:(B,x)=>(_(B)&&(m=B),_(x)&&(v=x),ee),withTimeout:B=>(o=B,ee),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return ee}const XS=100,ZS=2e3,eb=500;let tb=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-eb;if(t-e>ZS){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>XS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class ib{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ke(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=ke()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Is(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ke()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=ke();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const gs=1e4,zr=3,sb=6e4,rb=10,ab=1,nb=500;class ob{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new tb(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Qo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Qo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||_(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{JS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ib(zr,gs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,c=!1;const l=()=>{const w=a&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,k,q)=>{u&&u.abort(),u=Is(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(gs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zr).withFinally(()=>{u=null}).send()},f=(w,k,q)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},m=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const q=ke()-1e4;let W=0;for(let j=0;j<this.bufferStates.length;j++){const X=this.bufferStates[j];w=Math.min(w,X.buf),X.ts<q&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${w} drop=${W} jitter=${this.sourceJitter}`);let J=w-ab;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?v(1.15):J>1?v(1.1):J>.3?v(1.05):v(1)}},S=w=>{let k;const q=()=>k&&k.start?k.start.length:0,W=R=>k.start[R]/1e3,J=R=>k.dur[R]/1e3,j=R=>k.fragIndex+R,X=(R,Z)=>({chunkIdx:j(R),startTS:W(R),dur:J(R),discontinuity:Z}),ee=()=>{let R=0;if(k&&k.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=Z;this.sourceJitter>1&&(me+=this.sourceJitter-1);let be=k.dur.length-1;for(;be>=0&&(me-=k.dur[be],!(me<=0));--be);R=Math.min(be,k.dur.length-1-ue),R=Math.max(R,0)}return X(R,!0)},B=R=>{const Z=q();if(!(Z<=0)){if(_(R)){for(let ue=0;ue<Z;ue++)if(W(ue)>R)return X(ue)}return ee()}},x=R=>{const Z=q(),ue=R?R.chunkIdx+1:0,me=ue-k.fragIndex;if(!(Z<=0)){if(!R||me<0||me-Z>rb)return t(`Resync: offset=${me} bChunks=${Z} chunk=`+JSON.stringify(R)),ee();if(!(me>=Z))return X(ue-k.fragIndex,!1)}},ae=(R,Z,ue)=>{d&&d.abort(),d=Is(this.urlResolver.resolve(R,!0,this.lowLatency),Z,ue,()=>this._retryCallback()).withTimeout(gs).withRetryCount(zr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(R,Z)=>{ae(w,ue=>{if(!l())return;k=ue;const me=!!k.lowLatency;me!==this.lowLatency&&m(me);let be=0;for(let Je=0;Je<k.dur.length;++Je)be+=k.dur[Je];be>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,R(B(Z))},()=>this._handleNetworkError())},nextChunk:x}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{const{videoElement:k,logger:q}=this.params;let W=S(e.jidxUrl),J,j,X,ee,B=0,x,ae,N;const R=()=>{x&&(clearTimeout(x),x=void 0);const Q=Math.max(nb,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=B+Q,Ie=ke(),Le=Math.min(1e4,$e-Ie);B=Ie;const Qt=()=>{d||l()&&W.seek(()=>{l()&&(B=ke(),Z(),R())})};Le>0?x=window.setTimeout(()=>{this.paused?R():Qt()},Le):Qt()},Z=()=>{let Q;for(;Q=W.nextChunk(ee);)ee=Q,$i(Q);const $e=W.nextChunk(X);if($e){if(X&&$e.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}Je($e)}else R()},ue=(Q,$e)=>{if(!l()||!this.sourceBuffer)return;let Ie,Le,Qt;const Ai=ot=>{window.setTimeout(()=>{l()&&ue(Q,$e)},ot)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),Ai(100);else{const ot=ke(),Be=k.currentTime;!this.paused&&k.buffered.length>1&&ae===Be&&ot-N>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),ae!==Be&&(ae=Be,N=ot);const Kt=this._getBufferSizeSec();if(Kt>30)q(`Buffered ${Kt} seconds; delaying appendBuffer`),Ai(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Kt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(wi){if(wi.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Qt=this.sourceBuffer.buffered.length,Qt!==0&&(Ie=this.sourceBuffer.buffered.start(0),Le=Be,Le-Ie>4&&this.sourceBuffer.remove(Ie,Le-3)),Ai(1e3);else throw wi}}},me=()=>{j&&J&&(q([`Appending chunk, sz=${j.byteLength}:`,JSON.stringify(X)]),ue(j,function(){j=null,Z()}))},be=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Je=Q=>{l()&&f(be(Q),($e,Ie)=>{if(l()){if(Ie/=1e3,j=$e,X=Q,n=Q.startTS,Ie){const Le=Math.min(10,Q.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}me()}},()=>this._handleNetworkError())},$i=Q=>{l()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(Q),!1)))},zt=Q=>{l()&&(e.cachedHeader=Q,ue(Q,()=>{J=!0,me()}))};a=!0,W.seek(Q=>{if(l()){if(B=ke(),!Q){R();return}ee=Q,!K(w)||Q.startTS>w?Je(Q):(X=Q,Z())}},w),e.cachedHeader?zt(e.cachedHeader):h(e.headerUrl,zt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=l=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),v=l/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,f)=>{const v=ke();if(this.chunkRateEstimator.addInterval(h,v,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:g}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Fl(n)<3e4)return;s(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{const f=a.updateChunk(l,h);return f&&d(),f},notifySwitch:l=>{const h=ke();l<o&&(n=h),o=l}}}_fetchManifest(e,t,s){this.manifestRequest=Is(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(gs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){const{videoElement:e}=this.params;Wt(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(G.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},sb))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Vl{constructor(){this.onDroopedVideoFramesLimit$=new L,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new L,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Bt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&fi(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(D(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ci(this.droppedFramesChecker.checkTime).pipe(fe(()=>this.playing),fe(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(rt(this.droppedFramesChecker.checkTime)),s=F(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>As(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const xa=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},Ei=(i,e)=>new Va(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||xa()))},Object.assign(Object.assign({},s),e));r.observe(i);const a=D(document,"visibilitychange").pipe($(n=>!document.hidden||xa())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}}),db=[G.PAUSED,G.PLAYING,G.READY],lb=[G.PAUSED,G.PLAYING,G.READY];class ub{constructor(e){this.subscription=new re,this.videoState=new he(G.STOPPED),this.representations$=new y([]),this.textTracksManager=new At,this.droppedFramesManager=new Vl,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new fn,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,c=[];for(const l of d){const h=(a=l.name)!==null&&a!==void 0?a:l.index.toString(10),f=(n=Xs(l.name))!==null&&n!==void 0?n:Mt(l.video),v=l.bitrate/1e3,m=Object.assign({},l.video);if(!f)continue;const g={id:h,quality:f,bitrate:v,size:m};c.push({track:g,representation:l})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:l})=>l)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===G.MANIFEST_READY&&this.videoState.setState(G.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,c=(u=this.representations$.getValue().find(({representation:l})=>l===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:d,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(G.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(lb.includes(r)&&(d||c)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&db.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case G.STOPPED:this.videoState.startTransitionTo(G.MANIFEST_READY),this.dash.attachSource(Qe(this.params.source.url));return;case G.MANIFEST_READY:this.videoState.startTransitionTo(G.READY),this.prepare();break;case G.READY:if(n===p.PAUSED)this.videoState.setState(G.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(G.PLAYING);const l=o==null?void 0:o.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play()}return;case G.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case G.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(G.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(Qe(this.params.source.url,l))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};F(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Gt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(at(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=qt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe($(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===G.READY&&this.videoState.setState(G.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(G.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ue({zeroTime:this.zeroTime$.pipe(fe(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Qi(this.video,this.params.desiredState.isLooped,t)).add(Yt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Ti(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ei(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&wu(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case G.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case G.MANIFEST_READY:case G.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case G.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case G.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(F(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ge(["init"])).pipe(rt(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),jt(this.video)}createLiveDashPlayer(){const e=new ob({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!d&&_(u)?u:Zs(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=c==null?void 0:c.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(h||l!==f)&&this.setVideoTrack(c),v&&this.setAutoQuality(d),h||v||l!==f){const m=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===G.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Qe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Te;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Te||(Te={}));var et;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(et||(et={}));var Bs;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Bs||(Bs={}));var He;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(He||(He={}));var V;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(V||(V={}));var vi;(function(i){i.MP4="mp4",i.WEBM="webm"})(vi||(vi={}));var Ns;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Ns||(Ns={}));var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));var xi=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class Ko{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Ul extends Ko{constructor(){super(),this.listeners||Ko.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Hl=class{constructor(){Object.defineProperty(this,"signal",{value:new Ul,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Hl.prototype[Symbol.toStringTag]="AbortController",Ul.prototype[Symbol.toStringTag]="AbortSignal");function Gl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function cb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Gl({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,c){let l;c&&c.signal&&(l=c.signal,delete c.signal);const h=new t(d,c);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const c=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(c){let l;try{l=new DOMException("Aborted","AbortError")}catch(f){l=new Error("Aborted"),l.name="AbortError"}if(c.aborted)return Promise.reject(l);const h=new Promise((f,v)=>{c.addEventListener("abort",()=>v(l),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const er=Gl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jl=er?cb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Fi=er?jl.fetch:window.fetch;er?jl.Request:window.Request;const mi=er?Hl:window.AbortController;var Oa=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const hb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},fb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Jo=fb?hb:window.requestIdleCallback;var Qr,Kr;const pb=16;let Yl=!1;try{Yl=Fa().browser===Td.Safari&&parseInt((Kr=(Qr=navigator.userAgent.match(/Version\/(\d+)/))===null||Qr===void 0?void 0:Qr[1])!==null&&Kr!==void 0?Kr:"",10)<=pb}catch(i){console.error(i)}class mb{constructor(e){this.bufferFull$=new L,this.error$=new L,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return te(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return te(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return te(this,void 0,void 0,function*(){return new Promise(t=>{let s;Yl&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{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:H(t)}}}var Xo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Me{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.type=this.readString(4),this.size32=s<=e.buffer.byteLength-e.byteOffset?s:NaN;const r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class ql extends Me{}class vb extends Me{}class gb extends Me{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class Sb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class bb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class yb extends Me{constructor(e,t){super(e,t),this.data=this.content}}class vt extends Me{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class Wl extends vt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Tb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Eb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Ot;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ot||(Ot={}));class $b extends vt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Ot.MONOSCOPIC;break;case 1:this.stereoMode=Ot.TOP_BOTTOM;break;case 2:this.stereoMode=Ot.LEFT_RIGHT;break;case 3:this.stereoMode=Ot.STEREO_CUSTOM;break;case 4:this.stereoMode=Ot.RIGHT_LEFT;break}this.cursor+=1}}class Ab extends vt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class wb extends vt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class kb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Pb extends vt{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 _b extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ib extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Rb extends vt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class Cb extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Lb extends vt{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 Db extends vt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class xb extends vt{constructor(e,t){super(e,t),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let s=0;s<this.sampleCount;s++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}var oe;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UuidBox="uuid",i.UnknownBox="unknown"})(oe||(oe={}));const Ob={[oe.FtypBox]:gb,[oe.MoovBox]:Sb,[oe.MoofBox]:bb,[oe.MdatBox]:yb,[oe.SidxBox]:Wl,[oe.TrakBox]:Tb,[oe.MdiaBox]:kb,[oe.MfhdBox]:Rb,[oe.TkhdBox]:Pb,[oe.TrafBox]:Cb,[oe.TfhdBox]:Lb,[oe.TfdtBox]:Db,[oe.TrunBox]:xb,[oe.MinfBox]:_b,[oe.Sv3dBox]:Eb,[oe.St3dBox]:$b,[oe.PrhdBox]:Ab,[oe.ProjBox]:Ib,[oe.EquiBox]:wb,[oe.UuidBox]:vb,[oe.UnknownBox]:ql};class Ft{constructor(e={}){this.options=Object.assign({offset:0},e)}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;)try{const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(!n.size)break;t.push(n),s+=n.size}catch(r){break}return t}createBox(e,t){const s=Ob[e];return s?new s(t,new Ft):new ql(t,new Ft)}}class mn{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var s,r,a;(s=(r=this.index)[a=t.type])!==null&&s!==void 0||(r[a]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const Mb=new TextDecoder("ascii"),Bb=i=>Mb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Nb=i=>{const e=new Wl(i,new Ft);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:V.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Fb=(i,e)=>{const s=new Ft().parse(i),r=new mn(s),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;const o=a[0],u=n[n.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,d,l)},Vb=(i,e)=>{const s=new Ft().parse(i),a=new mn(s).findAll("traf"),n=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun");let d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,h)=>l+h,0):d=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Ub=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ns.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Ft().parse(i),r=new mn(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Hb={validateData:Bb,parseInit:Ub,getIndexRange:()=>{},parseSegments:Nb,parseFeedableSegmentChunk:Fb,getSegmentEndTime:Vb};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var I;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(I||(I={}));const Zo={[T.EBML]:{type:I.Master},[T.EBMLVersion]:{type:I.UnsignedInteger},[T.EBMLReadVersion]:{type:I.UnsignedInteger},[T.EBMLMaxIDLength]:{type:I.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[T.DocType]:{type:I.String},[T.DocTypeVersion]:{type:I.UnsignedInteger},[T.DocTypeReadVersion]:{type:I.UnsignedInteger},[T.Void]:{type:I.Binary},[T.Segment]:{type:I.Master},[T.SeekHead]:{type:I.Master},[T.Seek]:{type:I.Master},[T.SeekID]:{type:I.Binary},[T.SeekPosition]:{type:I.UnsignedInteger},[T.Info]:{type:I.Master},[T.TimestampScale]:{type:I.UnsignedInteger},[T.Duration]:{type:I.Float},[T.Tracks]:{type:I.Master},[T.TrackEntry]:{type:I.Master},[T.Video]:{type:I.Master},[T.Projection]:{type:I.Master},[T.ProjectionType]:{type:I.UnsignedInteger},[T.ProjectionPrivate]:{type:I.Master},[T.Chapters]:{type:I.Master},[T.Cluster]:{type:I.Master},[T.Timestamp]:{type:I.UnsignedInteger},[T.SilentTracks]:{type:I.Master},[T.SilentTrackNumber]:{type:I.UnsignedInteger},[T.Position]:{type:I.UnsignedInteger},[T.PrevSize]:{type:I.UnsignedInteger},[T.SimpleBlock]:{type:I.Binary},[T.BlockGroup]:{type:I.Master},[T.EncryptedBlock]:{type:I.Binary},[T.Attachments]:{type:I.Master},[T.Tags]:{type:I.Master},[T.Cues]:{type:I.Master},[T.CuePoint]:{type:I.Master},[T.CueTime]:{type:I.UnsignedInteger},[T.CueTrackPositions]:{type:I.Master},[T.CueTrack]:{type:I.UnsignedInteger},[T.CueClusterPosition]:{type:I.UnsignedInteger},[T.CueRelativePosition]:{type:I.UnsignedInteger},[T.CueDuration]:{type:I.UnsignedInteger},[T.CueBlockNumber]:{type:I.UnsignedInteger},[T.CueCodecState]:{type:I.UnsignedInteger},[T.CueReference]:{type:I.Master},[T.CueRefTime]:{type:I.UnsignedInteger}},zl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Fs(i,t),r=s in Zo,a=r?Zo[s].type:I.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,c=Fs(u),l=d*Math.pow(2,(o-1)*8)+c,h=t+o;let f;return h+l>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,l),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+l,value:f,valueSize:l}},Fs=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},it=(i,e)=>{switch(e){case I.SignedInteger:return i.getInt8(0);case I.UnsignedInteger:return Fs(i);case I.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(i);case I.UTF8:return new TextDecoder("utf-8").decode(i);case I.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case I.Master:return i;case I.Binary:return i;default:H(e)}},gi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=zl(s);if(!e(r))return;r.type===I.Master&&gi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Gb=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=zl(i);return gi(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=it(o,n):a===T.DocType?t=it(o,n):a===T.DocTypeReadVersion&&(s=it(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Ql=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],jb=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],Yb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,c=!1;const l=0;return gi(i,({tag:h,type:f,value:v,valueSize:m})=>{if(h===T.SeekID){const g=it(v,f);d=Fs(g)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=v.byteOffset,t=v.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=it(v,f):h===T.Duration?r=it(v,f):h===T.SeekPosition&&d===T.Cues?u=it(v,f):h===T.Tracks?gi(v,({tag:g,type:S,value:E})=>g===T.ProjectionType?(c=it(E,S)===1,!1):!0):a&&n&&Ql.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:l,projectionType:Ns.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},qb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wb=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return gi(i,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=it(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=it(d,u));break;default:t&&Ql.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:c}=o,l=a[u+1];return{status:V.NONE,time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},zb=i=>{let e=0,t=!1;try{gi(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):jb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Qb={validateData:Gb,parseInit:Yb,getIndexRange:qb,parseSegments:Wb,parseFeedableSegmentChunk:zb};var Kb=pt,Jb=Ui,Xb=_e,Zb=Xb("match"),ey=function(i){var e;return Kb(i)&&((e=i[Zb])!==void 0?!!e:Jb(i)=="RegExp")},ty=qi,iy=String,sy=function(i){if(ty(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return iy(i)},ry=mt,ay=function(){var i=ry(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},ny=Oe,oy=nt,dy=Gs,ly=ay,ed=RegExp.prototype,uy=function(i){var e=i.flags;return e===void 0&&!("flags"in ed)&&!oy(i,"flags")&&dy(ed,i)?ny(ly,i):e},vn=Ye,cy=Ws,hy=Math.floor,Jr=vn("".charAt),fy=vn("".replace),Xr=vn("".slice),py=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,my=/\$([$&'`]|\d{1,2})/g,vy=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=my;return r!==void 0&&(r=cy(r),u=py),fy(a,u,function(d,c){var l;switch(Jr(c,0)){case"$":return"$";case"&":return i;case"`":return Xr(e,0,t);case"'":return Xr(e,n);case"<":l=r[Xr(c,1,-1)];break;default:var h=+c;if(h===0)return d;if(h>o){var f=hy(h/10);return f===0?d:f<=o?s[f-1]===void 0?Jr(c,1):s[f-1]+Jr(c,1):d}l=s[h-1]}return l===void 0?"":l})},gy=Ke,Sy=Oe,gn=Ye,td=Ua,by=ge,yy=Hi,Ty=ey,ri=sy,Ey=qs,$y=uy,Ay=vy,wy=_e,ky=wy("replace"),Py=TypeError,Kl=gn("".indexOf),_y=gn("".replace),id=gn("".slice),Iy=Math.max,sd=function(i,e,t){return t>i.length?-1:e===""?t:Kl(i,e,t)};gy({target:"String",proto:!0},{replaceAll:function(e,t){var s=td(this),r,a,n,o,u,d,c,l,h,f=0,v=0,m="";if(!yy(e)){if(r=Ty(e),r&&(a=ri(td($y(e))),!~Kl(a,"g")))throw Py("`.replaceAll` does not allow non-global regexes");if(n=Ey(e,ky),n)return Sy(n,e,s,t);if(r)return _y(ri(s),e,t)}for(o=ri(s),u=ri(e),d=by(t),d||(t=ri(t)),c=u.length,l=Iy(1,c),f=sd(o,u,0);f!==-1;)h=d?ri(t(u,f,o)):Ay(u,o,f,[],void 0,t),m+=id(o,v,f)+h,v=f+c,f=sd(o,u,f+l);return v<o.length&&(m+=id(o,v)),m}});var Ry=un,Cy=Ry("String","replaceAll"),Ly=Cy,Dy=Ly,xy=Dy,Oy=xy,rd=Us(Oy);const My=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},ad=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},oi=(i,e)=>{let t=i;t=rd(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=rd(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},By=(i,e)=>{var t,s,r,a,n,o,u,d,c,l,h,f,v,m,g,S,E,A,w,k,q,W,J,j,X,ee,B,x,ae,N,R,Z,ue,me,be,Je,$i,zt,Q,$e,Ie,Le;const Ai=new DOMParser().parseFromString(i,"application/xml"),ot={video:[],audio:[],text:[]},Be=Ai.children[0],Kt=Be.getElementsByTagName("Period")[0],wi=(r=(s=(t=Be.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",su=Kt.children,ru=Be.getAttribute("type")==="dynamic",yn=Be.getAttribute("availabilityStartTime"),au=yn?new Date(yn).getTime():void 0;let wt;const Tn=Be.getAttribute("mediaPresentationDuration"),En=Kt.getAttribute("duration"),tr=Be.getElementsByTagName("vk:Attrs")[0],$n=tr==null?void 0:tr.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Tn)wt=ad(Tn);else if(En){const Ne=ad(En);_(Ne)&&(wt=Ne)}else $n&&(wt=parseInt($n,10));let nu=0;const ir=(n=(a=Be.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],ou=ir.includes(Bs.WEBM_AS_IN_FFMPEG)||ir.includes(Bs.WEBM_AS_IN_SPEC)?vi.WEBM:vi.MP4;for(const Ne of su){const Ki=Ne.getAttribute("mimeType"),du=Ne.getAttribute("codecs"),An=(o=Ne.getAttribute("contentType"))!==null&&o!==void 0?o:Ki==null?void 0:Ki.split("/")[0],lu=(d=(u=Ne.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&d!==void 0?d:[],wn=Ne.querySelectorAll("Representation"),uu=Ne.querySelector("SegmentTemplate");if(An===Te.TEXT){for(const ve of wn){const gt=ve.getAttribute("id")||"",Ji=Ne.getAttribute("lang"),Jt=Ne.getAttribute("label"),sr=(h=(l=(c=ve.querySelector("BaseURL"))===null||c===void 0?void 0:c.textContent)===null||l===void 0?void 0:l.trim())!==null&&h!==void 0?h:"",rr=new URL(sr||wi,e).toString(),Xi=gt.includes("_auto");ot[Te.TEXT].push({id:gt,lang:Ji,label:Jt,isAuto:Xi,kind:Te.TEXT,url:rr})}continue}for(const ve of wn){const gt=(f=ve.getAttribute("mimeType"))!==null&&f!==void 0?f:Ki,Ji=(m=(v=ve.getAttribute("codecs"))!==null&&v!==void 0?v:du)!==null&&m!==void 0?m:"",Jt=(S=(g=ve.getAttribute("contentType"))!==null&&g!==void 0?g:gt==null?void 0:gt.split("/")[0])!==null&&S!==void 0?S:An,sr=(A=(E=Ne.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],rr=parseInt((w=ve.getAttribute("width"))!==null&&w!==void 0?w:"",10),Xi=parseInt((k=ve.getAttribute("height"))!==null&&k!==void 0?k:"",10),kn=parseInt((q=ve.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,Pn=(W=ve.getAttribute("frameRate"))!==null&&W!==void 0?W:"",cu=(J=ve.getAttribute("quality"))!==null&&J!==void 0?J:void 0,hu=Pn?My(Pn):void 0,fu=(j=ve.getAttribute("id"))!==null&&j!==void 0?j:(nu++).toString(10),pu=Jt==="video"?`${Xi}p`:Jt==="audio"?`${kn}Kbps`:Ji,mu=`${fu}@${pu}`,vu=(B=(ee=(X=ve.querySelector("BaseURL"))===null||X===void 0?void 0:X.textContent)===null||ee===void 0?void 0:ee.trim())!==null&&B!==void 0?B:"",_n=new URL(vu||wi,e).toString(),gu=[...ir,...lu,...sr];let ar;const Su=ve.querySelector("SegmentBase"),kt=(x=ve.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:uu;if(Su){const Pt=(N=(ae=ve.querySelector("SegmentBase Initialization"))===null||ae===void 0?void 0:ae.getAttribute("range"))!==null&&N!==void 0?N:"",[_t,or]=Pt.split("-").map(Xt=>parseInt(Xt,10)),St={from:_t,to:or},ki=(R=ve.querySelector("SegmentBase"))===null||R===void 0?void 0:R.getAttribute("indexRange"),[dr,Zi]=ki?ki.split("-").map(Xt=>parseInt(Xt,10)):[],Pi=ki?{from:dr,to:Zi}:void 0;ar={type:He.BYTE_RANGE,url:_n,initRange:St,indexRange:Pi}}else if(kt){const Pt={representationId:(Z=ve.getAttribute("id"))!==null&&Z!==void 0?Z:void 0,bandwidth:(ue=ve.getAttribute("bandwidth"))!==null&&ue!==void 0?ue:void 0},_t=parseInt((me=kt.getAttribute("timescale"))!==null&&me!==void 0?me:"",10),or=(be=kt.getAttribute("initialization"))!==null&&be!==void 0?be:"",St=kt.getAttribute("media"),ki=($i=parseInt((Je=kt.getAttribute("startNumber"))!==null&&Je!==void 0?Je:"",10))!==null&&$i!==void 0?$i:1,dr=oi(or,Pt);if(!St)throw new ReferenceError("No media attribute in SegmentTemplate");const Zi=(zt=kt.querySelectorAll("SegmentTimeline S"))!==null&&zt!==void 0?zt:[],Pi=[];let Xt=0,lr="",ur=0;if(Zi.length){let es=ki,qe=0;for(const Zt of Zi){const Xe=parseInt((Q=Zt.getAttribute("d"))!==null&&Q!==void 0?Q:"",10),It=parseInt(($e=Zt.getAttribute("r"))!==null&&$e!==void 0?$e:"",10)||0,ts=parseInt((Ie=Zt.getAttribute("t"))!==null&&Ie!==void 0?Ie:"",10);qe=Number.isFinite(ts)?ts:qe;const cr=Xe/_t*1e3,hr=qe/_t*1e3;for(let is=0;is<It+1;is++){const yu=oi(St,Object.assign(Object.assign({},Pt),{segmentNumber:es.toString(10),segmentTime:(qe+is*Xe).toString(10)})),In=(hr!=null?hr:0)+is*cr,Tu=In+cr;es++,Pi.push({time:{from:In,to:Tu},url:yu})}qe+=(It+1)*Xe,Xt+=(It+1)*cr}ur=qe/_t*1e3,lr=oi(St,Object.assign(Object.assign({},Pt),{segmentNumber:es.toString(10),segmentTime:qe.toString(10)}))}else if(_(wt)){const qe=parseInt((Le=kt.getAttribute("duration"))!==null&&Le!==void 0?Le:"",10)/_t*1e3,Zt=Math.ceil(wt/qe);let Xe=0;for(let It=1;It<Zt;It++){const ts=oi(St,Object.assign(Object.assign({},Pt),{segmentNumber:It.toString(10),segmentTime:Xe.toString(10)}));Pi.push({time:{from:Xe,to:Xe+qe},url:ts}),Xe+=qe}ur=Xe,lr=oi(St,Object.assign(Object.assign({},Pt),{segmentNumber:Zt.toString(10),segmentTime:Xe.toString(10)}))}const bu={time:{from:ur,to:1/0},url:lr};ar={type:He.TEMPLATE,baseUrl:_n,segmentTemplateUrl:St,initUrl:dr,totalSegmentsDurationMs:Xt,segments:Pi,nextSegmentBeyondManifest:bu,timescale:_t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Jt||!gt)continue;const nr={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Jt];nr&&ot[nr].push({id:mu,kind:nr,segmentReference:ar,profiles:gu,duration:wt,bitrate:kn,mime:gt,codecs:Ji,width:rr,height:Xi,fps:hu,quality:cu})}}return{dynamic:ru,liveAvailabilityStartTime:au,duration:wt,container:ou,representations:ot}},Ny=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Xs(a):void 0)!==null&&n!==void 0?n:Mt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Fy=({id:i,bitrate:e})=>({id:i,bitrate:e}),Vy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=lt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:lt(i,-1)},Uy=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),nd=i=>"url"in i,ai=i=>i.type===He.TEMPLATE,Ma=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class od{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:c}){switch(this.currentSegmentLength$=new y(0),this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new L,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new mi,this.destroyAbortController=new mi,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.loadByteRangeSegmentsTimeoutId=0,this.startWith=Re(this.destroyAbortController.signal,function(l){return Ce(this,arguments,function*(){const h=this.representations.get(l);P(h,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new mb(this.sourceBuffer),this.subscription.add(D(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(D(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Xo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),v=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(P(f,"No init buffer for starting representation"),P(v,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield M(void 0);this.searchGaps(v,h),yield yield M(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,function(l){return Ce(this,arguments,function*(){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=l;const h=this.representations.get(l);P(h,`No such representation ${l}`);let f=this.segments.get(l),v=this.initData.get(l);if(K(v)||K(f)?yield yield M(this.loadInit(h,"high",!1)):v instanceof Promise&&(yield yield M(v)),f=this.segments.get(l),P(f,"No segments for starting representation"),v=this.initData.get(l),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();_(m)&&(this.isLive||(f.forEach(g=>g.status=V.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,function(l){var h;return Ce(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield M(void 0);for(const E of this.representations.keys()){const A=l.find(q=>q.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!ai(w.segmentReference))return yield M(void 0);const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,v=this.representations.get(f);P(v);const m=this.segments.get(f);P(m,"No segments for starting representation");const g=this.initData.get(f);if(P(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return yield M(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield M(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield M(this.sourceBufferTaskQueue.append(g,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=s,s){case vi.MP4:this.containerParser=Hb;break;case vi.WEBM:this.containerParser=Qb;break;default:H(s)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new mi,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var t,s;if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||this.isSeekingLive)return;const r=this.representations.get(this.downloadingRepresentationId),a=this.segments.get(this.downloadingRepresentationId);if(P(r,`No such representation ${this.downloadingRepresentationId}`),!a)return;const n=a.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next(((t=n==null?void 0:n.time.to)!==null&&t!==void 0?t:0)-((s=n==null?void 0:n.time.from)!==null&&s!==void 0?s:0));let o=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=xi(this.sourceBuffer.buffered,e),f=n?n.time.to+100:-1/0;n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+100&&(o=f)}if(isFinite(this.bufferLimit)&&Xo(this.sourceBuffer.buffered)>=this.bufferLimit){const l=xi(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<h);return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(a,r.segmentReference.type,o),d.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if(d.includes(n))l="high";else{const h=lt(d,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(d,r,l)}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status===V.FED&&!d.length&&xi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=lt(a,-1);c&&c.status===V.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(n===c))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;_(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!ai(n.segmentReference))return;const o=n.segmentReference.segments.map(l=>Object.assign(Object.assign({},l),{status:V.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=lt(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,c=o==null?void 0:o.findIndex(l=>Math.floor(d)>=Math.floor(l.time.from)&&Math.floor(d)<=Math.floor(l.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const l=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,l)}else{const l=o.slice(c+1);this.segments.set(n.id,[...u,...l])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!ai(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=oi(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:V.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:l,time:{from:h,to:f}},v)=>{const m=h<=s&&f>=s,g=h>s||m||v===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(l===V.NONE||l===V.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!Oa(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==He.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(n<=d||o<=c);l++){const h=a[l];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===V.NONE||h.status===V.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){t.segmentReference.type===He.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return te(this,void 0,void 0,function*(){e.status=V.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Re(o,function(){return Ce(this,arguments,function*(){const c=ws(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,c)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const c=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!c)return;const l=new DataView(c);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(l,o),r.segment.status=V.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ma(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=V.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Re(n,function(){return Ce(this,arguments,function*(){const u=ws(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),D(window,"online").pipe(we()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})}))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ma(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ai(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:lt(e,0).byte.from,to:lt(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:s,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ai(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){return te(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(u.status=V.PARTIALLY_FED,o.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const c of this.activeSegments){const{segment:l}=c,h=u===He.BYTE_RANGE,f=h?l.byte.to-l.byte.from+1:d;if(c.representationId!==t||!(!h||l.byte.from>=s&&l.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?l.byte.from-s:0,g=h?l.byte.to-s:e.byteLength,S=m<r,E=g<=r;if(l.status===V.DOWNLOADING&&S&&E){l.status=V.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(f,r-m),c.loadedBytes>c.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+m+c.feedingBytes,c.loadedBytes-c.feedingBytes),w=c.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(l.status=V.PARTIALLY_FED,c.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)c.fedBytes+=w.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=V.FED,nd(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===V.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=V.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===V.PARTIALLY_FED||e.status===V.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=V.NONE),e.status=V.PARTIALLY_EJECTED):e.status=V.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Jo(()=>cn(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return te(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Re(this.destroyAbortController.signal,function(){return Ce(this,arguments,function*(){const o=ws(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>te(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let h=c;this.isLive&&ai(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return te(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var c;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const l=nd(d)?(c=d.size)!==null&&c!==void 0?c:0:d.byte.to-d.byte.from;r+=l};for(const d of this.segments.values())for(const c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===V.FED&&u(c)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===V.FED&&u(c)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===V.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(l)){a=c,n=l;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const l of c)l.time.from>e+d&&l.status===V.FED&&u(l)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Jo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==V.FED&&a!==V.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),d=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1||this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status=V.PARTIALLY_EJECTED:r.status=V.NONE)}}}var Ba=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Hy=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ha.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},hi;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(hi||(hi={}));class Gy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new mi,this.subscription=new re,this.fetchManifest=Re(this.abortAllController.signal,function(r){return Ce(this,arguments,function*(){let a=r;this.requestQuic&&(a=Ba(a));const n=yield yield M(Fi(a,{signal:this.abortAllController.signal}).catch(Ii));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Re(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?hi.HEADER:hi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:c=!0,isLowLatency:l=!1}={}){var h,f;return Ce(this,arguments,function*(){let v=r;const m=new Headers;if(n)switch(a){case hi.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case hi.PARAM:{const x=new URL(v,location.href);x.searchParams.append("bytes",`${n.from}-${n.to}`),v=x.toString();break}default:H(a)}this.requestQuic&&(v=Ba(v));let g=this.abortAllController.signal,S;if(d){const x=new mi;if(S=F(D(this.abortAllController.signal,"abort"),D(d,"abort")).subscribe(()=>{try{x.abort()}catch(ae){Ii(ae)}}),this.abortAllController.signal.aborted||d.aborted)try{x.abort()}catch(ae){Ii(ae)}g=x.signal}const E=le(),A=yield yield M(Fi(v,{priority:u,headers:m,signal:g}).catch(Ii)),w=le();if(!A)return S==null||S.unsubscribe(),yield M(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`)));if(this.onHeadersReceived(A.headers),!o&&!c)return S==null||S.unsubscribe(),yield M(A.arrayBuffer());const[k,q]=A.body.tee(),W=k.getReader();c&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,l));let J=0,j=new Uint8Array(0),X=!1;const ee=x=>{S==null||S.unsubscribe(),X=!0,Ii(x)},B=Re(g,function({done:x,value:ae}){return Ce(this,arguments,function*(){if(J===0&&this.lastRequestFirstBytes$.next(le()-E),g.aborted)return S==null||S.unsubscribe(),yield M(void 0);if(!x&&ae){const N=new Uint8Array(j.length+ae.length);N.set(j),N.set(ae,j.length),j=N,J+=ae.byteLength,o==null||o(new DataView(j.buffer),J),yield yield M(W==null?void 0:W.read().then(B,ee))}})}.bind(this));return yield yield M(W==null?void 0:W.read().then(B,ee)),S==null||S.unsubscribe(),yield M(X?null:j.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,function(r,a,n){var o;return Ce(this,arguments,function*(){if(r.type!==He.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let c=u,l=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(c=Math.min(f,u),l=Math.max(v,d))),c=Math.min(c,0);const m=yield yield M(this.fetch(r.url,{range:{from:c,to:l},priority:n,measureThroughput:!1}));if(!m)return yield M(null);const g=new DataView(m,u-c,d-c+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(m,E.from-c,E.to-E.from+1);else{const k=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!k)return yield M(null);A=new DataView(k)}const w=a.parseSegments(A,S,E);return yield M({init:S,dataView:new DataView(m),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,function(r,a){return Ce(this,arguments,function*(){if(r.type!==He.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:V.NONE,size:void 0}));return yield M({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Hy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return te(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case He.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case He.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:H(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ii=i=>{if(!Ma(i))throw i},di=1e3,Vs=(i,e,t)=>t*e+(1-t)*i,Jl=(i,e)=>i.reduce((t,s)=>t+s,0)/e,jy=(i,e,t,s)=>{let r=0,a=t;const n=Jl(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class Sn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${s}`),this.smoothedSeries$=new tt(`smoothed_${s}`),this.reportedSeries$=new tt(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(K(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 Yy extends Sn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Vs(this.slow,e,this.params.emaAlphaSlow),this.fast=Vs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class qy extends Sn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Jl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Vs(this.emaSmoothed,e,this.params.emaAlpha);const s=jy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Wy extends Sn{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,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?Vs(this.smoothed,e,this.params.emaAlpha):e}}class Na{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Yy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new qy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Wy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const zy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Ct=()=>window.ManagedMediaSource||window.MediaSource,Xl=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Qy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Ky=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,dd=["timeupdate","progress","play","seeked","stalled","waiting"];var Ve;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ve||(Ve={}));let Jy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new he(Ve.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.currentVideoSegmentLength$=new y(0),this.currentAudioSegmentLength$=new y(0),this.error$=new L,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new mi,this.initManifest=Re(this.destroyController.signal,function(t,s,r){var a;return Ce(this,arguments,function*(){this.element=t,this.manifestUrlString=Qe(s,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ve.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Ve.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,function(){var t;return Ce(this,arguments,function*(){const s=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(null);let r;try{r=By(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var d,c,l,h;return!!(!((c=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||c===void 0)&&c.call(d,o)&&(!((h=(l=Ct())===null||l===void 0?void 0:l.isTypeSupported)===null||h===void 0)&&h.call(l,`${o}; codecs="${u}"`))||n===Te.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield M(Object.assign(Object.assign({},r),{representations:Os(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,function(t,s,r){var a;return Ce(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ve.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(D(m,"error").pipe(fe(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:C.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?Ky():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Xl())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new od(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new od(Te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),this.bufferManagers.push(this.audioBufferManager)),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(Ci(di).subscribe(m=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=Yo(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=Qe(this.manifestUrlString,S+di,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(F(...dd.filter(m=>m!=="waiting").map(m=>D(this.element,m))).pipe($(m=>this.element?xi(this.element.buffered,this.element.currentTime*1e3):0),pe(),fe(m=>!!m),Mi(m=>{var g;(g=this.stallWatchdogSubscription)===null||g===void 0||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(fe(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=g-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),zy(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let A=0;if(g){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(q=>{var W,J;return(J=(W=q.getLiveSegmentsToLoadState(this.manifest))===null||W===void 0?void 0:W.to)!==null&&J!==void 0?J:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let m=0;this.representationSubscription.add(Ue({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ku(di)).subscribe(({liveLoadBufferLength:g,bufferLength:S})=>te(this,void 0,void 0,function*(){if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=Yo(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,J=this.isActiveLowLatency?S:g;let j=et.None;if(this.isActiveLowLatency?j=et.ActiveLowLatency:J<k+W&&J>=k?j=et.LiveWithTargetOffset:A!==0&&J<k&&(j=et.LiveForwardBuffering),isFinite(g)&&(m=g>m?g:m),j===et.LiveForwardBuffering||j===et.LiveWithTargetOffset){const X=m-(k+q),ee=this.normolizeLiveOffset(Math.trunc(A+X/E)),B=Math.abs(ee-A);let x;!g||B<=this.tuning.dashCmafLive.offsetCalculationError?x=A:ee>0&&B>this.tuning.dashCmafLive.offsetCalculationError?x=ee:x=0,this.manifestUrlString=Qe(this.manifestUrlString,x,Se.DASH_CMAF_OFFSET_P)}j!==et.None&&j!==et.ActiveLowLatency&&(m=0,this.updateLive())})))}const d=F(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),c=F(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe($(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(F(this.forceEnded$,Ue({allBuffersFull:d,someBufferEnded:c}).pipe(fe(({allBuffersFull:m,someBufferEnded:g})=>m&&g))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(F(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield yield M(new Promise(m=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",m)})));const l=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,g)=>{var S;return Math.max(m,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,l),v=this.manifest.representations.video.reduce(h,l);(f||v)&&(this.source.duration=Math.max(f,v)/1e3),this.audioBufferManager&&_(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Ve.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ci(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Gy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Na.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return te(this,void 0,void 0,function*(){P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=Qe(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))})}initBuffer(){P(this.element),this.state$.setState(Ve.RUNNING),this.subscription.add(F(...dd.map(e=>D(this.element,e)),D(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(D(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(D(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&Oa(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=di,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=Ci(di).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:C.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return te(this,void 0,void 0,function*(){const s={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Oa(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return te(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Xy{constructor(e,t){this.fov=e,this.orientation=t}}class Zy{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var eT=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2
|
|
39
|
-
|
|
33
|
+
[best track] ${D==null?void 0:D.quality}
|
|
34
|
+
[selected track] ${$==null?void 0:$.quality}
|
|
35
|
+
`});let _=$&&l&&l.history[$.id]&&Pm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!_&&l.recordSelection($),_&&(l!=null&&l.last)){let A=l.last;return l==null||l.recordSwitch(A),d({message:`
|
|
36
|
+
[last selected] ${A==null?void 0:A.quality}
|
|
37
|
+
`}),A}return l==null||l.recordSwitch($),$},bt=Aw;var Z=i=>new URL(i).hostname;import{assertNever as $m,assertNonNullable as Cm,combine as Qw,debounce as zw,ErrorCategory as Dm,filter as Kw,filterChanged as Jw,isNonNullable as ru,map as ss,merge as Mm,observableFrom as Xw,Subscription as Zw,ValueSubject as iu,videoQualityToHeight as ek,videoSizeToQuality as tk}from"@vkontakte/videoplayer-shared";var wm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},pe=i=>R(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!wm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return wm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as rs,isNullable as $w,assertNonNullable as oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as km,assertNonNullable as ts,now as Rw}from"@vkontakte/videoplayer-shared";function ee(){return Rw()}function Xo(i){return ee()-i}function Zo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Am(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,v=()=>{if(u)return;ts(c);let w=Xo(c),U;if(w<b){U=b-w,setTimeout(v,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,O()},S=w=>(s=w,L),g=w=>(d=w,L),y=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},I=w=>(p=w,L),O=()=>{c=ee(),n=new a,n.open("get",i);let w=0,U,z=0,A=()=>(ts(c),Math.max(c,Math.max(U||0,z||0)));if(s&&n.addEventListener("progress",x=>{let q=ee();s.updateChunk&&x.loaded>w&&(s.updateChunk(A(),x.loaded-w),w=x.loaded,U=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ts(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let q=n.response.byteLength-w;q&&s.updateChunk&&s.updateChunk(A(),q)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{ts(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=ee(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:w=>(l=w,L),withRetryInterval:(w,U)=>(km(w)&&(b=w),km(U)&&(f=U),L),withTimeout:w=>(o=w,L),withFinally:g,send:O,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}var si=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ni=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var is=1e4,eu=3;var Cw=6e4,Dw=10,Mw=1,Ow=500,ui=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new si(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Zo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||rs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Am(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ni(eu,is,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,I,O)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withTimeout(is).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eu).withFinally(()=>{u=null}).send()},h=(T,I,O)=>{oi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let O=ee()-1e4,D=0;for(let _=0;_<this.bufferStates.length;_++){let H=this.bufferStates[_];T=Math.min(T,H.buf),H.ts<O&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${T} drop=${D} jitter=${this.sourceJitter}`);let $=T-Mw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=T=>{let I,O=()=>I&&I.start?I.start.length:0,D=x=>I.start[x]/1e3,$=x=>I.dur[x]/1e3,_=x=>I.fragIndex+x,H=(x,q)=>({chunkIdx:_(x),startTS:D(x),dur:$(x),discontinuity:q}),L=()=>{let x=0;if(I&&I.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=q;this.sourceJitter>1&&(K+=this.sourceJitter-1);let ie=I.dur.length-1;for(;ie>=0&&(K-=I.dur[ie],!(K<=0));--ie);x=Math.min(ie,I.dur.length-1-Y),x=Math.max(x,0)}return H(x,!0)},w=x=>{let q=O();if(!(q<=0)){if(rs(x)){for(let Y=0;Y<q;Y++)if(D(Y)>x)return H(Y)}return L()}},U=x=>{let q=O(),Y=x?x.chunkIdx+1:0,K=Y-I.fragIndex;if(!(q<=0)){if(!x||K<0||K-q>Dw)return t(`Resync: offset=${K} bChunks=${q} chunk=`+JSON.stringify(x)),L();if(!(K>=q))return H(Y-I.fragIndex,!1)}},z=(x,q,Y)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(x,!0,this.lowLatency),q,Y,()=>this._retryCallback()).withTimeout(is).withRetryCount(eu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,q)=>{z(T,Y=>{if(!d())return;I=Y;let K=!!I.lowLatency;K!==this.lowLatency&&b(K);let ie=0;for(let Ye=0;Ye<I.dur.length;++Ye)ie+=I.dur[Ye];ie>0&&(oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(w(q))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),oi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:I,logger:O}=this.params,D=S(e.jidxUrl),$,_,H,L,w=0,U,z,A,x=()=>{U&&(clearTimeout(U),U=void 0);let N=Math.max(Ow,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=w+N,he=ee(),Se=Math.min(1e4,se-he);w=he;let nt=()=>{l||d()&&D.seek(()=>{d()&&(w=ee(),q(),x())})};Se>0?U=window.setTimeout(()=>{this.paused?x():nt()},Se):nt()},q=()=>{let N;for(;N=D.nextChunk(L);)L=N,Zi(N);let se=D.nextChunk(H);if(se){if(H&&se.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}Ye(se)}else x()},Y=(N,se)=>{if(!d()||!this.sourceBuffer)return;let he,Se,nt,Jt=ot=>{window.setTimeout(()=>{d()&&Y(N,se)},ot)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ot=ee(),Et=I.currentTime;!this.paused&&I.buffered.length>1&&z===Et&&ot-A>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),z!==Et&&(z=Et,A=ot);let Xt=this._getBufferSizeSec();if(Xt>30)O(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Xt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(Cr){if(Cr.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),nt=this.sourceBuffer.buffered.length,nt!==0&&(he=this.sourceBuffer.buffered.start(0),Se=Et,Se-he>4&&this.sourceBuffer.remove(he,Se-3)),Jt(1e3);else throw Cr}}},K=()=>{_&&$&&(O([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(H)]),Y(_,function(){_=null,q()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),Ye=N=>{d()&&h(ie(N),(se,he)=>{if(d()){if(he/=1e3,_=se,H=N,n=N.startTS,he){let Se=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}K()}},()=>this._handleNetworkError())},Zi=N=>{d()&&(oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},$r=N=>{d()&&(e.cachedHeader=N,Y(N,()=>{$=!0,K()}))};s=!0,D.seek(N=>{if(d()){if(w=ee(),!N){x();return}L=N,!$w(T)||N.startTS>T?Ye(N):(H=N,q())}},T),e.cachedHeader?$r(e.cachedHeader):p(e.headerUrl,$r,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),rs(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Xo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(is).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;pe(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Cw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Bw,filter as Rm,fromEvent as Vw,interval as _w,isHigher as Nw,isInvariantQuality as Fw,isLower as qw,merge as Uw,Subject as Lm,Subscription as Hw}from"@vkontakte/videoplayer-shared";var tu=class{constructor(){this.onDroopedVideoFramesLimit$=new Lm;this.subscription=new Hw;this.playing=!1;this.tracks=[];this.forceChecker$=new Lm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Fw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Nw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Vw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_w(this.droppedFramesChecker.checkTime).pipe(Rm(()=>this.playing),Rm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Bw(this.droppedFramesChecker.checkTime)),r=Uw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>qw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},as=tu;import{map as jw,Observable as Gw}from"@vkontakte/videoplayer-shared";import{fromEvent as Yw}from"@vkontakte/videoplayer-shared";var li=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Ww=(i,e)=>new Gw(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||li()))},k(k({},r),e));a.observe(i);let s=Yw(document,"visibilitychange").pipe(jw(n=>!document.hidden||li())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=Ww;var rk=["paused","playing","ready"],ik=["paused","playing","ready"],ci=class{constructor(e){this.subscription=new Zw;this.videoState=new C("stopped");this.representations$=new iu([]);this.textTracksManager=new Ee;this.droppedFramesManager=new as;this.maxSeekBackTime$=new iu(1/0);this.zeroTime$=new iu(void 0);this.liveOffset=new Je;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Dm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=ft(u.name))!=null?r:tk(u.video),d=u.bitrate/1e3,p=k({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),ru(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ik.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&rk.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(re(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a==null?void 0:a.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(re(this.params.source.url,u))}return;default:return $m(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Dm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Mm(this.videoState.stateChangeStarted$.pipe(ss(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ss(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ue(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=de(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(ss(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Jw(),ss(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(Qw({zeroTime:this.zeroTime$.pipe(Kw(ru)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(He(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&ek(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return $m(a.to)}},t)).add(Mm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Xw(["init"])).pipe(zw(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),le(this.video)}createLiveDashPlayer(){let e=new ui({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&ru(t)?t:bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.representation;Cm(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;Cm(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(re(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Om=ci;var gt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as IA,assertNonNullable as zb,debounce as EA,ErrorCategory as wu,filter as xA,filterChanged as Kb,fromEvent as PA,isLowerOrEqual as Jb,isNonNullable as wA,videoSizeToQuality as Xb,map as ku,merge as vs,observableFrom as kA,observeElementSize as AA,once as RA,Subscription as LA,ValueSubject as Zb}from"@vkontakte/videoplayer-shared";var ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},yr=class extends ns{constructor(){super(),this.listeners||ns.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},di=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(di.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function os(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function au(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!os({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var pi=os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Bm=pi?au({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=pi?Bm.fetch:window.fetch,F0=pi?Bm.Request:window.Request,et=pi?di:window.AbortController,q0=pi?yr:window.AbortSignal;var Yb=Fe(_a(),1);var hi=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Eu,assertNonNullable as Yt,combine as qb,ErrorCategory as St,filter as hs,filterChanged as mA,fromEvent as kr,interval as xu,isNonNullable as Ub,map as Pu,merge as Ar,Subject as Hb,Subscription as jb,tap as bA,throttle as gA,ValueSubject as ge}from"@vkontakte/videoplayer-shared";var wr=Fe(Za(),1);var ak=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},sk=i=>window.clearTimeout(i),Vm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",su=Vm?ak:window.requestIdleCallback,j0=Vm?sk:window.cancelIdleCallback;var Cb=Fe(Ka(),1);import{assertNever as nk,CurrentClientBrowser as ok,ErrorCategory as _m,getCurrentBrowser as uk,Subject as Nm}from"@vkontakte/videoplayer-shared";var lk=16,Um=!1,Fm,qm;try{Um=uk().browser===ok.Safari&&parseInt((qm=(Fm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Fm[1])!=null?qm:"",10)<=lk}catch(i){console.error(i)}var nu=class{constructor(e){this.bufferFull$=new Nm;this.error$=new Nm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:_m.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})})}remove(e,t,r){return R(this,null,function*(){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Um&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:_m.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:nk(t)}}},Hm=nu;var ou=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as xr,assertNever as oA,assertNonNullable as tt,ErrorCategory as Pr,fromEvent as vu,getExponentialDelay as Su,once as uA,isNonNullable as $b,isNullable as rt,Subject as lA,Subscription as cA,ValueSubject as Oi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Tr=class extends F{};var fi=class extends F{};var mi=class extends F{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var bi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends F{constructor(t,r){super(t,r);this.data=this.content}};var W=class extends F{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Nt=class extends W{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Si=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends W{constructor(t,r){super(t,r);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ii=class extends W{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ei=class extends W{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var xi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends W{constructor(t,r){super(t,r);this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var wi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends W{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends W{constructor(t,r){super(t,r);this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var $i=class extends W{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ci=class extends W{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var dk={ftyp:mi,moov:bi,moof:gi,mdat:vi,sidx:Nt,trak:Si,mdia:xi,mfhd:Ai,tkhd:Pi,traf:Ri,tfhd:Li,tfdt:$i,trun:Ci,minf:wi,sv3d:yi,st3d:Ti,prhd:Ii,proj:ki,equi:Ei,uuid:fi,unknown:Tr},Ft=class i{constructor(e={}){this.options=k({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(a){break}return t}createBox(e,t){let r=dk[e];return r?new r(t,new i):new Tr(t,new i)}};var Ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var hk=new TextDecoder("ascii"),fk=i=>hk.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",mk=i=>{let e=new Nt(i,new Ft),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},bk=(i,e)=>{let r=new Ft().parse(i),a=new Ir(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},gk=(i,e)=>{let r=new Ft().parse(i),s=new Ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},vk=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Ft().parse(i),a=new Ir(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},jm={validateData:fk,parseInit:vk,getIndexRange:()=>{},parseSegments:mk,parseFeedableSegmentChunk:bk,getSegmentEndTime:gk};import{assertNonNullable as lu,isNonNullable as Qm,isNullable as yk}from"@vkontakte/videoplayer-shared";import{assertNever as Sk}from"@vkontakte/videoplayer-shared";var Gm={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"}},Ym=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Di(i,t),a=r in Gm,s=a?Gm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Di(u),d=l*Ne(2,(o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Di=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Ne(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Ne(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Ne(2,32)+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Oe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Di(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:Sk(e)}},qt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Ym(r);if(!e(a))return;a.type==="master"&&qt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Ym(i);return qt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Oe(o,n):s===17026?t=Oe(o,n):s===17029&&(r=Oe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Tk=[231,22612,22743,167,171,163,160,175],Ik=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return qt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let v=Oe(f,h);l=Di(v)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Oe(f,h):p===17545?a=Oe(f,h):p===21420&&l===475249515?u=Oe(f,h):p===374648427?qt(f,({tag:v,type:S,value:g})=>v===30321?(c=Oe(g,S)===1,!1):!0):s&&n&&zm.includes(p)&&(o=!0),!o}),lu(e,"Failed to parse webm Segment start"),lu(t,"Failed to parse webm Segment end"),lu(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ek=i=>{if(yk(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},xk=(i,e)=>{let t=!1,r=!1,a=o=>Qm(o.time)&&Qm(o.position),s=[],n;return qt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Oe(l,u));break;case 183:break;case 241:n&&(n.position=Oe(l,u));break;default:t&&zm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Pk=i=>{let e=0,t=!1;try{qt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Tk.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Km={validateData:Wm,parseInit:Ik,getIndexRange:Ek,parseSegments:xk,parseFeedableSegmentChunk:Pk};var fu=Fe(yb(),1);import{isNonNullable as Ib,isNullable as Eb}from"@vkontakte/videoplayer-shared";var Tb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var xb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ut=(i,e)=>{let t=i;t=(0,fu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,fu.default)(t,n,(o,u)=>Eb(s)?o:Eb(u)?s:s.padStart(parseInt(u,10),"0"))}return t},wb=(i,e)=>{var T,I,O,D,$,_,H,L,w,U,z,A,x,q,Y,K,ie,Ye,Zi,$r,N,se,he,Se,nt,Jt,ot,Et,Xt,Cr,Hu,ju,Gu,Yu,Wu,Qu,zu,Ku,Ju,Xu,Zu,el;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(O=(I=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:I.trim())!=null?O:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=xb(h);else if(f){let ye=xb(f);Ib(ye)&&(p=ye)}else v&&(p=parseInt(v,10));let S=0,g=($=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?$:[],y=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let ye of u){let ea=ye.getAttribute("mimeType"),tv=ye.getAttribute("codecs"),tl=(_=ye.getAttribute("contentType"))!=null?_:ea==null?void 0:ea.split("/")[0],rv=(L=(H=ye.getAttribute("profiles"))==null?void 0:H.split(","))!=null?L:[],rl=ye.querySelectorAll("Representation"),iv=ye.querySelector("SegmentTemplate");if(tl==="text"){for(let Q of rl){let ut=Q.getAttribute("id")||"",ta=ye.getAttribute("lang"),Zt=ye.getAttribute("label"),Ns=(z=(U=(w=Q.querySelector("BaseURL"))==null?void 0:w.textContent)==null?void 0:U.trim())!=null?z:"",Fs=new URL(Ns||o,e).toString(),ra=ut.includes("_auto");a.text.push({id:ut,lang:ta,label:Zt,isAuto:ra,kind:"text",url:Fs})}continue}for(let Q of rl){let ut=(A=Q.getAttribute("mimeType"))!=null?A:ea,ta=(q=(x=Q.getAttribute("codecs"))!=null?x:tv)!=null?q:"",Zt=(K=(Y=Q.getAttribute("contentType"))!=null?Y:ut==null?void 0:ut.split("/")[0])!=null?K:tl,Ns=(Ye=(ie=ye.getAttribute("profiles"))==null?void 0:ie.split(","))!=null?Ye:[],Fs=parseInt((Zi=Q.getAttribute("width"))!=null?Zi:"",10),ra=parseInt(($r=Q.getAttribute("height"))!=null?$r:"",10),il=parseInt((N=Q.getAttribute("bandwidth"))!=null?N:"",10)/1e3,al=(se=Q.getAttribute("frameRate"))!=null?se:"",av=(he=Q.getAttribute("quality"))!=null?he:void 0,sv=al?Tb(al):void 0,nv=(Se=Q.getAttribute("id"))!=null?Se:(S++).toString(10),ov=Zt==="video"?`${ra}p`:Zt==="audio"?`${il}Kbps`:ta,uv=`${nv}@${ov}`,lv=(ot=(Jt=(nt=Q.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:Jt.trim())!=null?ot:"",sl=new URL(lv||o,e).toString(),cv=[...g,...rv,...Ns],qs,dv=Q.querySelector("SegmentBase"),xt=(Et=Q.querySelector("SegmentTemplate"))!=null?Et:iv;if(dv){let Pt=(Cr=(Xt=Q.querySelector("SegmentBase Initialization"))==null?void 0:Xt.getAttribute("range"))!=null?Cr:"",[wt,Hs]=Pt.split("-").map(er=>parseInt(er,10)),lt={from:wt,to:Hs},Dr=(Hu=Q.querySelector("SegmentBase"))==null?void 0:Hu.getAttribute("indexRange"),[js,ia]=Dr?Dr.split("-").map(er=>parseInt(er,10)):[],Mr=Dr?{from:js,to:ia}:void 0;qs={type:"byteRange",url:sl,initRange:lt,indexRange:Mr}}else if(xt){let Pt={representationId:(ju=Q.getAttribute("id"))!=null?ju:void 0,bandwidth:(Gu=Q.getAttribute("bandwidth"))!=null?Gu:void 0},wt=parseInt((Yu=xt.getAttribute("timescale"))!=null?Yu:"",10),Hs=(Wu=xt.getAttribute("initialization"))!=null?Wu:"",lt=xt.getAttribute("media"),Dr=(zu=parseInt((Qu=xt.getAttribute("startNumber"))!=null?Qu:"",10))!=null?zu:1,js=Ut(Hs,Pt);if(!lt)throw new ReferenceError("No media attribute in SegmentTemplate");let ia=(Ku=xt.querySelectorAll("SegmentTimeline S"))!=null?Ku:[],Mr=[],er=0,Gs="",Ys=0;if(ia.length){let aa=Dr,Re=0;for(let tr of ia){let _e=parseInt((Ju=tr.getAttribute("d"))!=null?Ju:"",10),kt=parseInt((Xu=tr.getAttribute("r"))!=null?Xu:"",10)||0,sa=parseInt((Zu=tr.getAttribute("t"))!=null?Zu:"",10);Re=Number.isFinite(sa)?sa:Re;let Ws=_e/wt*1e3,Qs=Re/wt*1e3;for(let na=0;na<kt+1;na++){let hv=Ut(lt,B(k({},Pt),{segmentNumber:aa.toString(10),segmentTime:(Re+na*_e).toString(10)})),nl=(Qs!=null?Qs:0)+na*Ws,fv=nl+Ws;aa++,Mr.push({time:{from:nl,to:fv},url:hv})}Re+=(kt+1)*_e,er+=(kt+1)*Ws}Ys=Re/wt*1e3,Gs=Ut(lt,B(k({},Pt),{segmentNumber:aa.toString(10),segmentTime:Re.toString(10)}))}else if(Ib(p)){let Re=parseInt((el=xt.getAttribute("duration"))!=null?el:"",10)/wt*1e3,tr=Math.ceil(p/Re),_e=0;for(let kt=1;kt<tr;kt++){let sa=Ut(lt,B(k({},Pt),{segmentNumber:kt.toString(10),segmentTime:_e.toString(10)}));Mr.push({time:{from:_e,to:_e+Re},url:sa}),_e+=Re}Ys=_e,Gs=Ut(lt,B(k({},Pt),{segmentNumber:tr.toString(10),segmentTime:_e.toString(10)}))}let pv={time:{from:Ys,to:1/0},url:Gs};qs={type:"template",baseUrl:sl,segmentTemplateUrl:lt,initUrl:js,totalSegmentsDurationMs:er,segments:Mr,nextSegmentBeyondManifest:pv,timescale:wt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Zt||!ut)continue;let Us={video:"video",audio:"audio",text:"text"}[Zt];Us&&a[Us].push({id:uv,kind:Us,segmentReference:qs,profiles:cv,duration:p,bitrate:il,mime:ut,codecs:ta,width:Fs,height:ra,fps:sv,quality:av})}}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,container:y,representations:a}};var bu=Fe(Za(),1);import{videoSizeToQuality as nA}from"@vkontakte/videoplayer-shared";var kb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?ft(s):void 0)!=null?o:nA({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Ab=({id:i,bitrate:e})=>({id:i,bitrate:e}),Rb=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,bu.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,bu.default)(i,-1)},Lb=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),gu=i=>"url"in i,Ht=i=>i.type==="template",Mi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Bi=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:c}){this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new lA;this.gaps=[];this.subscription=new cA;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new et;this.destroyAbortController=new et;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){let t=this.representations.get(e);tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hm(this.sourceBuffer),this.subscription.add(vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:Pr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,ou(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);tt(r,"No init buffer for starting representation"),tt(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);tt(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(rt(a)||rt(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),tt(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();$b(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))})}.bind(this));this.seekLive=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let l=e.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ht(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);tt(r);let a=this.segments.get(t);tt(a,"No segments for starting representation");let s=this.initData.get(t);if(tt(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=jm;break;case"webm":this.containerParser=Km;break;default:oA(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(rt(e)||rt(this.downloadingRepresentationId)||rt(this.playingRepresentationId)||rt(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(tt(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=gt(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&ou(this.sourceBuffer.buffered)>=this.bufferLimit){let d=gt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,wr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&>(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,wr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;$b(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!Ht(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>B(k({},d),{status:"none",size:void 0})),u=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=(0,wr.default)(u,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(l)>=Math.floor(d.time.from)&&Math.floor(l)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...u,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Ht(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Ut(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,v=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!hi(this.sourceBuffer.buffered,r))&&v&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield xr(o,function(){return J(this,null,function*(){let c=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Mi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield xr(n,function(){return J(this,null,function*(){let u=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),vu(window,"online").pipe(uA()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Mi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Ht(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,wr.default)(e,0).byte.from,to:(0,wr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ht(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){a();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(y,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",gu(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=su(()=>(0,Cb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?xr(this.destroyAbortController.signal,function(){return J(this,null,function*(){let o=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ht(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Pr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||rt(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=gu(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=su(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Pr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(rt(this.sourceBuffer)||rt(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Vi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Db=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};import{abortable as _i,assertNever as Mb,fromEvent as Ob,merge as dA,now as yu,Subscription as pA,ValueSubject as Tu}from"@vkontakte/videoplayer-shared";var us=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Tu(void 0);this.lastConnectionReused$=new Tu(void 0);this.lastRequestFirstBytes$=new Tu(void 0);this.abortAllController=new et;this.subscription=new pA;this.fetchManifest=_i(this.abortAllController.signal,function(e){return J(this,null,function*(){let t=e;this.requestQuic&&(t=Vi(t));let r=yield Ze(t,{signal:this.abortAllController.signal}).catch(Ni);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=_i(this.abortAllController.signal,function(l){return J(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,H;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Mb(t)}this.requestQuic&&(c=Vi(c));let p=this.abortAllController.signal,h;if(n){let L=new et;if(h=dA(Ob(this.abortAllController.signal,"abort"),Ob(n,"abort")).subscribe(()=>{try{L.abort()}catch(w){Ni(w)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(w){Ni(w)}p=L.signal}let f=yu(),b=yield Ze(c,{priority:s,headers:d,signal:p}).catch(Ni),v=yu();if(!b)return h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,g]=b.body.tee(),y=S.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(g,u));let T=0,I=new Uint8Array(0),O=!1,D=L=>{h==null||h.unsubscribe(),O=!0,Ni(L)},$=_i(p,function(U){return J(this,arguments,function*({done:L,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(yu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&w){let z=new Uint8Array(I.length+w.length);z.set(I),z.set(w,I.length),I=z,T+=w.byteLength,a==null||a(new DataView(I.buffer),T),yield y==null?void 0:y.read().then($,D)}})}.bind(this));return yield y==null?void 0:y.read().then($,D),h==null||h.unsubscribe(),O?null:I.buffer})}.bind(this));this.fetchByteRangeRepresentation=_i(this.abortAllController.signal,function(e,t,r){return J(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=_i(this.abortAllController.signal,function(e,t){return J(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>B(k({},n),{status:"none",size:void 0})),dataView:new DataView(a)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=Db(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Mb(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ni=i=>{if(!Mi(i))throw i};var jt=(i,e,t)=>t*e+(1-t)*i,Iu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Bb=(i,e,t,r)=>{let a=0,s=t,n=Iu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as hA,ValueSubject as Vb}from"@vkontakte/videoplayer-shared";var vt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Vb(e.initial),this.debounced$=new Vb(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ae(`raw_${t}`),this.smoothedSeries$=new ae(`smoothed_${t}`),this.reportedSeries$=new ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ne(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(hA(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ls=class extends vt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=jt(this.slow,t,this.params.emaAlphaSlow),this.fast=jt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var cs=class extends vt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Iu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jt(this.emaSmoothed,t,this.params.emaAlpha);let a=Bb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ds=class extends vt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?jt(this.smoothed,t,this.params.emaAlpha):t}};var Gt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ls({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new cs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ds(k({initial:e,label:"liveEdgeDelay"},t))}};var _b=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var it=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Nb=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Fb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Gb=["timeupdate","progress","play","seeked","stalled","waiting"];var fs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new jb;this.representationSubscription=new jb;this.state$=new C("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new Hb;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.isLive$=new ge(!1);this.liveDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Hb;this.gapWatchdogActive=!1;this.destroyController=new et;this.initManifest=Eu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var a;this.element=e,this.manifestUrlString=re(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Eu(this.destroyController.signal,function(){return J(this,null,function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=wb(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var u,l,c,d;return!!((l=(u=this.element)==null?void 0:u.canPlayType)!=null&&l.call(u,n)&&((d=(c=it())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),B(k({},t),{representations:(0,Yb.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))})})}.bind(this));this.initRepresentations=Eu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var h;Yt(this.manifest),Yt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=f=>{this.representationSubscription.add(kr(f,"error").pipe(hs(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?Fb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(r){let f=document.createElement("source");a(f),f.type="application/x-mpegurl",f.src=r.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Bi("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Ub(t)&&(this.audioBufferManager=new Bi("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),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(xu(1e3).subscribe(f=>{var b;if((b=this.element)!=null&&b.paused){let v=Fo(this.manifestUrlString,2);this.manifestUrlString=re(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(Ar(...Gb.filter(f=>f!=="waiting").map(f=>kr(this.element,f))).pipe(Pu(f=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),mA(),hs(f=>!!f),bA(f=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(hs(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-v,T=1+Math.sign(y)*g;Math.abs(y)<S?T=1:Math.abs(y)>S*2&&(T=1+Math.sign(y)*g*2),_b(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(I=>{var O,D;return(D=(O=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:O.to)!=null?D:y}))-y}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let f=0;this.representationSubscription.add(qb({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gA(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:b,bufferLength:v}){if(Yt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=Fo(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=this.isActiveLowLatency?v:b,_=3;if(this.isActiveLowLatency?_=0:$<I+D&&$>=I?_=1:y!==0&&$<I&&(_=2),isFinite(b)&&(f=b>f?b:f),_===2||_===1){let H=f-(I+O),L=this.normolizeLiveOffset(Math.trunc(y+H/g)),w=Math.abs(L-y),U;!b||w<=this.tuning.dashCmafLive.offsetCalculationError?U=y:L>0&&w>this.tuning.dashCmafLive.offsetCalculationError?U=L:U=0,this.manifestUrlString=re(this.manifestUrlString,U,2)}_!==3&&_!==0&&(f=0,this.updateLive())})))}let o=Ar(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(Pu(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),u=Ar(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(Pu(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(Ar(this.forceEnded$,qb({allBuffersFull:o,someBufferEnded:u}).pipe(hs(({allBuffersFull:f,someBufferEnded:b})=>f&&b))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(f=this.source)==null||f.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(Ar(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",f)}));let l=(h=this.manifest.duration)!=null?h:0,c=(f,b)=>{var v;return Math.max(f,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,l),p=this.manifest.representations.video.reduce(c,l);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&Ub(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=xu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new us({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return R(this,null,function*(){var r,a,s,n;Yt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=re(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio))})}initBuffer(){Yt(this.element),this.state$.setState("running"),this.subscription.add(Ar(...Gb.map(e=>kr(this.element,e)),kr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(kr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(kr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&hi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=xu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return R(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var a,s,n,o,u;Yt(this.element),Yt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),hi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ms=class{constructor(e,t){this.fov=e,this.orientation=t}};var bs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Ne(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=k({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*Ne(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Wb=`attribute vec2 a_vertex;
|
|
38
|
+
attribute vec2 a_texel;
|
|
39
|
+
|
|
40
|
+
varying vec2 v_texel;
|
|
41
|
+
|
|
42
|
+
void main(void) {
|
|
43
|
+
// direct vertex drawing
|
|
44
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
45
|
+
// save texel vector to pass to fragment shader
|
|
46
|
+
v_texel = a_texel;
|
|
47
|
+
}
|
|
48
|
+
`;var Qb=`#ifdef GL_ES
|
|
49
|
+
precision highp float;
|
|
50
|
+
precision highp int;
|
|
40
51
|
#else
|
|
41
|
-
precision highp float;
|
|
42
|
-
#define GLSLIFY 1
|
|
52
|
+
precision highp float;
|
|
43
53
|
#endif
|
|
54
|
+
|
|
44
55
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class iT{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Xy(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zy(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(eT,this.gl.VERTEX_SHADER),s=this.createShader(tT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,c=t+r,l=e-s,h=t+r;return[a,n,o,u,d,c,l,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Zl{constructor(e){this.subscription=new re,this.videoState=new he(de.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new At,this.droppedFramesManager=new Vl,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new QS,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==de.STOPPED&&n!==p.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-c,u.forcePrecise)}if(n===p.STOPPED){a!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case de.STOPPED:this.videoState.startTransitionTo(de.READY),this.prepare();return;case de.READY:n===p.PAUSED?(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new iT(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.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});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Gt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(at(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Jy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=qt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:C.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe($(d=>d.map(({track:c})=>c)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(fe(_),we()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Qi(this.video,t.isLooped,r)),this.subscription.add(Yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ti(this.video,t.playbackRate,s.playbackRateState$,r)),a(Pu(this.video),this.elementSize$),a(Ei(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var c;if(d===Ve.MANIFEST_READY){const l=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=Fy(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of v){const E=Ny(S);if(E){l.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&Vy(f,v,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(l);for(const S of m){const E=Uy(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(l.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();P(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))===null||c===void 0?void 0:c.id,this.params.sourceHls)}else d===Ve.REPRESENTATIOS_READY&&(this.videoState.setState(de.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(F(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,D(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!==Ve.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(l){let m=l.id;!this.params.output.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=Mt(S),A=Mt(l);if(E&&A)return Cs(E,A)&&Cs(E,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(Te.VIDEO,m).catch(n);const g=this.audioRepresentations.get(l.id);g&&this.player.switchRepresentation(Te.AUDIO,g.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),$(d=>{var c;return d&&((c=this.videoTracks$.getValue().find(({representation:{id:l}})=>l===d))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var c,l;if(d!=null&&d.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===p.READY),pe());this.subscription.add(F(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(F(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,l=this.params.output.currentVideoTrack$.getValue(),h=xi(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(c&&!u&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,l&&(n=(a=this.audioRepresentations.get(l.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),g=Zs(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:c:c!=null?c:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Wt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),jt(this.video)}}class sT extends Zl{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class rT extends Zl{constructor(e){super(e),this.liveOffset=new fn}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ue({interval:Ci(di),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===de.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ue({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===de.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const We={};var z;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const ni=(i,e)=>new Va(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class aT{constructor(e){this.subscription=new re,this.videoState=new he(z.INITIALIZING),this.textTracksManager=new At,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==z.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case z.PLAYING:this.pause();break;default:H(t)}break;default:H(s)}},this.video=Gt(e.container),this.params=e,this.params.output.element$.next(this.video),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(at(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),jt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);cn(import("hls.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){P(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=qt(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Qi(this.video,e.isLooped,s)),this.subscription.add(Yt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ti(this.video,e.playbackRate,r.playbackRateState$,s)),a(Ei(this.video),t.elementVisible$),this.subscription.add(ni(this.hls,We.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)===null||c===void 0?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),a(ni(this.hls,We.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((c,l)=>{var h,f;const v=l.name||l.height.toString(10),{width:m,height:g}=l,S=(f=Xs((h=l.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Mt({width:m,height:g});if(!S)return c;const E=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,A={id:v.toString(),quality:S,bitrate:l.bitrate/1e3,size:{width:m,height:g},fps:E};return this.trackLevels.set(v,{track:A,level:l}),c.push(A),c},[]))),t.availableVideoTracks$),a(ni(this.hls,We.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const c=[];for(const l of d.subtitleTracks){const h=l.name,f=l.attrs.URI||"",v=l.lang,m="internal";c.push({id:h,url:f,language:v,type:m})}e.internalTextTracks.startTransitionTo(c)}}),a(ni(this.hls,We.Events.LEVEL_LOADING).pipe($(({url:d})=>at(d))),t.hostname$),a(ni(this.hls,We.Events.FRAG_CHANGED),d=>{var c,l,h,f;const{video:v,audio:m}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((c=v==null?void 0:v.endPTS)!==null&&c!==void 0?c:0)-((l=v==null?void 0:v.startPTS)!==null&&l!==void 0?l:0))*1e3),t.currentAudioSegmentLength$.next((((h=m==null?void 0:m.endPTS)!==null&&h!==void 0?h:0)-((f=m==null?void 0:m.startPTS)!==null&&f!==void 0?f:0))*1e3)}),this.subscription.add(ut(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))===null||c===void 0?void 0:c.track},o=ni(this.hls,We.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(fe(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(ut(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var c;if(K(d))return;const l=(c=this.trackLevels.get(d.id))===null||c===void 0?void 0:c.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,v=this.hls.levels[f];!v||l.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=F(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return te(this,void 0,void 0,function*(){this.videoState.startTransitionTo(z.PLAYING),(yield Wt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:t})))||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const ld="X-Playback-Duration";var ud=i=>te(void 0,void 0,void 0,function*(){var e;const t=yield Fi(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(ld)?parseInt(t.headers.get(ld),10):void 0});const nT=i=>{let e=null;if(i.QUALITY&&(e=Xs(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Mt({width:t,height:s})}return e!=null?e:null},oT=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!c)){if(d){const l=Os(d[1].split(",").map(E=>E.split("="))),h=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,f=nT(l);let v;l.BANDWIDTH&&(v=parseInt(l.BANDWIDTH,10)/1e3||void 0),!v&&l["AVERAGE-BANDWIDTH"]&&(v=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[E,A]=l.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(g={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:v,size:g,fps:m})}if(c){const l=Os(c[1].split(",").map(m=>m.split("=")).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(s=l.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=l.LANGUAGE,v=l.NAME;h&&f&&n.push({type:"internal",id:f,label:v,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},dT=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Zr=0;const bn=(i,e=i,t)=>te(void 0,void 0,void 0,function*(){const r=yield(yield Fi(i)).text();Zr+=1;try{const{qualityManifests:a,textTracks:n}=oT(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(Zr<=t.manifestRetryMaxCount)return yield dT(ws(Zr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),bn(i,e,t)}return{qualityManifests:[],textTracks:[]}});var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class lT{constructor(e){var t;this.subscription=new re,this.videoState=new he(ie.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.liveOffset=new fn,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=Gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:De.INVARIANT,url:this.params.source.url},bn(Qe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:C.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(at(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const l=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),c.find(h=>h.id===l)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=qt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),a(Ei(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(at(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const c=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(c||void 0)},s)),this.subscription.add(Ue({startTime:this.manifestStartTime$.pipe(fe(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s));const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),jt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[l,h]of[[d,"mq"],[c,"lq"]]){const f=String(parseFloat(l||""));h&&l&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=Qe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),ud(u).then(d=>{var c;if(!K(d))this.maxSeekBackTime$.next(d);else{const l=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(K(l)||!isFinite(l))try{Fi(u).then(h=>h.text()).then(h=>{var f;const v=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(v){const m=new URL(v,u).toString();ud(m).then(g=>{K(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ne||(ne={}));class uT{constructor(e){this.subscription=new re,this.videoState=new he(ne.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o||u){const l=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),s){case ne.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return H(s)}},this.params=e,this.video=Gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:De.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(at(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),bn(Qe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const l=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),c.find(h=>h.id===l)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=qt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Qi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&_(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(v=>v.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(at(f.url));const v=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(v!==m){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(v),g.playbackRate=v)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===ne.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s)),!_u()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(F(D(o,"addtrack"),D(o,"removetrack"),D(o,"change"),Ge(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),jt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,c]of[[o,"mq"],[u,"lq"]]){const l=String(parseFloat(d||""));c&&d&&n.searchParams.set(c,l)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ce||(ce={}));class cT{constructor(e){this.subscription=new re,this.videoState=new he(ce.STOPPED),this.trackUrls={},this.textTracksManager=new At,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(d&&a!==ce.READY&&!c){this.handleQualityLimitTransition(d.to.max);return}if(a===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(c){const{currentTime:h}=this.video;this.prepare(),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[c.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&l.state===Y.Requested&&this.seek(l.position),a){case ce.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=Gt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=qt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Qi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),a(Ei(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&_(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const c=this.params.desiredState.playbackRate.getState(),l=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(c!==l){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),jt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Ba(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(at(s))}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(s=Object.values(this.trackUrls).find(l=>!Bt(l.track.quality)&&Cs(l.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&c&&ca(c.quality,u.quality)&&(n=u),!n){const l=Object.values(this.trackUrls).filter(f=>!Bt(f.track.quality)&&fi(f.track.quality,e)),h=l.length;h&&(n=l[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=Zs(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const cd=["stun:videostun.mycdn.me:80"],hT=1e3,fT=3,ea=()=>null;class pT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ea,this.externalStopCallback=ea,this.externalErrorCallback=ea,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return te(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return te(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:cd}]};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);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return te(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return te(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C.WTF,message:e.message})}onPeerConnectionStream(e){return te(this,void 0,void 0,function*(){const 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){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return te(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),hT)}normalizeOptions(e={}){const t={stunServerList:cd,maxRetryNumber:fT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class mT{constructor(e){this.videoState=new he(se.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:s===p.PAUSED?(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Gt(e.container),this.liveStreamClient=new pT(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),jt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};F(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=qt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ei(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Yt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},s)).add(F(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(rt(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(at(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:De.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.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.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class hd{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var Pe;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(Pe||(Pe={}));var yt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(yt||(yt={}));var ta,ia,sa,ra,Ss,aa,bs,na,ys,oa,Ts,da,Es,la,$s,ua;const eu=Fa().device===Iu.Android,Tt=document.createElement("video"),vT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gT='video/mp4; codecs="hev1.1.6.L93.B0"',tu='video/webm; codecs="vp09.00.10.08"',iu='video/webm; codecs="av01.0.00M.08"',ST='audio/mp4; codecs="mp4a.40.2"',bT='audio/webm; codecs="opus"',Lt={mms:Xl(),mse:Qy(),hls:!!(!((ta=Tt.canPlayType)===null||ta===void 0)&&ta.call(Tt,"application/x-mpegurl")||!((ia=Tt.canPlayType)===null||ia===void 0)&&ia.call(Tt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Fe={mp4:!!(!((sa=Tt.canPlayType)===null||sa===void 0)&&sa.call(Tt,"video/mp4")),webm:!!(!((ra=Tt.canPlayType)===null||ra===void 0)&&ra.call(Tt,"video/webm")),cmaf:!0},st={h264:!!(!((aa=(Ss=Ct())===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||aa===void 0)&&aa.call(Ss,vT)),h265:!!(!((na=(bs=Ct())===null||bs===void 0?void 0:bs.isTypeSupported)===null||na===void 0)&&na.call(bs,gT)),vp9:!!(!((oa=(ys=Ct())===null||ys===void 0?void 0:ys.isTypeSupported)===null||oa===void 0)&&oa.call(ys,tu)),av1:!!(!((da=(Ts=Ct())===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||da===void 0)&&da.call(Ts,iu)),aac:!!(!((la=(Es=Ct())===null||Es===void 0?void 0:Es.isTypeSupported)===null||la===void 0)&&la.call(Es,ST)),opus:!!(!((ua=($s=Ct())===null||$s===void 0?void 0:$s.isTypeSupported)===null||ua===void 0)&&ua.call($s,bT))},Ri=(st.h264||st.h265)&&st.aac;let Dt;const yT=()=>te(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:iu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:tu})}))]);Dt={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}});try{yT()}catch(i){console.error(i)}const Vi=Lt.hls&&Fe.mp4,TT=()=>Object.keys(st).filter(i=>st[i]),ET=(i,e=!1,t=!1)=>{const s=Lt.mse||Lt.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&Fe.mp4&&Ri;case b.DASH_WEBM:return s&&Fe.webm&&st.vp9&&st.opus;case b.DASH_WEBM_AV1:return s&&Fe.webm&&st.av1&&st.opus;case b.DASH_LIVE:return Lt.mse&&Fe.mp4&&Ri;case b.DASH_LIVE_CMAF:return s&&Fe.mp4&&Ri&&Fe.cmaf;case b.DASH_ONDEMAND:return s&&Fe.mp4&&Ri;case b.HLS:case b.HLS_ONDEMAND:return Vi||e&&Lt.mse&&Fe.mp4&&Ri;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return Vi;case b.MPEG:return Fe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Lt.webrtc&&Lt.ws&&st.h264&&(Fe.mp4||Fe.webm);default:return H(r)}})},bt=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case yt.VP9:return[e,t];case yt.AV1:return[t,e];case yt.NONE:return[];case yt.SMOOTH:return Dt?Dt[t].smooth?[t,e]:Dt[e].smooth?[e,t]:[t,e]:[e,t];case yt.POWER_EFFICIENT:return Dt?Dt[t].powerEfficient?[t,e]:Dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(i)}return[e,t]},$T=({webmCodec:i,androidPreferredFormat:e})=>{if(eu)switch(e){case Pe.MPEG:return[b.MPEG,...bt(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Pe.HLS:return[b.HLS,b.HLS_ONDEMAND,...bt(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case Pe.DASH:return[...bt(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case Pe.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...bt(i),b.HLS,b.HLS_ONDEMAND];case Pe.DASH_ANY_WEBM:return[...bt(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Pe.DASH_SEP:return[b.DASH_SEP,b.MPEG,...bt(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:H(e)}return Vi?[...bt(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...bt(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},AT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[b.DASH_LIVE_CMAF,b.DASH_LIVE]:[b.DASH_LIVE,b.DASH_LIVE_CMAF],r=e?[b.HLS_LIVE_CMAF,b.HLS_LIVE]:[b.HLS_LIVE,b.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(eu)switch(i){case Pe.DASH:case Pe.DASH_ANY_MPEG:case Pe.DASH_ANY_WEBM:case Pe.DASH_SEP:{o=a;break}case Pe.HLS:case Pe.MPEG:{o=n;break}default:H(i)}else Vi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},fd=i=>i?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE_CMAF]:[b.DASH_WEBM,b.DASH_WEBM_AV1,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var wT=i=>new Va(e=>{const t=new re,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:c})=>`${d}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:d})=>d!==void 0)),n=new L;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const kT={chunkDuration:5e3,maxParallelRequests:5};class PT{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new L,warning$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),elementVisible$:new y(!0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=ET([...AT(this.params.tuning),...$T(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>_(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new hd(a);const n=[...fd(!0),...fd(!1)];this.chromecastFormatsIterator=new hd(n.filter(o=>_(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:C.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return H(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new sT(Object.assign(Object.assign({},n),{source:o,sourceHls:u}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new rT(Object.assign(Object.assign({},n),{source:o}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Vi||!this.params.tuning.useHlsJs?new uT(Object.assign(Object.assign({},n),{source:o})):new aT(Object.assign(Object.assign({},n),{source:o}))}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new lT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new cT(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new ub(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},kT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new mT({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new kS({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Os(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,s=0;return e.add(F(this.providerOutput.error$,wT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:C.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(fe(({to:a})=>a===p.PLAYING),we()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===C.NETWORK,o=r.category===C.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ae.SCREEN)}})),e}}const _T=5e3,pd="one_video_throughput",md="one_video_rtt",ft=window.navigator.connection,vd=()=>{const i=ft==null?void 0:ft.downlink;if(_(i)&&i!==10)return i*1e3},gd=()=>{const i=ft==null?void 0:ft.rtt;if(_(i)&&i!==3e3)return i},Sd=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Oi{constructor(e){var t,s;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Oi.load(pd)||(e.useBrowserEstimation?vd():void 0)||_T,a=(s=(t=Oi.load(md))!==null&&t!==void 0?t:e.useBrowserEstimation?gd():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(Sd(r,a,e.rttPenaltyRequestSize)),this.throughput=Na.getSmoothedValue(r,-1,e),this.rtt=Na.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vd();u&&this.throughput.next(u);const d=gd();_(d)&&this.rtt.next(d)};ft&&"onchange"in ft&&this.subscription.add(D(ft,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{fr.set(pd,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{fr.set(md,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ue({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Sd(n,o,e.rttPenaltyRequestSize)),fe(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=le();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(D(e,"progress").pipe(we()).subscribe(a=>{t=a.loaded,s=le()}));break;case 1:case 0:r.add(D(e,"loadstart").subscribe(()=>{t=0,s=le()}));break}r.add(D(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-s;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=c=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=({done:c,value:l})=>te(this,void 0,void 0,function*(){if(c)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=l.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=l.byteLength,a=le()}o=le()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());yield s==null?void 0:s.read().then(d,u)}});this.concurrentDownloads.add(e),s==null||s.read().then(d,u)}addRawSpeed(e,t,s=1,r=!1){if(Oi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=fr.get(e);if(_(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const bd={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:De.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:De.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:yt.VP9,androidPreferredFormat:Pe.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},IT=i=>{var e;return Object.assign(Object.assign({},Ru(i,bd)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...bd.configName]})};var yd=({seekState:i,position$:e})=>F(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),fe(_)),e.pipe(fe(()=>i.getState().state===Y.None))),RT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const CT=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(fe(r=>r.length>0),we()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class MT{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Cu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:Y.None}),volume:new he({volume:1,muted:!1}),videoTrack:new he(void 0),autoVideoTrackSwitching:new he(!0),autoVideoTrackLimits:new he({}),isLooped:new he(!1),playbackRate:new he(1),externalTextTracks:new he([]),internalTextTracks:new he([]),currentTextTrack:new he(void 0),textTrackCuesSettings:new he({}),cameraOrientation:new he({x:0,y:0})},this.info={playbackState$:new y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(dt.NONE),chromecastState$:new y(ye.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0)},this.events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:qS},this.initLogs(),this.tuning=IT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Oi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(l=>JSON.stringify(l,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=RT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new PT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!xa()?D(document,"visibilitychange").pipe(we()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),we()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return CT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return _(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e===p.STOPPED),we()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:Y.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,u)=>Bt(o)?1:Bt(u)?-1:fi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe($(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ue({hasLiveOffsetByPaused:F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),pe(),$(n=>n===p.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ue({atLiveEdge:Ue({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:u})=>{const d=this.getActiveLiveDelay(u);return n&&Math.abs(o)<d/1e3}),pe(),Mi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ue({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe($(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),pe(),Mi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),pe()).subscribe(this.info.volume$)).add(yd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(F(e.providerOutput.endedEvent$.pipe(Rs(!0)),e.providerOutput.seekedEvent$.pipe(Rs(!1))).pipe(pe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe($(n=>({id:n?`No${n}`:"NoProviders",category:C.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(we(),$(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(we(),$(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(we(),$(()=>le()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n===p.PLAYING),we()).subscribe(()=>s.next(!1)));let r=0;const a=F(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),pe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(F(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(F(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue();let l;c===ye.CONNECTED?l=dt.SECOND_SCREEN:u?d?n?l=dt.PIP:o?l=dt.FULLSCREEN:l=dt.INLINE:l=dt.INVISIBLE:l=dt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new re;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),we()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Zs(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(F(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),YS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>jS(s)),this.providerContainer.current$.subscribe(({type:s})=>vs("provider",s)),t.duration$.subscribe(s=>vs("duration",s)),t.availableVideoTracks$.pipe(fe(s=>!!s.length),we()).subscribe(s=>vs("tracks",s)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),t.position$.subscribe(new tt("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),t.isBuffering$.subscribe(new tt("isBuffering"))].forEach(s=>this.subscription.add(s)),vs("codecs",TT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>te(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)})})});this.subscription.add(F(D(document,"visibilitychange"),D(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const BT=`@vkontakte/videoplayer-core@${Lu}`;export{ye as ChromecastState,ha as HttpConnectionType,VT as Observable,p as PlaybackState,MT as Player,BT as SDK_VERSION,UT as Subject,HT as Subscription,dt as Surface,Lu as VERSION,GT as ValueSubject,b as VideoFormat,jT as VideoQuality};
|
|
56
|
+
|
|
57
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
58
|
+
|
|
59
|
+
uniform sampler2D u_texture;
|
|
60
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
61
|
+
|
|
62
|
+
void main(void) {
|
|
63
|
+
// center point of output projection
|
|
64
|
+
float lambda0 = u_focus.x / 360.0;
|
|
65
|
+
float phi0 = u_focus.y / 180.0;
|
|
66
|
+
|
|
67
|
+
float lambda = PI * 2.0 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
68
|
+
float phi = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
69
|
+
|
|
70
|
+
float p = sqrt(lambda * lambda + phi * phi); // rou
|
|
71
|
+
float c = atan(p);
|
|
72
|
+
float cos_c = cos(c);
|
|
73
|
+
float sin_c = sin(c);
|
|
74
|
+
|
|
75
|
+
// geo coordinates of projection
|
|
76
|
+
float x = lambda0 + atan(
|
|
77
|
+
lambda * sin_c,
|
|
78
|
+
p * cos(phi0) * cos_c - phi * sin(phi0) * sin_c
|
|
79
|
+
);
|
|
80
|
+
float y = asin(cos_c * sin(phi0) + (phi * sin_c * cos(phi0)) / p);
|
|
81
|
+
|
|
82
|
+
// reprojected texture coordinates
|
|
83
|
+
vec2 tc = vec2(
|
|
84
|
+
mod(x / (PI * 2.0) - 0.5, 1.0), // [0..1]
|
|
85
|
+
mod(y / PI - 0.5, 1.0) // [0..1]
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
// sample using new coordinates
|
|
89
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
90
|
+
}
|
|
91
|
+
`;var gs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new ms(this.params.fov,this.params.orientation),this.cameraRotationManager=new bs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Wb,this.gl.VERTEX_SHADER),r=this.createShader(Qb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Qt=class{constructor(e){this.subscription=new LA;this.videoState=new C("stopped");this.elementSize$=new Zb(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new as;this.videoTracks$=new Zb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new es;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return IA(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new gs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=de(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:wu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe(ku(l=>l.map(({track:c})=>c)))}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(xA(wA),RA()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(He(this.video,t.isLooped,a)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(AA(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var c;if(l==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();zb(p,"Manifest not loaded or empty");let h=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),f=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of h){let g=Ab(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of f){let g=kb(S);if(g){d.push({track:g,representation:S});let y=!this.params.tuning.isAudioDisabled&&Rb(h,f,S);y&&this.audioRepresentations.set(S.id,y)}}this.videoTracks$.next(d);for(let S of b){let g=Lb(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();zb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.id,this.params.sourceHls)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:wu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(vs(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,PA(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&h&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=Xb(S),y=Xb(d);if(g&&y)return Jb(g,y)&&Jb(g,f)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Kb(),ku(l=>{var c;return l&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(ku(({to:l})=>l==="ready"),Kb());this.subscription.add(vs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(vs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=vs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kA(["init"])).pipe(EA(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,h,f,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=gt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(r&&!e&&(f=(h=this.audioRepresentations.get(r.id))==null?void 0:h.bitrate)!=null?f:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),l=bt(this.videoTracks$.getValue().map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?l!=null?l:r:r!=null?r:l;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),le(this.video)}};var Fi=class extends Qt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as eg,interval as $A,map as CA}from"@vkontakte/videoplayer-shared";var qi=class extends Qt{constructor(e){super(e),this.liveOffset=new Je}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(eg({interval:$A(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(eg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(CA(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var rg=Fe(Ka(),1);import{assertNever as Ui,assertNonNullable as tg,debounce as DA,ErrorCategory as Ss,filter as MA,isNonNullable as OA,isNullable as BA,map as Au,merge as VA,Observable as _A,observableFrom as NA,Subscription as FA,videoSizeToQuality as qA}from"@vkontakte/videoplayer-shared";var Be={};var Rr=(i,e)=>new _A(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Hi=class{constructor(e){this.subscription=new FA;this.videoState=new C("initializing");this.textTracksManager=new Ee;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ui(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ui(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ui(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ui(e)}break;default:Ui(t)}};this.video=ue(e.container),this.params=e,this.params.output.element$.next(this.video),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(Z(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),le(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ss.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rg.default)(import("hls.js").then(a=>{e||(Be.Hls=a.default,Be.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){tg(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tg(Be.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ss.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=de(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(He(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),this.subscription.add(Rr(this.hls,Be.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ss.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Rr(this.hls,Be.Events.MANIFEST_PARSED).pipe(Au(({levels:l})=>l.reduce((c,d)=>{var g,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=ft((g=d.attrs.QUALITY)!=null?g:""))!=null?y:qA({width:h,height:f});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Rr(this.hls,Be.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang,b="internal";c.push({id:p,url:h,language:f,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(Rr(this.hls,Be.Events.LEVEL_LOADING).pipe(Au(({url:l})=>Z(l))),t.hostname$),s(Rr(this.hls,Be.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Rr(this.hls,Be.Events.LEVEL_SWITCHED).pipe(Au(({level:l})=>n(this.hls.levels[l])));o.pipe(MA(OA)).subscribe(t.currentVideoTrack$,r),this.subscription.add(dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(BA(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=VA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NA(["init"])).pipe(DA(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ss.DOM,thrown:t})))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var ig="X-Playback-Duration",Ru=i=>R(void 0,null,function*(){var a;let e=yield Ze(i),t=yield e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(ig)?parseInt(e.headers.get(ig),10):void 0});import{assertNever as WA,combine as QA,debounce as zA,ErrorCategory as Ts,filter as KA,filterChanged as JA,isNonNullable as sg,isNullable as Is,map as ng,merge as XA,observableFrom as ZA,Subscription as eR,ValueSubject as Cu,VideoQuality as tR}from"@vkontakte/videoplayer-shared";var $u=Fe(_a(),1);import{videoSizeToQuality as UA,getExponentialDelay as HA}from"@vkontakte/videoplayer-shared";var jA=i=>{let e=null;if(i.QUALITY&&(e=ft(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=UA({width:t,height:r})}return e!=null?e:null},GA=(i,e)=>{var s,n;let t=i.split(`
|
|
92
|
+
`),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,$u.default)(l[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=jA(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,y]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&y&&(v={width:g,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:v,fps:b})}if(c){let d=(0,$u.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&a.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},YA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Lu=0,ag=(r,...a)=>R(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield Ze(i)).text();Lu+=1;try{let{qualityManifests:o,textTracks:u}=GA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Lu<=t.manifestRetryMaxCount)return yield YA(HA(Lu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ag(i,e,t)}return{qualityManifests:[],textTracks:[]}}),ys=ag;var ji=class{constructor(e){this.subscription=new eR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new Cu([]);this.liveOffset=new Je;this.manifestStartTime$=new Cu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(a==null?void 0:a.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(a==null?void 0:a.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return WA(t)}};var t;this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tR.INVARIANT,url:this.params.source.url},ys(re(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ts.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ts.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),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(Z(this.params.source.url)),this.maxSeekBackTime$=new Cu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ts.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(JA(),ng(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&sg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(QA({startTime:this.manifestStartTime$.pipe(KA(sg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(ng(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=XA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ZA(["init"])).pipe(zA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Is(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=re(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ru(n).then(l=>{var c;if(!Is(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Is(d)||!isFinite(d))try{Ze(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Ru(b).then(v=>{Is(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ts.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as rR,debounce as iR,ErrorCategory as Du,fromEvent as Mu,isNonNullable as aR,isNullable as sR,map as nR,merge as og,observableFrom as ug,Subscription as oR,ValueSubject as uR,VideoQuality as lR,isIOS as cR}from"@vkontakte/videoplayer-shared";var Gi=class{constructor(e){this.subscription=new oR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new uR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(a==null?void 0:a.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return rR(t)}};this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lR.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ys(re(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Du.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Du.WTF,message:"HlsProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&aR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(f),v.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(nR(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!cR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(og(Mu(o,"addtrack"),Mu(o,"removetrack"),Mu(o,"change"),ug(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=og(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ug(["init"])).pipe(iR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var s,n;let e=this.selectManifest();if(sR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as dR,assertNonNullable as lg,debounce as pR,ErrorCategory as cg,isHigher as hR,isHigherOrEqual as fR,isInvariantQuality as dg,isLowerOrEqual as mR,isNonNullable as bR,merge as gR,observableFrom as vR,Subscription as SR}from"@vkontakte/videoplayer-shared";var Yi=class{constructor(e){this.subscription=new SR;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ee;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return dR(e)}};this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:cg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&bR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=gR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vR(["init"])).pipe(pR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),le(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;lg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];lg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!dg(d.track.quality)&&mR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&fR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!dg(h.track.quality)&&hR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as hg,debounce as ER,merge as fg,observableFrom as xR,Subscription as PR,map as mg,ValueSubject as wR,ErrorCategory as Bu,VideoQuality as kR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as yR}from"@vkontakte/videoplayer-shared";var pg=["stun:videostun.mycdn.me:80"],TR=1e3,IR=3,Ou=()=>null,Es=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ou;this.externalStopCallback=Ou;this.externalErrorCallback=Ou;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:pg}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:yR.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){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()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),TR)}normalizeOptions(e={}){let t={stunServerList:pg,maxRetryNumber:IR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Wi=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new wR(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return hg(e)}};this.subscription=new PR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container),this.liveStreamClient=new Es(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Bu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};fg(this.videoState.stateChangeStarted$.pipe(mg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(mg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=de(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Pe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ce(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).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 hg(n.to)}},r)).add(fg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xR(["init"])).pipe(ER(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(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:kR.INVARIANT}),this.video.srcObject=e,E(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.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Bu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ki,assertNonNullable as Tt,ErrorCategory as $s,filter as FR,isNonNullable as Og,isNullable as qR,map as UR,merge as HR,once as jR,Subject as Ve,Subscription as Bg,ValueSubject as V}from"@vkontakte/videoplayer-shared";import{assertNever as Ls,CurrentClientDevice as LR,getCurrentBrowser as $R}from"@vkontakte/videoplayer-shared";var wg=$R().device===LR.Android,ke=document.createElement("video"),CR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',DR='video/mp4; codecs="hev1.1.6.L93.B0"',kg='video/webm; codecs="vp09.00.10.08"',Ag='video/webm; codecs="av01.0.00M.08"',MR='audio/mp4; codecs="mp4a.40.2"',OR='audio/webm; codecs="opus"',bg,gg,zt={mms:ps(),mse:Nb(),hls:!!((bg=ke.canPlayType)!=null&&bg.call(ke,"application/x-mpegurl")||(gg=ke.canPlayType)!=null&&gg.call(ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},vg,Sg,we={mp4:!!((vg=ke.canPlayType)!=null&&vg.call(ke,"video/mp4")),webm:!!((Sg=ke.canPlayType)!=null&&Sg.call(ke,"video/webm")),cmaf:!0},xs,yg,Ps,Tg,ws,Ig,ks,Eg,As,xg,Rs,Pg,Ge={h264:!!((yg=(xs=it())==null?void 0:xs.isTypeSupported)!=null&&yg.call(xs,CR)),h265:!!((Tg=(Ps=it())==null?void 0:Ps.isTypeSupported)!=null&&Tg.call(Ps,DR)),vp9:!!((Ig=(ws=it())==null?void 0:ws.isTypeSupported)!=null&&Ig.call(ws,kg)),av1:!!((Eg=(ks=it())==null?void 0:ks.isTypeSupported)!=null&&Eg.call(ks,Ag)),aac:!!((xg=(As=it())==null?void 0:As.isTypeSupported)!=null&&xg.call(As,MR)),opus:!!((Pg=(Rs=it())==null?void 0:Rs.isTypeSupported)!=null&&Pg.call(Rs,OR))},zi=(Ge.h264||Ge.h265)&&Ge.aac,Kt,BR=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(k({},i),{video:B(k({},i.video),{contentType:Ag})})),window.navigator.mediaCapabilities.decodingInfo(B(k({},i),{video:B(k({},i.video),{contentType:kg})}))]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{BR()}catch(i){console.error(i)}var Lr=zt.hls&&we.mp4,Rg=()=>Object.keys(Ge).filter(i=>Ge[i]),Lg=(i,e=!1,t=!1)=>{let r=zt.mse||zt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&we.mp4&&zi;case"DASH_WEBM":return r&&we.webm&&Ge.vp9&&Ge.opus;case"DASH_WEBM_AV1":return r&&we.webm&&Ge.av1&&Ge.opus;case"DASH_LIVE":return zt.mse&&we.mp4&&zi;case"DASH_LIVE_CMAF":return r&&we.mp4&&zi&&we.cmaf;case"DASH_ONDEMAND":return r&&we.mp4&&zi;case"HLS":case"HLS_ONDEMAND":return Lr||e&&zt.mse&&we.mp4&&zi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Lr;case"MPEG":return we.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zt.webrtc&&zt.ws&&Ge.h264&&(we.mp4||we.webm);default:return Ls(a)}})},yt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ls(i)}return[e,t]},$g=({webmCodec:i,androidPreferredFormat:e})=>{if(wg)switch(e){case"mpeg":return["MPEG",...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...yt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...yt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Ls(e)}return Lr?[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Cg=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(wg)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Ls(i)}else Lr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Vu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as VR,map as Dg,Subscription as _R,Subject as NR}from"@vkontakte/videoplayer-shared";var Mg=i=>new VR(e=>{let t=new _R,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Dg(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Dg(({type:l})=>l!==void 0)),n=new NR,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var GR={chunkDuration:5e3,maxParallelRequests:5},Ji=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Ve;this.noAvailableProvidersError$=new Ve;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),currentVideoTrack$:new V(void 0),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),availableVideoTracks$:new V([]),availableAudioTracks$:new V([]),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Ve,warning$:new Ve,willSeekEvent$:new Ve,seekedEvent$:new Ve,loopedEvent$:new Ve,endedEvent$:new Ve,firstBytesEvent$:new Ve,firstFrameEvent$:new Ve,canplay$:new Ve,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1)};this.subscription=new Bg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Lg([...Cg(this.params.tuning),...$g(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Og(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Qi(s);let n=[...Vu(!0),...Vu(!1)];this.chromecastFormatsIterator=new Qi(n.filter(o=>Og(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(qR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:$s.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ki(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Tt(o),new Fi(B(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new qi(B(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Tt(o),Lr||!this.params.tuning.useHlsJs?new Gi(B(k({},n),{source:o})):new Hi(B(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new ji(B(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Yi(B(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Om(B(k({},n),{source:o,config:B(k({},GR),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Wi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Ki(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Tt(o),new ei({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}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 Ki(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ki(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ki(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return B(k({},e),{url:r(e.url)})}return(0,Vg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Bg,t=!1,r=0;return e.add(HR(this.providerOutput.error$,Mg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(UR(a=>({id:`ProviderHangup:${a}`,category:$s.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(FR(({to:s})=>s==="playing"),jR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===$s.NETWORK,o=a.category===$s.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Cs,once as YR,combine as WR,Subscription as _g,ValueSubject as _u,map as QR,filter as zR,isNonNullable as Ds,now as ve,safeStorage as Nu}from"@vkontakte/videoplayer-shared";var KR=5e3,Ng="one_video_throughput",Fg="one_video_rtt",at=window.navigator.connection,qg=()=>{let i=at==null?void 0:at.downlink;if(Ds(i)&&i!==10)return i*1e3},Ug=()=>{let i=at==null?void 0:at.rtt;if(Ds(i)&&i!==3e3)return i},Hg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Fu=class i{constructor(e){this.subscription=new _g;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Ng)||(e.useBrowserEstimation?qg():void 0)||KR,r=(s=(a=i.load(Fg))!=null?a:e.useBrowserEstimation?Ug():void 0)!=null?s:0;if(this.throughput$=new _u(t),this.rtt$=new _u(r),this.rttAdjustedThroughput$=new _u(Hg(t,r,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=qg();u&&this.throughput.next(u);let l=Ug();Ds(l)&&this.rtt.next(l)};at&&"onchange"in at&&this.subscription.add(Cs(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Nu.set(Ng,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Nu.set(Fg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(WR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(QR(({throughput:n,rtt:o})=>Hg(n,o,e.rttPenaltyRequestSize)),zR(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=ve(),a=new _g;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Cs(e,"progress").pipe(YR()).subscribe(s=>{t=s.loaded,r=ve()}));break;case 1:case 0:a.add(Cs(e,"loadstart").subscribe(()=>{t=0,r=ve()}));break}a.add(Cs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=ve(),n=0,o=ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>R(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(ve()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=ve()}o=ve()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ve()-o,this.concurrentDownloads.size),n=0,o=ve());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Nu.get(e);if(Ds(t))return(r=parseInt(t,10))!=null?r:void 0}},jg=Fu;import{fillWithDefault as JR,VideoQuality as Gg}from"@vkontakte/videoplayer-shared";var Yg={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Gg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gg.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Wg=i=>{var e;return B(k({},JR(i,Yg)),{configName:[...(e=i.configName)!=null?e:[],...Yg.configName]})};import{assertNonNullable as Ms,combine as Os,ErrorCategory as Bs,filter as Xi,filterChanged as Ae,fromEvent as Uu,isNonNullable as aL,isNullable as sL,Logger as nL,map as M,mapTo as Jg,merge as It,now as Vs,once as st,Subject as j,Subscription as Xg,tap as Zg,ValueSubject as P,isHigher as oL,isInvariantQuality as ev}from"@vkontakte/videoplayer-shared";import{merge as XR,map as ZR,filter as Qg,isNonNullable as eL}from"@vkontakte/videoplayer-shared";var qu=({seekState:i,position$:e})=>XR(i.stateChangeEnded$.pipe(ZR(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Qg(eL)),e.pipe(Qg(()=>i.getState().state==="none")));import{assertNonNullable as tL}from"@vkontakte/videoplayer-shared";var zg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return tL(e,`Wrong container or containerId {${i.container}}`),e};import{filter as rL,once as iL}from"@vkontakte/videoplayer-shared";var Kg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(rL(a=>a.length>0),iL()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var _s=class{constructor(e={configName:[]}){this.subscription=new Xg;this.logger=new nL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Im};if(this.initLogs(),this.tuning=Wg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new la({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new jg(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Bs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=zg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Ji({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!li()?Uu(document,"visibilitychange").pipe(st()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){Ms(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Xi(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ms(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>k({type:"external"},t))),this}selectTextTrack(e){var t;return Kg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(sL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return aL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Xi(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Vs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(B(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(M(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(n=>n.destination),Ae()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(M(n=>n.map(({quality:o})=>o).sort((o,u)=>ev(o)?1:ev(u)?-1:oL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Ae()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(M(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Os({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(n=>n.to),Ae(),M(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Os({atLiveEdge:Os({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Ae(),Zg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Os({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Ae(),Zg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(n=>n.muted),Ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(n=>n.volume),Ae()).subscribe(this.info.volume$)).add(qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(Jg(!0)),e.providerOutput.seekedEvent$.pipe(Jg(!1))).pipe(Ae()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(M(n=>({id:n?`No${n}`:"NoProviders",category:Bs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),M(n=>n!=null?n:Vs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),M(()=>Vs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),M(()=>Vs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Xi(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let a=0,s=It(e.providerOutput.isBuffering$,t,r).pipe(M(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Ae());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(It(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(It(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Xg;this.subscription.add(t),this.subscription.add(e.current$.pipe(Ae((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Xi(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=bt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ms(this.providerContainer),Ms(e),Tm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ym(r)),this.providerContainer.current$.subscribe(({type:r})=>ai("provider",r)),e.duration$.subscribe(r=>ai("duration",r)),e.availableVideoTracks$.pipe(Xi(r=>!!r.length),st()).subscribe(r=>ai("tracks",r)),this.events.fatalError$.subscribe(new ae("fatalError")),this.events.managedError$.subscribe(new ae("managedError")),e.position$.subscribe(new ae("position")),e.currentVideoTrack$.pipe(M(r=>r==null?void 0:r.quality)).subscribe(new ae("quality")),this.info.currentBuffer$.subscribe(new ae("buffer")),e.isBuffering$.subscribe(new ae("isBuffering"))].forEach(r=>this.subscription.add(r)),ai("codecs",Rg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bs.DOM,message:String(a)})})});this.subscription.add(It(Uu(document,"visibilitychange"),Uu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as Lj,Observable as $j,Subject as Cj,ValueSubject as Dj,VideoQuality as Mj}from"@vkontakte/videoplayer-shared";var Oj=`@vkontakte/videoplayer-core@${cl}`;export{oa as ChromecastState,Ks as HttpConnectionType,$j as Observable,fe as PlaybackState,_s as Player,Oj as SDK_VERSION,Cj as Subject,Lj as Subscription,Js as Surface,cl as VERSION,Dj as ValueSubject,At as VideoFormat,Mj as VideoQuality};
|