@vkontakte/videoplayer-core 2.0.77 → 2.0.78
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 +6 -4
- package/es2015.esm.js +6 -4
- package/es2018.cjs.js +6 -4
- package/es2018.esm.js +6 -4
- package/esnext.cjs.js +6 -4
- package/esnext.esm.js +6 -4
- package/index.d.ts +606 -8
- package/package.json +4 -4
- package/build/polyfills/runtime/abortableFetch.d.ts +0 -4
- package/build/polyfills/runtime/idleCallback.d.ts +0 -2
- package/env.d.ts +0 -2
- package/es2015.cjs.d.ts +0 -11
- package/es2015.esm.d.ts +0 -11
- package/es2018.cjs.d.ts +0 -11
- package/es2018.esm.d.ts +0 -11
- package/esnext.esm.d.ts +0 -11
- package/packages/core/src/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -23
- package/packages/core/src/providers/DashIFProvider/dashjsTypes.d.ts +0 -37
- package/packages/core/src/providers/DashLiveProvider/types.d.ts +0 -14
- package/packages/core/src/providers/DashLiveProvider/utils/FilesFetcher.d.ts +0 -25
- package/packages/core/src/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -135
- package/packages/core/src/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -33
- package/packages/core/src/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -42
- package/packages/core/src/providers/DashProvider/types.d.ts +0 -33
- package/packages/core/src/providers/DashProvider/utils/DashLite.d.ts +0 -60
- package/packages/core/src/providers/DashProvider/utils/stream.d.ts +0 -39
- package/packages/core/src/providers/DashProvider/utils/xhr2.d.ts +0 -15
- package/packages/core/src/providers/DashVKProvider/lib/buffer.d.ts +0 -72
- package/packages/core/src/providers/DashVKProvider/lib/ebml.d.ts +0 -71
- package/packages/core/src/providers/DashVKProvider/lib/fetcher.d.ts +0 -43
- package/packages/core/src/providers/DashVKProvider/lib/isobmff.d.ts +0 -13
- package/packages/core/src/providers/DashVKProvider/lib/mpd.d.ts +0 -2
- package/packages/core/src/providers/DashVKProvider/lib/player.d.ts +0 -47
- package/packages/core/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +0 -18
- package/packages/core/src/providers/DashVKProvider/lib/types.d.ts +0 -92
- package/packages/core/src/providers/DashVKProvider/lib/webm.d.ts +0 -3
- package/packages/core/src/providers/ProviderContainer/types.d.ts +0 -20
- package/packages/core/src/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +0 -9
- package/packages/core/src/providers/types.d.ts +0 -64
- package/packages/core/src/providers/utils/LiveOffset/index.d.ts +0 -14
- package/packages/core/src/providers/utils/LiveOffset/types.d.ts +0 -10
- package/packages/core/src/providers/utils/extractConnectionHeaders.d.ts +0 -6
- package/packages/core/src/utils/StateMachine/types.d.ts +0 -56
- package/packages/core/src/utils/StatefulIterator/StatefulIterator.spec.d.ts +0 -1
- package/packages/core/src/utils/buffer/HttpVideoBuffer.d.ts +0 -14
- package/packages/core/src/utils/buffer/getTotalBufferDuration.d.ts +0 -3
- package/packages/core/src/utils/buffer/isPositionBuffered.d.ts +0 -3
- package/packages/core/src/utils/buffer/types.d.ts +0 -4
- package/packages/core/src/utils/link.d.ts +0 -2
- package/packages/core/src/utils/quality/quality.spec.d.ts +0 -1
- package/player/Player.d.ts +0 -111
- package/player/types.d.ts +0 -430
- package/player/utils/optimisticPosition.d.ts +0 -12
- package/player/utils/selectContainer.d.ts +0 -3
- package/player/utils/watchCoverage.d.ts +0 -12
- package/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +0 -31
- package/providers/ChromecastProvider/index.d.ts +0 -33
- package/providers/DashIFProvider/BigRequestLoader.d.ts +0 -41
- package/providers/DashIFProvider/endOfStreamHack.d.ts +0 -3
- package/providers/DashIFProvider/index.d.ts +0 -37
- package/providers/DashIFProvider/observableManifestLoader.d.ts +0 -11
- package/providers/DashIFProvider/requestQuic.d.ts +0 -3
- package/providers/DashIFProvider/stripRangeHeader.d.ts +0 -3
- package/providers/DashLiveProvider/DashLiveProvider.d.ts +0 -36
- package/providers/DashLiveProvider/index.d.ts +0 -2
- package/providers/DashProvider/DashProvider.d.ts +0 -32
- package/providers/DashProvider/index.d.ts +0 -2
- package/providers/DashVKProvider/index.d.ts +0 -23
- package/providers/DashVKProvider/lib/player.d.ts +0 -47
- package/providers/DashVKProvider/lib/types.d.ts +0 -92
- package/providers/HlsJsProvider/index.d.ts +0 -24
- package/providers/HlsLiveProvider/index.d.ts +0 -28
- package/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +0 -3
- package/providers/HlsProvider/index.d.ts +0 -20
- package/providers/HlsProvider/qualityExtractor.d.ts +0 -12
- package/providers/MpegProvider/index.d.ts +0 -19
- package/providers/ProviderContainer/index.d.ts +0 -69
- package/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -4
- package/providers/ProviderContainer/utils/playbackHangup.d.ts +0 -11
- package/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +0 -188
- package/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +0 -60
- package/providers/utils/HtmlVideoTextTrackManager.d.ts +0 -23
- package/providers/utils/addQuicParam.d.ts +0 -2
- package/providers/utils/forcePlay.d.ts +0 -7
- package/providers/utils/generateLiveUrl.d.ts +0 -7
- package/providers/utils/initVideoInContainer.d.ts +0 -2
- package/providers/utils/observableVideo.d.ts +0 -24
- package/providers/utils/okQualityStringToVideoQuality.d.ts +0 -3
- package/providers/utils/parseFps.d.ts +0 -1
- package/providers/utils/syncDesiredState.d.ts +0 -12
- package/providers/utils/syncPlaybackState.d.ts +0 -4
- package/utils/StateMachine/StateMachine.d.ts +0 -17
- package/utils/StatefulIterator/index.d.ts +0 -13
- package/utils/ThroughputEstimator.d.ts +0 -25
- package/utils/addScript.d.ts +0 -2
- package/utils/autoSelectVideoTrack.d.ts +0 -24
- package/utils/buffer/getBufferedRangeForPosition.d.ts +0 -3
- package/utils/buffer/getForwardBufferDuration.d.ts +0 -3
- package/utils/hostnameFromUrl.d.ts +0 -2
- package/utils/iframeSafeStorage.d.ts +0 -5
- package/utils/isSafari.d.ts +0 -2
- package/utils/observeElementSize.d.ts +0 -3
- package/utils/playbackTelemetry.d.ts +0 -12
- package/utils/quality/types.d.ts +0 -21
- package/utils/quality/utils.d.ts +0 -20
- package/utils/smoothedValue.d.ts +0 -28
- package/utils/tuningConfig.d.ts +0 -75
- package/utils/videoFormat.d.ts +0 -2
package/es2018.cjs.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Thu,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
+
* Thu, 02 Feb 2023 10:14:35 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-78/doc/
|
|
5
5
|
*/
|
|
6
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2018.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce.js'));var a,r,o,n,l,u;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_ONDEMAND_VK='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS',r.HLS_LIVE='HLS_LIVE',r.WEB_RTC_LIVE='WEB_RTC_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(o||(o={})),exports.ChromecastState=void 0,(n=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',n.AVAILABLE='AVAILABLE',n.CONNECTING='CONNECTING',n.CONNECTED='CONNECTED',exports.HttpConnectionType=void 0,(l=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',l.HTTP2='http2',l.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(u||(u={}));class d{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,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 a=t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast),r=Boolean(window.__onGCastApiAvailable);var o;a?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},r||(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:t.ErrorCategory.NETWORK,message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,a;null===(a=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===a||a.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,a;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(a=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===a?void 0:a.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 t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(h),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var r;const o=a===exports.ChromecastState.CONNECTED,n=t.isNonNullable(this.connection$.getValue());if(o&&!n){const a=s.getCurrentSession();t.assertNonNullable(a);const o=a.getCastDevice(),n=null===(r=a.getMediaSession())||void 0===r?void 0:r.media.contentId;(t.isNullable(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:a,castDevice:o}))}else!o&&n&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){var e;let i,s,a;try{i=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{i.setOptions({receiverApplicationId:null!==(e=this.params.receiverApplicationId)&&void 0!==e?e:s,autoJoinPolicy:a}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',category:t.ErrorCategory.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:e})}}}const h=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var c='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},p=function(t){try{return!!t()}catch(t){return!0}},m=!p((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),f=m,b=Function.prototype,S=b.bind,v=b.call,g=f&&S.bind(v,v),y=f?function(t){return t&&g(t)}:function(t){return t&&function(){return v.apply(t,arguments)}},T=y,E=T({}.toString),k=T(''.slice),w=function(t){return k(E(t),8,-1)},P=p,$=w,A=Object,x=y(''.split),N=P((function(){return!A('z').propertyIsEnumerable(0)}))?function(t){return'String'==$(t)?x(t,''):A(t)}:A,R=TypeError,D=function(t){if(null==t)throw R('Can\'t call method on '+t);return t},C=N,_=D,I=function(t){return C(_(t))},L={},O=function(t){return t&&t.Math==Math&&t},B=O('object'==typeof globalThis&&globalThis)||O('object'==typeof window&&window)||O('object'==typeof self&&self)||O('object'==typeof c&&c)||function(){return this}()||Function('return this')(),M=function(t){return'function'==typeof t},V=B,F=Object.defineProperty,U=function(t,e){try{F(V,t,{value:e,configurable:!0,writable:!0})}catch(i){V[t]=e}return e},q=B['__core-js_shared__']||U('__core-js_shared__',{}),j=M,H=q,G=y(Function.toString);j(H.inspectSource)||(H.inspectSource=function(t){return G(t)});var Y,Q,z=M,W=H.inspectSource,J=B.WeakMap,X=z(J)&&/native code/.test(W(J)),K=M,Z=function(t){return'object'==typeof t?null!==t:K(t)},tt=!p((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),et={},it=Z,st=B.document,at=it(st)&&it(st.createElement),rt=function(t){return at?st.createElement(t):{}},ot=rt,nt=!tt&&!p((function(){return 7!=Object.defineProperty(ot('div'),'a',{get:function(){return 7}}).a})),lt=tt&&p((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ut=Z,dt=String,ht=TypeError,ct=function(t){if(ut(t))return t;throw ht(dt(t)+' is not an object')},pt=m,mt=Function.prototype.call,ft=pt?mt.bind(mt):function(){return mt.apply(mt,arguments)},bt={},St=bt,vt=B,gt=M,yt=function(t){return gt(t)?t:void 0},Tt=function(t,e){return arguments.length<2?yt(St[t])||yt(vt[t]):St[t]&&St[t][e]||vt[t]&&vt[t][e]},Et=y({}.isPrototypeOf),kt=B,wt=Tt('navigator','userAgent')||'',Pt=kt.process,$t=kt.Deno,At=Pt&&Pt.versions||$t&&$t.version,xt=At&&At.v8;xt&&(Q=(Y=xt.split('.'))[0]>0&&Y[0]<4?1:+(Y[0]+Y[1])),!Q&&wt&&(!(Y=wt.match(/Edge\/(\d+)/))||Y[1]>=74)&&(Y=wt.match(/Chrome\/(\d+)/))&&(Q=+Y[1]);var Nt=Q,Rt=p,Dt=!!Object.getOwnPropertySymbols&&!Rt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Nt&&Nt<41})),Ct=Dt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,_t=Tt,It=M,Lt=Et,Ot=Object,Bt=Ct?function(t){return'symbol'==typeof t}:function(t){var e=_t('Symbol');return It(e)&&Lt(e.prototype,Ot(t))},Mt=String,Vt=function(t){try{return Mt(t)}catch(t){return'Object'}},Ft=M,Ut=Vt,qt=TypeError,jt=function(t){if(Ft(t))return t;throw qt(Ut(t)+' is not a function')},Ht=jt,Gt=function(t,e){var i=t[e];return null==i?void 0:Ht(i)},Yt=ft,Qt=M,zt=Z,Wt=TypeError,Jt={exports:{}},Xt=q;(Jt.exports=function(t,e){return Xt[t]||(Xt[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Kt=D,Zt=Object,te=function(t){return Zt(Kt(t))},ee=te,ie=y({}.hasOwnProperty),se=Object.hasOwn||function(t,e){return ie(ee(t),e)},ae=y,re=0,oe=Math.random(),ne=ae(1..toString),le=function(t){return'Symbol('+(void 0===t?'':t)+')_'+ne(++re+oe,36)},ue=B,de=Jt.exports,he=se,ce=le,pe=Dt,me=Ct,fe=de('wks'),be=ue.Symbol,Se=be&&be.for,ve=me?be:be&&be.withoutSetter||ce,ge=function(t){if(!he(fe,t)||!pe&&'string'!=typeof fe[t]){var e='Symbol.'+t;pe&&he(be,t)?fe[t]=be[t]:fe[t]=me&&Se?Se(e):ve(e)}return fe[t]},ye=ft,Te=Z,Ee=Bt,ke=Gt,we=function(t,e){var i,s;if('string'===e&&Qt(i=t.toString)&&!zt(s=Yt(i,t)))return s;if(Qt(i=t.valueOf)&&!zt(s=Yt(i,t)))return s;if('string'!==e&&Qt(i=t.toString)&&!zt(s=Yt(i,t)))return s;throw Wt('Can\'t convert object to primitive value')},Pe=TypeError,$e=ge('toPrimitive'),Ae=function(t,e){if(!Te(t)||Ee(t))return t;var i,s=ke(t,$e);if(s){if(void 0===e&&(e='default'),i=ye(s,t,e),!Te(i)||Ee(i))return i;throw Pe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),we(t,e)},xe=Bt,Ne=function(t){var e=Ae(t,'string');return xe(e)?e:e+''},Re=tt,De=nt,Ce=lt,_e=ct,Ie=Ne,Le=TypeError,Oe=Object.defineProperty,Be=Object.getOwnPropertyDescriptor;et.f=Re?Ce?function(t,e,i){if(_e(t),e=Ie(e),_e(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Be(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Oe(t,e,i)}:Oe:function(t,e,i){if(_e(t),e=Ie(e),_e(i),De)try{return Oe(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Le('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Me,Ve,Fe,Ue=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},qe=et,je=Ue,He=tt?function(t,e,i){return qe.f(t,e,je(1,i))}:function(t,e,i){return t[e]=i,t},Ge=Jt.exports,Ye=le,Qe=Ge('keys'),ze=function(t){return Qe[t]||(Qe[t]=Ye(t))},We={},Je=X,Xe=B,Ke=y,Ze=Z,ti=He,ei=se,ii=q,si=ze,ai=We,ri=Xe.TypeError,oi=Xe.WeakMap;if(Je||ii.state){var ni=ii.state||(ii.state=new oi),li=Ke(ni.get),ui=Ke(ni.has),di=Ke(ni.set);Me=function(t,e){if(ui(ni,t))throw new ri('Object already initialized');return e.facade=t,di(ni,t,e),e},Ve=function(t){return li(ni,t)||{}},Fe=function(t){return ui(ni,t)}}else{var hi=si('state');ai[hi]=!0,Me=function(t,e){if(ei(t,hi))throw new ri('Object already initialized');return e.facade=t,ti(t,hi,e),e},Ve=function(t){return ei(t,hi)?t[hi]:{}},Fe=function(t){return ei(t,hi)}}var ci={set:Me,get:Ve,has:Fe,enforce:function(t){return Fe(t)?Ve(t):Me(t,{})},getterFor:function(t){return function(e){var i;if(!Ze(e)||(i=Ve(e)).type!==t)throw ri('Incompatible receiver, '+t+' required');return i}}},pi=m,mi=Function.prototype,fi=mi.apply,bi=mi.call,Si='object'==typeof Reflect&&Reflect.apply||(pi?bi.bind(fi):function(){return bi.apply(fi,arguments)}),vi={},gi={},yi={}.propertyIsEnumerable,Ti=Object.getOwnPropertyDescriptor,Ei=Ti&&!yi.call({1:2},1);gi.f=Ei?function(t){var e=Ti(this,t);return!!e&&e.enumerable}:yi;var ki=tt,wi=ft,Pi=gi,$i=Ue,Ai=I,xi=Ne,Ni=se,Ri=nt,Di=Object.getOwnPropertyDescriptor;vi.f=ki?Di:function(t,e){if(t=Ai(t),e=xi(e),Ri)try{return Di(t,e)}catch(t){}if(Ni(t,e))return $i(!wi(Pi.f,t,e),t[e])};var Ci=p,_i=M,Ii=/#|\.prototype\./,Li=function(t,e){var i=Bi[Oi(t)];return i==Vi||i!=Mi&&(_i(e)?Ci(e):!!e)},Oi=Li.normalize=function(t){return String(t).replace(Ii,'.').toLowerCase()},Bi=Li.data={},Mi=Li.NATIVE='N',Vi=Li.POLYFILL='P',Fi=Li,Ui=jt,qi=m,ji=y(y.bind),Hi=function(t,e){return Ui(t),void 0===e?t:qi?ji(t,e):function(){return t.apply(e,arguments)}},Gi=B,Yi=Si,Qi=y,zi=M,Wi=vi.f,Ji=Fi,Xi=bt,Ki=Hi,Zi=He,ts=se,es=function(t){var e=function(i,s,a){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,a)}return Yi(t,this,arguments)};return e.prototype=t.prototype,e},is=function(t,e){var i,s,a,r,o,n,l,u,d=t.target,h=t.global,c=t.stat,p=t.proto,m=h?Gi:c?Gi[d]:(Gi[d]||{}).prototype,f=h?Xi:Xi[d]||Zi(Xi,d,{})[d],b=f.prototype;for(a in e)i=!Ji(h?a:d+(c?'.':'#')+a,t.forced)&&m&&ts(m,a),o=f[a],i&&(n=t.dontCallGetSet?(u=Wi(m,a))&&u.value:m[a]),r=i&&n?n:e[a],i&&typeof o==typeof r||(l=t.bind&&i?Ki(r,Gi):t.wrap&&i?es(r):p&&zi(r)?Qi(r):r,(t.sham||r&&r.sham||o&&o.sham)&&Zi(l,'sham',!0),Zi(f,a,l),p&&(ts(Xi,s=d+'Prototype')||Zi(Xi,s,{}),Zi(Xi[s],a,r),t.real&&b&&!b[a]&&Zi(b,a,r)))},ss=tt,as=se,rs=Function.prototype,os=ss&&Object.getOwnPropertyDescriptor,ns=as(rs,'name'),ls={EXISTS:ns,PROPER:ns&&'something'===function(){}.name,CONFIGURABLE:ns&&(!ss||ss&&os(rs,'name').configurable)},us={},ds=Math.ceil,hs=Math.floor,cs=Math.trunc||function(t){var e=+t;return(e>0?hs:ds)(e)},ps=function(t){var e=+t;return e!=e||0===e?0:cs(e)},ms=ps,fs=Math.max,bs=Math.min,Ss=ps,vs=Math.min,gs=function(t){return t>0?vs(Ss(t),9007199254740991):0},ys=function(t){return gs(t.length)},Ts=I,Es=function(t,e){var i=ms(t);return i<0?fs(i+e,0):bs(i,e)},ks=ys,ws=function(t){return function(e,i,s){var a,r=Ts(e),o=ks(r),n=Es(s,o);if(t&&i!=i){for(;o>n;)if((a=r[n++])!=a)return!0}else for(;o>n;n++)if((t||n in r)&&r[n]===i)return t||n||0;return!t&&-1}},Ps={includes:ws(!0),indexOf:ws(!1)},$s=se,As=I,xs=Ps.indexOf,Ns=We,Rs=y([].push),Ds=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Cs=function(t,e){var i,s=As(t),a=0,r=[];for(i in s)!$s(Ns,i)&&$s(s,i)&&Rs(r,i);for(;e.length>a;)$s(s,i=e[a++])&&(~xs(r,i)||Rs(r,i));return r},_s=Ds,Is=Object.keys||function(t){return Cs(t,_s)},Ls=tt,Os=lt,Bs=et,Ms=ct,Vs=I,Fs=Is;us.f=Ls&&!Os?Object.defineProperties:function(t,e){Ms(t);for(var i,s=Vs(e),a=Fs(e),r=a.length,o=0;r>o;)Bs.f(t,i=a[o++],s[i]);return t};var Us,qs=Tt('document','documentElement'),js=ct,Hs=us,Gs=Ds,Ys=We,Qs=qs,zs=rt,Ws=ze('IE_PROTO'),Js=function(){},Xs=function(t){return'<script>'+t+'<\/script>'},Ks=function(t){t.write(Xs('')),t.close();var e=t.parentWindow.Object;return t=null,e},Zs=function(){try{Us=new ActiveXObject('htmlfile')}catch(t){}var t,e;Zs='undefined'!=typeof document?document.domain&&Us?Ks(Us):((e=zs('iframe')).style.display='none',Qs.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Xs('document.F=Object')),t.close(),t.F):Ks(Us);for(var i=Gs.length;i--;)delete Zs.prototype[Gs[i]];return Zs()};Ys[Ws]=!0;var ta,ea,ia,sa=Object.create||function(t,e){var i;return null!==t?(Js.prototype=js(t),i=new Js,Js.prototype=null,i[Ws]=t):i=Zs(),void 0===e?i:Hs.f(i,e)},aa=!p((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ra=se,oa=M,na=te,la=aa,ua=ze('IE_PROTO'),da=Object,ha=da.prototype,ca=la?da.getPrototypeOf:function(t){var e=na(t);if(ra(e,ua))return e[ua];var i=e.constructor;return oa(i)&&e instanceof i?i.prototype:e instanceof da?ha:null},pa=He,ma=function(t,e,i,s){return s&&s.enumerable?t[e]=i:pa(t,e,i),t},fa=p,ba=M,Sa=sa,va=ca,ga=ma,ya=ge('iterator'),Ta=!1;[].keys&&('next'in(ia=[].keys())?(ea=va(va(ia)))!==Object.prototype&&(ta=ea):Ta=!0);var Ea=null==ta||fa((function(){var t={};return ta[ya].call(t)!==t}));ba((ta=Ea?{}:Sa(ta))[ya])||ga(ta,ya,(function(){return this}));var ka={IteratorPrototype:ta,BUGGY_SAFARI_ITERATORS:Ta},wa={};wa[ge('toStringTag')]='z';var Pa='[object z]'===String(wa),$a=Pa,Aa=M,xa=w,Na=ge('toStringTag'),Ra=Object,Da='Arguments'==xa(function(){return arguments}()),Ca=$a?xa:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=Ra(t),Na))?i:Da?xa(e):'Object'==(s=xa(e))&&Aa(e.callee)?'Arguments':s},_a=Ca,Ia=Pa?{}.toString:function(){return'[object '+_a(this)+']'},La=Pa,Oa=et.f,Ba=He,Ma=se,Va=Ia,Fa=ge('toStringTag'),Ua=function(t,e,i,s){if(t){var a=i?t:t.prototype;Ma(a,Fa)||Oa(a,Fa,{configurable:!0,value:e}),s&&!La&&Ba(a,'toString',Va)}},qa=ka.IteratorPrototype,ja=sa,Ha=Ue,Ga=Ua,Ya=L,Qa=function(){return this},za=(TypeError,y);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=za(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Wa=is,Ja=ft,Xa=function(t,e,i,s){var a=e+' Iterator';return t.prototype=ja(qa,{next:Ha(+!s,i)}),Ga(t,a,!1,!0),Ya[a]=Qa,t},Ka=ca,Za=Ua,tr=ma,er=L,ir=ls.PROPER,sr=ka.BUGGY_SAFARI_ITERATORS,ar=ge('iterator'),rr=function(){return this},or=I,nr=L,lr=ci;et.f;var ur=function(t,e,i,s,a,r,o){Xa(i,e,s);var n,l,u,d=function(t){if(t===a&&f)return f;if(!sr&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},h=e+' Iterator',c=!1,p=t.prototype,m=p[ar]||p['@@iterator']||a&&p[a],f=!sr&&m||d(a),b='Array'==e&&p.entries||m;if(b&&(n=Ka(b.call(new t)))!==Object.prototype&&n.next&&(Za(n,h,!0,!0),er[h]=rr),ir&&'values'==a&&m&&'values'!==m.name&&(c=!0,f=function(){return Ja(m,this)}),a)if(l={values:d('values'),keys:r?f:d('keys'),entries:d('entries')},o)for(u in l)(sr||c||!(u in p))&&tr(p,u,l[u]);else Wa({target:e,proto:!0,forced:sr||c},l);return o&&p[ar]!==f&&tr(p,ar,f,{name:a}),er[e]=f,l},dr=lr.set,hr=lr.getterFor('Array Iterator');ur(Array,'Array',(function(t,e){dr(this,{type:'Array Iterator',target:or(t),index:0,kind:e})}),(function(){var t=hr(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),nr.Arguments=nr.Array;var cr=L,pr=ge('iterator'),mr=Array.prototype,fr=Ca,br=Gt,Sr=L,vr=ge('iterator'),gr=function(t){if(null!=t)return br(t,vr)||br(t,'@@iterator')||Sr[fr(t)]},yr=ft,Tr=jt,Er=ct,kr=Vt,wr=gr,Pr=TypeError,$r=ft,Ar=ct,xr=Gt,Nr=Hi,Rr=ft,Dr=ct,Cr=Vt,_r=function(t){return void 0!==t&&(cr.Array===t||mr[pr]===t)},Ir=ys,Lr=Et,Or=function(t,e){var i=arguments.length<2?wr(t):e;if(Tr(i))return Er(yr(i,t));throw Pr(kr(t)+' is not iterable')},Br=gr,Mr=function(t,e,i){var s,a;Ar(t);try{if(!(s=xr(t,'return'))){if('throw'===e)throw i;return i}s=$r(s,t)}catch(t){a=!0,s=t}if('throw'===e)throw i;if(a)throw s;return Ar(s),i},Vr=TypeError,Fr=function(t,e){this.stopped=t,this.result=e},Ur=Fr.prototype,qr=Ne,jr=et,Hr=Ue,Gr=function(t,e,i){var s,a,r,o,n,l,u,d=i&&i.that,h=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Nr(e,d),b=function(t){return s&&Mr(s,'normal',t),new Fr(!0,t)},S=function(t){return h?(Dr(t),m?f(t[0],t[1],b):f(t[0],t[1])):m?f(t,b):f(t)};if(c)s=t.iterator;else if(p)s=t;else{if(!(a=Br(t)))throw Vr(Cr(t)+' is not iterable');if(_r(a)){for(r=0,o=Ir(t);o>r;r++)if((n=S(t[r]))&&Lr(Ur,n))return n;return new Fr(!1)}s=Or(t,a)}for(l=c?t.next:s.next;!(u=Rr(l,s)).done;){try{n=S(u.value)}catch(t){Mr(s,'throw',t)}if('object'==typeof n&&n&&Lr(Ur,n))return n}return new Fr(!1)},Yr=function(t,e,i){var s=qr(e);s in t?jr.f(t,s,Hr(0,i)):t[s]=i};is({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Gr(t,(function(t,i){Yr(e,t,i)}),{AS_ENTRIES:!0}),e}});var Qr=bt.Object.fromEntries,zr={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},Wr=B,Jr=Ca,Xr=He,Kr=L,Zr=ge('toStringTag');for(var to in zr){var eo=Wr[to],io=eo&&eo.prototype;io&&Jr(io)!==Zr&&Xr(io,Zr,to),Kr[to]=Kr.Array}var so,ao=Qr;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(so||(so={}));var ro,oo=(e,i=0,s=so.OFFSET_P)=>{switch(s){case so.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case so.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},no=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(ro=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',ro.Q_144P='144p',ro.Q_240P='240p',ro.Q_360P='360p',ro.Q_480P='480p',ro.Q_720P='720p',ro.Q_1080P='1080p',ro.Q_1440P='1440p',ro.Q_2160P='2160p',ro.Q_4320P='4320p';const lo={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},uo=(t,e)=>lo[t].height>lo[e].height,ho=(t,e)=>lo[t].height<lo[e].height,co=Object.keys(lo).sort(((t,e)=>ho(t,e)?-1:1)),po=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return co.find((t=>{const e=lo[t];return e.width>=s&&e.height>=i}))},mo=t=>t===exports.VideoQuality.INVARIANT;class fo{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var bo;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(bo||(bo={}));class So{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new fo(bo.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==a?void 0:a.to)===exports.PlaybackState.PAUSED||r.state!==u.Requested||e===bo.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case bo.PLAYING:break;case bo.PAUSED:case bo.READY:this.videoState.startTransitionTo(bo.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case bo.STOPPED:this.videoState.startTransitionTo(bo.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case bo.PLAYING:this.videoState.startTransitionTo(bo.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case bo.PAUSED:break;case bo.READY:this.videoState.startTransitionTo(bo.PAUSED),this.videoState.setState(bo.PAUSED);break;case bo.STOPPED:this.videoState.startTransitionTo(bo.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(r.position)}else e!==bo.STOPPED&&(this.videoState.startTransitionTo(bo.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===u.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,a=this.params.output.isBuffering$.getValue(),r=s===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),no(this.params.desiredState.playbackState,exports.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:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(bo.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(bo.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:u.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==bo.PAUSED&&t!==bo.PLAYING||(this.videoState.setState(bo.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==bo.PLAYING&&t!==bo.PAUSED||(this.videoState.setState(bo.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===bo.READY&&this.videoState.setState(bo.READY)}handleRemoteStop(){this.videoState.getState()!==bo.STOPPED&&this.videoState.setState(bo.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),a={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};a.volume===s.volume&&a.muted==a.muted||this.params.output.volume$.next(a)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(e){var i;const s=this.params.source;let a,r,o;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const n=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:ho(t,e)?1:-1))[0];t.assertNonNullable(n);const l=i[n];t.assertNonNullable(l),a=l,r='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),a=oo(i.url),r='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const e='Unsupported format for Chromecast',i=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:t.ErrorCategory.VIDEO_PIPELINE,message:e,thrown:i}),i}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}const n=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:a,r);n.contentUrl=a,n.streamType=o,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:l,subtitle:u}=this.params.meta;return t.isNonNullable(l)&&(n.metadata.title=l),t.isNonNullable(u)&&(n.metadata.subtitle=u),n}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===u.Applying||i.state===u.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===u.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(e=>{const i=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:i}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:t.ErrorCategory.VIDEO_PIPELINE,message:i,thrown:e})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}class vo{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class go extends vo{constructor(){super(),this.listeners||vo.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class yo{constructor(){Object.defineProperty(this,'signal',{value:new go,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function To(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(yo.prototype[Symbol.toStringTag]='AbortController',go.prototype[Symbol.toStringTag]='AbortSignal');const Eo=To({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ko=Eo?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=t;if(!To({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const o=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,o(t,e)])}return o(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wo=Eo?ko.fetch:window.fetch;Eo?ko.Request:window.Request;const Po=Eo?yo:window.AbortController,$o=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Ao{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=$o(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),a=this.activeRequests.get(i.url);s&&a&&a.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,i){const s=i.map($o),a=s[0][0];let r=s[0][1];for(let t=1;t<s.length&&r<this.params.minDataSize;t++){const e=s[t][1];e-a<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===a?Math.max(r,a+this.params.minInitSize):Math.max(r,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append('bytes',`${a}-${r}`);const n=o.toString(),l=new Po,u=l.signal,d={url:e,from:a,to:r,loaded:0,data:null,abortController:l};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const h=e=>{var i,s;throw null===(s=(i=this.params).onError)||void 0===s||s.call(i,{id:'BigRequestParsing',category:t.ErrorCategory.PARSER,message:'Error parsing response data',thrown:e}),e};return wo(n,{signal:u}).then((t=>{var e,i,s;if(d.response=t,!t.ok||!t.body)return void this.onBigRequestError(d);const[o,n]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,n);const l=o.getReader(),u=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10)||r-a+1;d.data=new ArrayBuffer(u);const c=new Uint8Array(d.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(d):e&&(c.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),await(null==l?void 0:l.read().then(p,Ao.suppressStreamErrors).catch(h)))};null==l||l.read().then(p,Ao.suppressStreamErrors).catch(h)}),Ao.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){var o,n,l,u,d,h,c,p;if(!this.activeRequests.has(t)||!a)return;const m=null!==(o=this.dashJsRequestQueue.get(t))&&void 0!==o?o:[];for(const o of m){const{request:m}=o,[f,b]=$o(m),S=f>=e&&b<=e+s,v=e>=f&&e+s<b,g=a.slice(f-e,Math.min(b-e+1,s));if((S||v)&&(m.requestStartDate=null!==(n=m.requestStartDate)&&void 0!==n?n:new Date,m.firstByteDate=null!==(l=m.firstByteDate)&&void 0!==l?l:new Date,m.bytesLoaded=g.byteLength,m.bytesTotal=i-e),S){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==o))),null===(d=o.success)||void 0===d||d.call(o,g,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(h=this.dashMetrics)||void 0===h||h.addHttpRequest(m,t,null!==(c=null==r?void 0:r.status)&&void 0!==c?c:200,e,[])}else v&&(null===(p=o.progress)||void 0===p||p.call(o,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:i,to:s},a){var r,o,n,l;if(null===(o=(r=this.params).onError)||void 0===o||o.call(r,{id:'BigRequest',category:t.ErrorCategory.NETWORK,message:'Download error',thrown:a}),!this.activeRequests.has(e))return;const u=null!==(n=this.dashJsRequestQueue.get(e))&&void 0!==n?n:[];for(const t of u){const[e,r]=$o(t.request);(e>=i&&e<s||r>i&&r<=s)&&(null===(l=null==t?void 0:t.error)||void 0===l||l.call(t,t.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:t,from:e,to:i}){var s,a;if(!this.activeRequests.has(t))return;const r=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of r){const[s,r]=$o(t.request);(s>=e&&s<i||r>e&&r<=i)&&(null===(a=null==t?void 0:t.abort)||void 0===a||a.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class xo{constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(xo.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;xo.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const No=(t,e)=>{const i=new Ao(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new xo(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var Ro=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&(null==e||e())}}}),!0)},Do=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject,a=new t.ValueSubject(void 0),r=new t.ValueSubject(void 0);let o=NaN,n=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,l=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const l=e.onload,u=e.progress;e.onload=function(...e){return(e=>{var s,o,n,l,u;const d=ao(e.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in d||'x-playback-duration-millis'in d){const a=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),r=parseInt(null!==(o=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==o?o:'',10),l=null!==(n=null!=r?r:1e3*a)&&void 0!==n?n:NaN;t.isNonNullable(l)&&!isNaN(l)&&i.next(l)}const h=null!==(l=d['x-delivery-type'])&&void 0!==l?l:exports.HttpConnectionType.HTTP1,c=null!==(u={1:!0,0:!1}[d['x-reused']])&&void 0!==u?u:void 0;a.next(h),r.next(c)})(this),l(...e)},e.progress=function(...t){return this.readyState>=2&&!n&&(n=!0,s.next(Date.now()-o)),u(...t)},o=Date.now(),n=!1}return l(e)}}}),!0),{playbackDuration$:i,ping$:s,connectionReused$:r,connectionType$:a}},Co=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},_o=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const Io=(e,i,s,{equal:a=((t,e)=>t===e),changed$:r,onError:o}={})=>{const n=e.getState(),l=i(),u=t.isNullable(r),d=new t.Subscription;return r&&d.add(r.subscribe((t=>{const i=e.getState();a(t,i)&&e.setState(t)}),o)),a(l,n)||(s(n),u&&e.setState(n)),d.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),u&&e.setState(t.to)}),o)),d},Lo=(e,i,s)=>Io(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Oo=(e,i,s,a)=>Io(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:a}),Bo=(e,i,s,a)=>Io(i,(()=>e.playbackRate),(i=>{t.isNonNullable(i)&&(e.playbackRate=i)}),{changed$:s,onError:a}),Mo=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class Vo{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const a=e=>{this.error$.next({id:'TextTracksManager',category:t.ErrorCategory.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:e})};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(Io(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(Io(i.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(Io(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const a=t=>{var e,i,s,r,o;const n=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;n&&n.length&&(this.applyCueSettings(null!==(r=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==r?r:null),null===(o=t.target)||void 0===o||o.removeEventListener('cuechange',a))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',a)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(Vo.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&Mo(i,e)?i.mode='showing':i.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var Fo=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),e.setAttribute('poster','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='),t.appendChild(e),e};class Uo{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(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var qo=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class jo{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,o=a>=t&&a<e;r&&o||(r?i(e,a):o?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var Ho=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const o=t.start(r),n=t.end(r);if(o<=e&&e<=n){if(s=o,a=n,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const Go=e=>{const i=i=>t.fromEvent(e,i).pipe(t.mapTo(void 0)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((t=>'ended'===t.type?e.readyState<2:e.readyState<3)),t.filterChanged()),a=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>Ho(e.buffered,e.currentTime)))),r=qo()?t.combine({play:i('play').pipe(t.once()),playing:i('playing')}).pipe(t.mapTo(void 0)):i('playing'),o=t.fromEvent(e,'volumechange').pipe(t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'ratechange').pipe(t.map((()=>e.playbackRate))),l=t.fromEvent(e,'error').pipe(t.filter((()=>Boolean(e.error||e.played.length))),t.map((()=>{var i;const s=e.error;return{id:s?`MediaError#${s.code}`:'HtmlVideoError',category:t.ErrorCategory.VIDEO_PIPELINE,message:s?s.message:'Error event from HTML video element',thrown:null!==(i=e.error)&&void 0!==i?i:void 0}}))),u=t.fromEvent(e,'timeupdate').pipe(t.map((()=>e.currentTime))),d=new t.Subject;let h;return u.subscribe((i=>{e.loop&&t.isNonNullable(h)&&t.isNonNullable(i)&&h>=e.duration-.3&&i<=.3&&d.next(h),h=i})),{playing$:r,pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:d,error$:l,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:u,durationChange$:t.fromEvent(e,'durationchange').pipe(t.map((()=>e.duration))),isBuffering$:s,currentBuffer$:a,volumeState$:o,playbackRateState$:n}},Yo=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Qo=te,zo=ys,Wo=ps;is({target:'Array',proto:!0},{at:function(t){var e=Qo(this),i=zo(e),s=Wo(t),a=s>=0?s:i+s;return a<0||a>=i?void 0:e[a]}});var Jo=Tt('Array','at');let Xo=!1,Ko={};const Zo=t=>{t(Ko)},tn=(t,e)=>{var i;Xo&&(Ko.meta=null!==(i=Ko.meta)&&void 0!==i?i:{},Ko.meta[t]=e)};class en{constructor(t){this.name=t}next(t){var e,i;if(!Xo)return;Ko.series=null!==(e=Ko.series)&&void 0!==e?e:{};const s=null!==(i=Ko.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Ko.series[this.name]=s}}const sn=new en('best_bitrate');class an{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const rn=(e,{container:i,throughput:s,tuning:a,limits:r,reserve:o=0,forwardBufferHealth:n,playbackRate:l,current:u,history:d})=>{var h,c,p,m;const f=a.usePixelRatio&&null!==(h=window.devicePixelRatio)&&void 0!==h?h:1,b=a.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*a.containerSizeFactor,height:i.height*f*a.containerSizeFactor},S=b&&po(b),v=a.considerPlaybackRate&&t.isNonNullable(l)?l:1,g=e.filter((t=>!mo(t.quality))).sort(((t,e)=>uo(t.quality,e.quality)?-1:1)),y=null===(c=Jo(g,-1))||void 0===c?void 0:c.quality,T=null===(p=Jo(g,0))||void 0===p?void 0:p.quality,E=t.isNullable(r)||t.isNonNullable(r.min)&&t.isNonNullable(r.max)&&ho(r.max,r.min)||t.isNonNullable(r.min)&&T&&uo(r.min,T)||t.isNonNullable(r.max)&&y&&ho(r.max,y),k=v*(w=null!=n?n:.5,P=a.bitrateFactorAtEmptyBuffer,$=a.bitrateFactorAtFullBuffer,(P-$)*Math.pow(2,-10*w)+$);var w,P,$;const A=g.filter((e=>{const i=!S||ho(e.quality,S),l=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-o>=e.bitrate*k,d=a.lazyQualitySwitch&&t.isNonNullable(a.minBufferToSwitchUp)&&u&&!mo(u.quality)&&(null!=n?n:0)<a.minBufferToSwitchUp&&uo(e.quality,u.quality),h=E||(t.isNullable(r.max)||(c=e.quality,p=r.max,lo[c].height<=lo[p].height))&&(t.isNullable(r.min)||((t,e)=>lo[t].height>=lo[e].height)(e.quality,r.min));var c,p;return i&&l&&!d&&h}))[0];A&&A.bitrate&&sn.next(A.bitrate);const x=null!==(m=null!=A?A:g[Math.ceil((g.length-1)/2)])&&void 0!==m?m:e[0],N=x&&d&&d.history[x.id]&&t.now()-d.history[x.id]<=a.trackCooldown&&(!d.last||x.id!==d.last.id);if((null==x?void 0:x.id)&&d&&!N&&d.recordSelection(x),N&&(null==d?void 0:d.last)){const t=d.last;return null==d||d.recordSwitch(t),t}return null==d||d.recordSwitch(x),x};var on=t=>new URL(t).hostname;const nn=(e,i=300)=>new t.Observable((a=>{const{width:r,height:o}=e.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,r;i.contentBoxSize&&i.contentBoxSize[0]?(r=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,r=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(r)&&a.next({width:s,height:r})}),i));return n.observe(e),()=>n.disconnect()})),ln={};var un;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(un||(un={}));const dn=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class hn{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(un.DOWNLOADING_LIB),this.textTracksManager=new Vo,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new Uo,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==un.DOWNLOADING_LIB&&e!==un.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===u.Requested&&e!==un.STOPPED&&i!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case exports.PlaybackState.STOPPED:switch(e){case un.STOPPED:break;case un.PLAYING:case un.PAUSED:case un.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case un.PLAYING:break;case un.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case un.READY:this.play();break;case un.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case un.PLAYING:this.pause(),this.liveOffset.pause();break;case un.PAUSED:break;case un.READY:this.videoState.setState(un.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case un.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const s=i=>{var s;e||this.params.output.error$.next({id:'timeout'===i?'DashJSTimedOut':'DashJSLoadingError',category:t.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${null===(s=null==i?void 0:i.toString)||void 0===s?void 0:s.call(i)}`,thrown:i}),e=!0},a=window.setTimeout((()=>s('timeout')),5e3);Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(ln.MediaPlayer=t.MediaPlayer,ln.Debug=t.Debug,this.init())}),s).finally((()=>{window.clearTimeout(a),e=!0}))}init(){t.assertNonNullable(ln.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(ln.Debug,'dashjs not loaded'),this.player=ln.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Yo(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=No(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&_o(this.player),Ro(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Co})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(un.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashIFProvider',category:t.ErrorCategory.WTF,message:'DashIFProvider internal logic error',thrown:i})},a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(nn(this.video),this.elementSize$),a(dn(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),a(dn(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const r=dn(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));r.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===un.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Io(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Io(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),a(dn(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),a(dn(this.player,'fragmentLoadingStarted'),(({mediaType:t,request:{url:i}})=>{var s,a;const r=this.player.getDashMetrics(),o=r.getLatestFragmentRequestHeaderValueByID(t,'X-Reused'),n=null!==(s=r.getLatestFragmentRequestHeaderValueByID(t,'X-Delivery-Type'))&&void 0!==s?s:exports.HttpConnectionType.HTTP1,l=null!==(a={1:!0,0:!1}[o])&&void 0!==a?a:void 0;this.params.output.httpConnectionType$.next(n),this.params.output.httpConnectionReused$.next(l),e.hostname$.next(on(i))})),a(dn(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=po(t),s=t.bitrate/1e3,o={width:t.width,height:t.height},n=this.frameRatesByFrameHeight[t.height];if(i){const l={id:e,quality:i,bitrate:s,size:o,fps:n};this.videoTracks.push({track:l,bitrateInfo:t}),t.qualityIndex===a&&(r=l)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&e.currentVideoTrack$.next(r),this.videoState.setState(un.STREAM_INITIALIZED),this.videoState.startTransitionTo(un.READY)})),a(dn(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=rn(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const o=dn(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));a(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:o}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(o.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),a(dn(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),a(dn(this.player,'playbackEnded'),e.endedEvent$),a(dn(this.player,'playbackProgress').pipe(t.map((()=>Ho(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),a(dn(this.player,'playbackPlaying'),(()=>{this.videoState.setState(un.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)})),a(dn(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(un.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(dn(this.player,'playbackPaused'),(()=>{this.videoState.setState(un.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)})),a(dn(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===un.READY&&this.videoState.setState(un.READY)})),a(this.isLive$,e.isLive$),a(nn(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:l,connectionType$:u,connectionReused$:d}=Do(this.player);a(u,this.params.output.httpConnectionType$),a(d,this.params.output.httpConnectionReused$),a(n,this.maxSeekBackTime$),a(l.pipe(t.once()),e.firstBytesEvent$),a(dn(this.player,'canPlay'),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(o.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(dn(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{this.subscription.add(dn(this.player,'playbackPlaying').pipe(t.once(),t.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))}),s)),this.subscription.add(Lo(this.video,i.isLooped,s));const{volumeState$:h,looped$:c,playbackRateState$:p}=Go(this.video);this.subscription.add(Oo(this.video,i.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(c.subscribe(e.loopedEvent$)),this.subscription.add(Bo(this.video,i.playbackRate,p,s))}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.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(un.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(un.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=oo(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,so.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(un.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(un.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var cn=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},pn=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function mn(){return t.now()}function fn(t){return mn()-t}function bn(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Sn(e,i,s,a){const r=window.XMLHttpRequest;let o,n,l,u,d,h=!1,c=0,p=!1,m='arraybuffer',f=7e3,b=2e3,S=()=>{if(h)return;t.assertNonNullable(u);const e=fn(u);let i;if(e<b)return i=b-e,void setTimeout(S,i);b*=2,b>f&&(b=f),n&&n.abort(),n=new r,g()};const v=()=>{if(!h){if(--c>=0)return S(),void(a&&a());h=!0,d&&d(),s&&s()}},g=()=>{u=mn(),n=new r,n.open('get',e);let s,a=0,c=0;const f=()=>(t.assertNonNullable(u),Math.max(u,Math.max(s||0,c||0)));if(o&&n.addEventListener('progress',(t=>{const e=mn();o.updateChunk&&t.loaded>a&&(o.updateChunk(f(),t.loaded-a),a=t.loaded,s=e)})),l&&(n.timeout=l,n.addEventListener('timeout',(()=>v()))),n.addEventListener('load',(()=>{if(h)return;t.assertNonNullable(n);const e=n.status;if(e>=200&&e<300){if(n.response.byteLength&&o){const t=n.response.byteLength-a;t&&o.updateChunk&&o.updateChunk(f(),t)}d&&d(),n&&i(n.response)}else v()})),n.addEventListener('error',(()=>{v()})),p){const e=()=>{t.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(c=mn(),n.removeEventListener('readystatechange',e))};n.addEventListener('readystatechange',e)}return n.responseType=m,n.send(),y},y={withBitrateReporting:t=>(o=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(c=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(b=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(l=t,y),withFinally:t=>(d=t,y),send:g,abort:()=>{n&&(n.abort(),n=void 0),h=!0,d&&d()}};return y}class vn{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const o=t.bytes*a/r;s+=o,t.start=e,t.bytes-=o}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class gn{constructor(t,e,i,s,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=mn(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=Sn(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=mn()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=mn()}_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 t=this._getParallelRequestCount(),e=mn();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class yn{constructor(t){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=t,this.chunkRateEstimator=new vn(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=bn(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}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(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}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(t){this.manifestUrl=t,this.urlResolver=bn(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(()=>{var i;Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${null===(i=t.error)||void 0===i?void 0:i.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new gn(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:a}=this.params;let r=!1,o=null,n=null,l=null,u=null,d=!1;const h=()=>{const t=r&&(!d||d===this.rep);return t||i('Not running!'),t},c=(t,e,i)=>{l&&l.abort(),l=Sn(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{l=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==n||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=mn()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const a=this.bufferStates[i];t=Math.min(t,a.buf),a.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},S=e=>{let s;const r=()=>s&&s.start?s.start.length:0,o=t=>s.start[t]/1e3,n=t=>s.dur[t]/1e3,l=t=>s.fragIndex+t,d=(t,e)=>({chunkIdx:l(t),startTS:o(t),dur:n(t),discontinuity:e}),c=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=s.dur.length-1;for(;r>=0&&(a-=s.dur[r],!(a<=0));--r);t=Math.min(r,s.dur.length-1-i),t=Math.max(t,0)}return d(t,!0)},p=(t,e,i)=>{u&&u.abort(),u=Sn(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(i,n)=>{p(e,(e=>{if(!h())return;s=e;const l=Boolean(s.lowLatency);l!==this.lowLatency&&f(l);let u=0;for(let t=0;t<s.dur.length;++t)u+=s.dur[t];u>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/s.dur.length)),a({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=r();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(o(t)>e)return d(t);return c()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=r(),a=t?t.chunkIdx+1:0,o=a-s.fragIndex;if(!(e<=0)){if(!t||o<0||o-e>10)return i(`Resync: offset=${o} bChunks=${e} chunk=`+JSON.stringify(t)),c();if(!(o>=e))return d(a-s.fragIndex,!1)}}}},v=()=>{r=!1,n&&n.abort(),l&&l.abort(),u&&u.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:i=>{const{videoElement:s,logger:a}=this.params;let n,l,d,m,f,g,y,T=S(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=mn(),s=Math.min(1e4,e-i);E=i;const a=()=>{u||h()&&T.seek((()=>{h()&&(E=mn(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():a()}),s):a()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(d);if(i){if(d&&i.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(v(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!h()||!this.sourceBuffer)return;let i,r,o;const n=i=>{window.setTimeout((()=>{h()&&P(t,e)}),i)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const l=mn(),u=s.currentTime;!this.paused&&s.buffered.length>1&&g===u&&l-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,y=l);const d=this._getBufferSizeSec();if(d>30)a(`Buffered ${d} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:l,buf:d}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(i=this.sourceBuffer.buffered.start(0),r=u,r-i>4&&this.sourceBuffer.remove(i,r-3)),n(1e3)}}},$=()=>{l&&n&&(a([`Appending chunk, sz=${l.byteLength}:`,JSON.stringify(d)]),P(l,(function(){l=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{h()&&p(A(t),((e,i)=>{if(h()){if(i/=1e3,l=e,d=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{h()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},R=t=>{h()&&(e.cachedHeader=t,P(t,(()=>{n=!0,$()})))};r=!0,T.seek((e=>{h()&&(E=mn(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(d=e,w())):k())}),i),e.cachedHeader?R(e.cachedHeader):c(e.headerUrl,R,(()=>this._handleNetworkError()))},stop:v,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),t.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=mn();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,o=!0;const n=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(o&&t>a&&fn(r)<3e4)return;i(t)}o=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&n(),i},notifySwitch:t=>{const e=mn();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=Sn(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;pn(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0:t.length)?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var Tn;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Tn||(Tn={}));const En=[Tn.PAUSED,Tn.PLAYING,Tn.READY],kn=[Tn.PAUSED,Tn.PLAYING,Tn.READY];class wn{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(Tn.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Vo,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new Uo,this._dashCb=e=>{var i,s,a,r;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:t.ErrorCategory.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,r=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),a=null!==(s=cn(e.name))&&void 0!==s?s:po(e.video),o=e.bitrate/1e3,n={...e.video};if(!a)continue;const l={id:t,quality:a,bitrate:o,size:n};r.push({track:l,representation:e})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===Tn.MANIFEST_READY&&this.videoState.setState(Tn.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(r=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===r?void 0:r.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a!==exports.PlaybackState.STOPPED){if(!s){if(kn.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested&&En.includes(i))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(i){case Tn.STOPPED:return this.videoState.startTransitionTo(Tn.MANIFEST_READY),void this.dash.attachSource(oo(this.params.source.url));case Tn.MANIFEST_READY:this.videoState.startTransitionTo(Tn.READY),this.prepare();break;case Tn.READY:return void(a===exports.PlaybackState.PAUSED?this.videoState.setState(Tn.PAUSED):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tn.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Tn.PAUSED)}))));case Tn.PLAYING:return void(a===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Tn.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Tn.PAUSED:return void(a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tn.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Tn.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==Tn.STOPPED&&(this.videoState.startTransitionTo(Tn.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Tn.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=i=>{e.output.error$.next({id:'DashLiveProvider',category:t.ErrorCategory.WTF,message:'DashLiveProvider internal logic error',thrown:i})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fo(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.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Go(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Tn.READY&&this.videoState.setState(Tn.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(Tn.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===u.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Tn.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(Lo(this.video,this.params.desiredState.isLooped,i)).add(Oo(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(Bo(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,i)).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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&lo[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case Tn.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Tn.MANIFEST_READY:case Tn.READY:break;case Tn.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Tn.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new yn({videoElement:this.video,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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,a,r,o;const n=this.representations$.getValue(),l=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),u=null!==(a=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==a?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&t.isNonNullable(l)?l:null===(r=rn(n.map((({track:t})=>t)),{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()}))||void 0===r?void 0:r.id,h=null===(o=n.find((({track:t})=>t.id===d)))||void 0===o?void 0:o.representation;t.assertNonNullable(h,'Representations missing'),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(d),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(oo(this.params.source.url,i))}}var Pn=t=>{var e,i;const s=t.get('X-Delivery-Type'),a=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===a?void 0:null!==(i={1:!0,0:!1}[a])&&void 0!==i?i:void 0}},$n=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class An{constructor(t,e=[],i,s,a,r){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let e=!1;this._xhr.onreadystatechange=()=>{var i,s,a,r,o,n,l,u;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(a=this._xhr)||void 0===a?void 0:a.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=ao(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(o=this._headersCb)||void 0===o||o.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(l=this._progressCb)||void 0===l||l.call(this,this._xhr.response))}catch(t){throw null===(u=this._errorCb)||void 0===u||u.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class xn{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,o){this.abort((()=>{let n=0;const l=Date.now();let u=0,d=0,h=0;const c=t=>{s(xn._str2ua(t.substr(n))),n=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Co(p)),this._lastXhr=new An(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-l;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==a||a()}),(t=>{if(t.length-n>o&&c(t),0===d)return void(d=Date.now());h=t.length-u;const e=Date.now()-d;h>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:h,duration:e,speed:8*h/(e/1e3)}),h=0,u=t.length,d=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=xn._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Nn{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=Co(i)),new An(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],o=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,n,l,u,d,h,c,p,m,f,b,S,v,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&a(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&a(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const a=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,r=(i?i+'/':'')+(null===(d=null===(u=null===(l=null===(n=t.getElementsByTagName('BaseURL'))||void 0===n?void 0:n[0])||void 0===l?void 0:l.childNodes)||void 0===u?void 0:u[0])||void 0===d?void 0:d.data),c=null!==(h=e.getAttribute('lang'))&&void 0!==h?h:void 0;r&&o.push({id:a,url:r,language:c})}return}const N=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const C=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=C?Yo(C):void 0,r.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(b=t.attributes.getNamedItem('height'))||void 0===b?void 0:b.value),bandwidth:N,baseURL:R,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(v=null===(S=t.attributes.getNamedItem('codecs'))||void 0===S?void 0:S.value)&&void 0!==v?v:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:D,bufferSize:.1*N/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w:void 0})})),r.length?(this._representations=r,o.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let o=a.getUint32(s,!1),n=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const l=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<l;e+=1){const e=n+(2147483647&a.getUint32(s,!1)),i=o+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:o/r,toTime:i/r,fromOffset:n,toOffset:e-1}),n=e,o=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}o()}),250)},n=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new xn({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener('sourceopen',n),i.removeEventListener('webkitsourceopen',n)};i.addEventListener('sourceopen',n,!1),i.addEventListener('webkitsourceopen',n,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const a=i[e];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Rn;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Rn||(Rn={}));const Dn=[Rn.PAUSED,Rn.PLAYING];class Cn{constructor(e){this.videoState=new fo(Rn.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Vo,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const a=[];for(const r of t){const t=null!==(i=null!==(e=r.name)&&void 0!==e?e:r.id)&&void 0!==i?i:r.height.toString(10),o=null!==(s=r.name&&cn(r.name))&&void 0!==s?s:po(r),n=r.bandwidth/1e3,l={width:r.width,height:r.height},u=r.fps;if(!o)continue;const d={id:t,quality:o,bitrate:n,size:l,fps:u};a.push({track:d,representation:r})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),this.videoState.setState(Rn.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&r.state===u.Requested&&Dn.includes(e)&&this.seek(r.position,r.forcePrecise),e){case Rn.STOPPED:return this.videoState.startTransitionTo(Rn.MANIFEST_LOADED),void this.prepare();case Rn.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Rn.INITIAL_REPRESENTATION_SELECTED);case Rn.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Rn.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Rn.METADATA_LOADED:return this.videoState.startTransitionTo(Rn.READY),void this.dash.updateRefsForCurrentTime();case Rn.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Rn.PLAYING),this.playIfAllowed()));case Rn.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Rn.PAUSED),this.video.pause()):(null==a?void 0:a.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Rn.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Rn.PLAYING),this.playIfAllowed()):(null==a?void 0:a.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Rn.STOPPED&&(this.videoState.startTransitionTo(Rn.STOPPED),this.dash.destroy(),this.video.setAttribute('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(Rn.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fo(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new jo(this.video),this.dash=new Nn({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(e,i,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:i,thrown:s,category:t.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashProvider',category:t.ErrorCategory.WTF,message:'DashProvider internal logic error',thrown:i})},a=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},r=Go(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,s));o(r.timeUpdate$,e.position$),o(r.durationChange$,e.duration$),o(r.ended$,e.endedEvent$),o(r.looped$,e.loopedEvent$),o(r.error$,e.error$),o(r.isBuffering$,e.isBuffering$),o(r.playing$,e.firstFrameEvent$),o(r.canplay$,e.canplay$),this.subscription.add(r.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==u.Applying)&&(this.videoState.getState()===Rn.PLAYING||this.videoState.getState()===Rn.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Bo(this.video,i.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),o(nn(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Rn.READY&&this.videoState.setState(Rn.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Rn.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Rn.METADATA_LOADED)}),s)).add(r.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:e,message:i,thrown:s})=>({id:`DashLite_${e}`,category:t.ErrorCategory.WTF,message:i,thrown:s})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const r=this.currentRepresentation$.getValue(),o=this.representations$.getValue(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),h=a();let c;if(n&&this.params.desiredState.autoVideoTrackSwitching.setState(n.to),!h&&t.isNonNullable(l))c=l;else{const t=$n(this.video.buffered,1e3*this.video.currentTime),s=h?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(t/s,1);c=null===(i=rn(o.map((({track:t})=>t)),{container:d,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:null===(e=o.find((({representation:t})=>t===r)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(c)?null===(s=o.find((({track:t})=>t.id===c)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Rn.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Rn.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?t.height<=e.height:t===e))).subscribe((t=>{const e=$n(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!a())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(on(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Pn(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once(),t.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var _n,In,Ln,On,Bn;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(_n||(_n={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(In||(In={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Ln||(Ln={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(On||(On={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Bn||(Bn={}));var Mn=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const Vn='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var Fn,Un;let qn=!1;try{qn=qo()&&parseInt(null!==(Un=null===(Fn=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Fn?void 0:Fn[1])&&void 0!==Un?Un:'',10)<16}catch(t){console.error(t)}class jn{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var e;try{if(this.currentTask){const t=null===(e=this.currentTask.signal)||void 0===e?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:'BufferTaskQueueUnknown',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:e})}},this.buffer=e,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=qn&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const i=this.queue.shift();if(!i)return;if(null===(e=i.signal)||void 0===e?void 0:e.aborted)return i.callback(!1),void this.pull();this.currentTask=i;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(e){e instanceof DOMException&&'QuotaExceededError'===e.name&&'append'===s?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&'InvalidStateError'===e.name&&'remove'===s||this.error$.next({id:`BufferTaskQueue:${s}`,category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:e}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){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:t.assertNever(i)}}}var Hn,Gn=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Hn||(Hn={}));class Yn{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Po,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=Co(e));const i=yield wo(e,{signal:this.abortAllController.signal}).catch(Qn);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=t.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:i=Hn.HEADER,range:s,onProgress:a,priority:r='auto',signal:o,measureThroughput:n=!0}={}){var l,u,d,h;let c=e;const p=new Headers;if(s)switch(i){case Hn.HEADER:p.append('Range',`${s.from}-${s.to}`);break;case Hn.PARAM:{const t=new URL(c,location.href);t.searchParams.append('bytes',`${s.from}-${s.to}`),c=t.toString();break}default:t.assertNever(i)}this.requestQuic&&(c=Co(c));let m=this.abortAllController.signal;if(o){const e=new Po;if(this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{try{e.abort()}catch(t){Qn(t)}}))),this.abortAllController.signal.aborted||o.aborted)try{e.abort()}catch(t){Qn(t)}m=e.signal}const f=t.now(),b=yield wo(c,{priority:r,headers:p,signal:m}).catch(Qn),S=t.now();if(null===(l=this.throughputEstimator)||void 0===l||l.addRawRtt(S-f),!b)return null;if(!b.ok||!b.body)return Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const v=parseInt(null!==(u=b.headers.get('Content-Length'))&&void 0!==u?u:'',10)||s&&s.to-s.from+1||NaN;if(!v){const e=yield b.arrayBuffer();return null===(d=this.throughputEstimator)||void 0===d||d.addRawSpeed(e.byteLength,t.now()-S),null==a||a(new DataView(e),e.byteLength),e}if(!a&&!n)return b.arrayBuffer();const[g,y]=b.body.tee(),T=g.getReader();n&&(null===(h=this.throughputEstimator)||void 0===h||h.trackStream(y));let E=0;const k=new ArrayBuffer(v),w=new Uint8Array(k),P=new DataView(k);let $=!1;const A=t=>{$=!0,Qn(t)},x=t.abortable(m,async function*({done:e,value:i}){0===E&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted||(e?null==a||a(P,E):i&&(w.set(i,E),E+=i.byteLength,null==a||a(P,E),yield null==T?void 0:T.read().then(x,A)))}.bind(this));return yield null==T?void 0:T.read().then(x,A),$?null:k}.bind(this)),this.fetchByteRangeRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e,i){if(t.type!==Ln.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,o,n=s,l=a,u=!1;t.indexRange&&(r=t.indexRange.from,o=t.indexRange.to,u=a+1===r,u&&(n=Math.min(r,s),l=Math.max(o,a))),n=Math.min(n,0);const d=yield this.fetch(t.url,{rangeMethod:Hn.PARAM,range:{from:n,to:l},priority:i,measureThroughput:!1});if(!d)return null;const h=new DataView(d,s-n,a-n+1);if(!e.validateData(h))throw new Error('Invalid media file');const c=e.parseInit(h);let p;if(u&&void 0!==r&&void 0!==o)p=new DataView(d,r-n,o-r+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:Hn.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(d),segments:m}}.bind(this)),this.fetchTemplateRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e){if(t.type!==Ln.TEMPLATE)return null;const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield this.fetch(i,{priority:e,measureThroughput:!1});if(!s)return null;return{segments:t.segments.map((t=>({...t,status:On.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Pn(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,i,s='auto'){var a,r;const{type:o}=e;switch(o){case Ln.BYTE_RANGE:return null!==(a=await this.fetchByteRangeRepresentation(e,i,s))&&void 0!==a?a:null;case Ln.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(e,s))&&void 0!==r?r:null;default:t.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qn=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},zn=new TextDecoder('ascii'),Wn=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=zn.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},Jn={validateData:t=>'ftyp'===zn.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Wn(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),o=a(),n=a(),l=4294967295&a();let u=o/r*1e3,d=t.byteOffset+t.byteLength+n;for(let t=0;t<l;t++){const t=a(),e=t>>>31,s=t<<1>>>1,o=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;i.push({status:On.NONE,time:{from:u,to:u+n},byte:{from:d,to:d+s-1}}),u+=n,d+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=Wn(a);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Xn,Kn;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(Xn||(Xn={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(Kn||(Kn={}));const Zn={[Xn.EBML]:{type:Kn.Master},[Xn.EBMLVersion]:{type:Kn.UnsignedInteger},[Xn.EBMLReadVersion]:{type:Kn.UnsignedInteger},[Xn.EBMLMaxIDLength]:{type:Kn.UnsignedInteger},[Xn.EBMLMaxSizeLength]:{type:Kn.UnsignedInteger},[Xn.DocType]:{type:Kn.String},[Xn.DocTypeVersion]:{type:Kn.UnsignedInteger},[Xn.DocTypeReadVersion]:{type:Kn.UnsignedInteger},[Xn.Void]:{type:Kn.Binary},[Xn.Segment]:{type:Kn.Master},[Xn.SeekHead]:{type:Kn.Master},[Xn.Seek]:{type:Kn.Master},[Xn.SeekID]:{type:Kn.Binary},[Xn.SeekPosition]:{type:Kn.UnsignedInteger},[Xn.Info]:{type:Kn.Master},[Xn.TimestampScale]:{type:Kn.UnsignedInteger},[Xn.Duration]:{type:Kn.Float},[Xn.Tracks]:{type:Kn.Master},[Xn.Chapters]:{type:Kn.Master},[Xn.Cluster]:{type:Kn.Master},[Xn.Timestamp]:{type:Kn.UnsignedInteger},[Xn.SilentTracks]:{type:Kn.Master},[Xn.SilentTrackNumber]:{type:Kn.UnsignedInteger},[Xn.Position]:{type:Kn.UnsignedInteger},[Xn.PrevSize]:{type:Kn.UnsignedInteger},[Xn.SimpleBlock]:{type:Kn.Binary},[Xn.BlockGroup]:{type:Kn.Master},[Xn.EncryptedBlock]:{type:Kn.Binary},[Xn.Attachments]:{type:Kn.Master},[Xn.Tags]:{type:Kn.Master},[Xn.Cues]:{type:Kn.Master},[Xn.CuePoint]:{type:Kn.Master},[Xn.CueTime]:{type:Kn.UnsignedInteger},[Xn.CueTrackPositions]:{type:Kn.Master},[Xn.CueTrack]:{type:Kn.UnsignedInteger},[Xn.CueClusterPosition]:{type:Kn.UnsignedInteger},[Xn.CueRelativePosition]:{type:Kn.UnsignedInteger},[Xn.CueDuration]:{type:Kn.UnsignedInteger},[Xn.CueBlockNumber]:{type:Kn.UnsignedInteger},[Xn.CueCodecState]:{type:Kn.UnsignedInteger},[Xn.CueReference]:{type:Kn.Master},[Xn.CueRefTime]:{type:Kn.UnsignedInteger}},tl=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=el(t,i),a=s in Zn,r=a?Zn[s].type:Kn.Binary,o=t.getUint8(i);let n=0;128&o?n=1:64&o?n=2:32&o?n=3:16&o?n=4:8&o?n=5:4&o?n=6:2&o?n=7:1&o&&(n=8);const l=new DataView(t.buffer,t.byteOffset+i+1,n-1),u=((o&255>>n)<<8*(n-1))+el(l),d=i+n;let h;return h=d+u>t.byteLength?new DataView(t.buffer,t.byteOffset+d):new DataView(t.buffer,t.byteOffset+d,u),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:d,tagSize:d+u,value:h,valueSize:u}},el=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},il=(e,i)=>{switch(i){case Kn.SignedInteger:return e.getInt8(0);case Kn.UnsignedInteger:return el(e);case Kn.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Kn.String:return new TextDecoder('ascii').decode(e);case Kn.UTF8:return new TextDecoder('utf-8').decode(e);case Kn.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Kn.Master:case Kn.Binary:return e;default:t.assertNever(i)}},sl=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=tl(s);if(!e(a))return;a.type===Kn.Master&&sl(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},al=[Xn.Info,Xn.SeekHead,Xn.Tracks,Xn.Chapters,Xn.Cluster,Xn.Cues,Xn.Attachments,Xn.Tags],rl=[Xn.Timestamp,Xn.SilentTracks,Xn.SilentTrackNumber,Xn.Position,Xn.PrevSize,Xn.SimpleBlock,Xn.BlockGroup,Xn.EncryptedBlock],ol={validateData:t=>{if(t.getUint32(0)!==Xn.EBML)return!1;let e,i,s;const a=tl(t);return sl(a.value,(({tag:t,type:a,value:r})=>(t===Xn.EBMLReadVersion?e=il(r,a):t===Xn.DocType?i=il(r,a):t===Xn.DocTypeReadVersion&&(s=il(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,a,r,o,n,l=!1,u=!1,d=!1;return sl(e,(({tag:t,type:e,value:h,valueSize:c})=>{if(t===Xn.SeekID){const t=il(h,e);n=el(t)}else t!==Xn.SeekPosition&&(n=void 0);return t===Xn.Segment?(i=h.byteOffset,s=h.byteOffset+c):t===Xn.Info?l=!0:t===Xn.SeekHead?u=!0:t===Xn.TimestampScale?a=il(h,e):t===Xn.Duration?r=il(h,e):t===Xn.SeekPosition&&n===Xn.Cues?o=il(h,e):l&&u&&al.includes(t)&&(d=!0),!d})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(r,'Failed to parse webm Segment duration'),a=null!=a?a:1e6,{segmentStart:Math.round(i/1e9*a*1e3),segmentEnd:Math.round(s/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,a=!1;const r=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),o=[];let n;return sl(e,(({tag:t,type:e,value:i})=>{switch(t){case Xn.Cues:s=!0;break;case Xn.CuePoint:n&&r(n)&&o.push(n),n={};break;case Xn.CueTime:n&&(n.time=il(i,e));break;case Xn.CueTrackPositions:break;case Xn.CueClusterPosition:n&&(n.position=il(i,e));break;default:s&&al.includes(t)&&(a=!0)}return!(s&&a)})),n&&r(n)&&o.push(n),o.map(((t,e)=>{const{time:s,position:a}=t,r=o[e+1];return{status:On.NONE,time:{from:s,to:r?r.time:i.segmentDuration},byte:{from:i.segmentStart+a,to:r?i.segmentStart+r.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{sl(t,(s=>s.tag===Xn.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!rl.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Xn.SimpleBlock,Xn.BlockGroup,Xn.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class nl{constructor(e,i,s,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Po,this.destroyAbortController=new Po,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=t.abortable(this.destroyAbortController.signal,async function*(e){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new jn(this.sourceBuffer),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',category:t.ErrorCategory.WTF,message:'Error when trying to clear segments ejected by browser',thrown:e})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:t.ErrorCategory.VIDEO_PIPELINE,message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>{if(!this.sourceBuffer)return;const e=Math.min(this.bufferLimit,Gn(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(i,'high',!0);const s=this.initData.get(i.id),a=this.segments.get(i.id);if(t.assertNonNullable(s,'No init buffer for starting representation'),t.assertNonNullable(a,'No segments for starting representation'),!(s instanceof ArrayBuffer))return;let r=0;for(const t of a)t.time.from-r>0&&this.gaps.push({representation:i.id,from:r,to:t.time.from}),r=t.time.to;t.isNonNullable(i.duration)&&i.duration-r>0&&this.gaps.push({representation:i.id,from:r,to:i.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)?yield this.loadInit(i,'high',!1):s instanceof Promise&&(yield s),s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();t.isNonNullable(a)&&this.maintain(a)}.bind(this)),this.fetcher=r,this.tuning=o,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=s,s){case Bn.MP4:this.containerParser=Jn;break;case Bn.WEBM:this.containerParser=ol;break;default:t.assertNever(s)}this.initData=new Map(a.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(a.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Po,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find((t=>e>=t.time.from&&e<t.time.to));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=$n(this.sourceBuffer.buffered,e),s=a?a.time.to+t:-1/0;a&&i>=a.time.to-e+t&&(r=s)}if(isFinite(this.bufferLimit)&&Gn(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),a&&a.status!==On.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,i.segmentReference.type,r),o.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))t='high';else{const e=Jo(o,0);e&&e.time.from-a.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(o,i,t)}!this.allInitsLoaded&&a&&a.status===On.FED&&!o.length&&$n(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const n=Jo(s,-1);n&&n.status===On.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===n))}findSegmentStartTime(t){var e,i,s;const a=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!a)return;const r=this.segments.get(a);if(!r)return;const o=r.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==o?void 0:o.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===On.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Ln.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const o=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==On.NONE&&e.status!==On.PARTIALLY_EJECTED)break;o.push(e)}return o}async loadSegments(e,i,s='auto'){if(!e.length)return;let a,r,o=e;const{type:n}=i.segmentReference;switch(n){case Ln.BYTE_RANGE:a=i.segmentReference.url,r={from:Jo(e,0).byte.from,to:Jo(e,-1).byte.to};break;case Ln.TEMPLATE:{const t=Jo(e,0);a=new URL(t.url,i.segmentReference.baseUrl).toString(),o=[t];break}default:t.assertNever(n)}for(const t of o)t.status=On.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:i.id});const{signal:l}=this.downloadAbortController;if(this.failedDownloads&&(await t.abortable(l,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))(),l.aborted))for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.fetcher.fetch(a,{rangeMethod:Hn.PARAM,range:r,onProgress:(e,s)=>{if(!l.aborted)try{this.onSomeDataLoaded(e,i.id,r?r.from:0,s,l)}catch(e){this.error$.next({id:'SegmentFeeding',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:e})}},signal:l,priority:s}).then((()=>this.failedDownloads=0),(t=>{for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.onSegmentDownloadError(t)}))}onSegmentDownloadError(e){var i;let s=!1;const a=this.getCurrentPosition();if(this.sourceBuffer&&t.isNonNullable(a)){s=$n(null===(i=this.sourceBuffer)||void 0===i?void 0:i.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',category:t.ErrorCategory.NETWORK,message:'Error when fetching segments',thrown:e})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},o=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=On.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===On.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=On.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},n=this.representations.get(e);if(!n)return;const l=n.segmentReference.type,u=t.byteLength;for(const n of this.activeSegments){const{segment:d}=n,h=l===Ln.BYTE_RANGE,c=h?d.byte.to-d.byte.from+1:u;if(n.representationId!==e)continue;if(!(!h||d.byte.from>=i&&d.byte.to<i+t.byteLength))continue;if(a.aborted){r(n);continue}const p=h?d.byte.from-i:0,m=p<s,f=(h?d.byte.to-i:t.byteLength)<=s;if(d.status===On.DOWNLOADING&&m&&f){d.status=On.DOWNLOADED,this.activeSegments.delete(n);const e=new DataView(t.buffer,t.byteOffset+p,c);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?o(n):r(n)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(n.loadedBytes=Math.min(c,s-p),n.loadedBytes>n.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+n.feedingBytes,n.loadedBytes-n.feedingBytes),i=n.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(d.status=On.PARTIALLY_FED,n.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{if(a.aborted)r(n);else if(t)n.fedBytes+=i.byteLength,n.fedBytes===c&&o(n);else{if(n.feedingBytes<c)return;r(n)}})))}}}abortSegment(t){t.status===On.PARTIALLY_FED||t.status===On.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=On.NONE)),t.status=On.PARTIALLY_EJECTED):t.status=On.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||(e=a),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=Vn((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(e,i='auto',s=!1){const a=this.tuning.dash.useFetchPriorityHints?i:'auto',r=(!s&&this.failedDownloads>0?t.abortable(this.destroyAbortController.signal,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a))).then((t=>{if(!t)return;const{dataView:i,segments:s}=t,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(e.id,a),this.segments.set(e.id,s)})).then((()=>this.failedDownloads=0),(i=>{this.initData.set(e.id,null),s&&this.error$.next({id:'LoadInits',category:t.ErrorCategory.WTF,message:'loadInit threw',thrown:i})}));return this.initData.set(e.id,r),r}async pruneBuffer(e){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let a=0,r=1/0,o=-1/0,n=!1;const l=t=>{var e;r=Math.min(r,t.time.from),o=Math.max(o,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;a+=i};for(const t of s){if(t.time.to>=i||a>=e)break;t.status===On.FED&&l(t)}if(n=isFinite(r)&&isFinite(o),!n){a=0,r=1/0,o=-1/0;for(const t of s){if(t.time.from<i+this.forwardBufferTarget||a>e)break;t.status===On.FED&&l(t)}}if(n=isFinite(r)&&isFinite(o),!n)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),i=1e3*this.sourceBuffer.buffered.end(t);for(const t of s)if(t.status===On.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(i)){r=e,o=i;break}}return n=isFinite(r)&&isFinite(o),!!n&&this.sourceBufferTaskQueue.remove(r,o)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(e,i){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Vn((()=>{try{this.detectGaps(e,i)}catch(e){this.error$.next({id:'GapDetection',category:t.ErrorCategory.WTF,message:'detectGaps threw',thrown:e})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(t)),s=Math.round(1e3*this.sourceBuffer.buffered.end(t));e.push({from:i,to:s})}for(const t of this.segments.values())for(const i of t){const{status:t}=i;if(t!==On.FED&&t!==On.PARTIALLY_EJECTED)continue;const s=Math.floor(i.time.from),a=Math.ceil(i.time.to),r=e.some((t=>t.from-1<=s&&t.to+1>=a)),o=e.some((t=>s>=t.from-1&&s<=t.to+1||a>=t.from-1&&a<=t.to+1));r||(i.status=o?On.PARTIALLY_EJECTED:On.NONE)}}}const ll=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},ul=(e,i)=>{let s=e;s=s.replaceAll('$$','$');const a={RepresentationID:i.representationId,Number:i.segmentNumber,Bandwidth:i.bandwidth,Time:i.segmentTime};for(const[e,i]of Object.entries(a)){const a=new RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,'g');s=s.replaceAll(a,((e,s)=>t.isNullable(i)?e:t.isNullable(s)?i:i.padStart(parseInt(s,10),'0')))}return s},dl=['timeupdate','progress','play','seeked','stalled'];var hl,cl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(hl||(hl={}));class pl{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new fo(hl.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Po,this.initManifest=t.abortable(this.destroyController.signal,async function*(e,i){this.element=e,this.state$.startTransitionTo(hl.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i).catch((e=>this.error$.next({id:'LoadManifest',category:t.ErrorCategory.NETWORK,message:'Failed to load manifest',thrown:e})));if(!s)return null;let a;try{a=((e,i)=>{var s,a,r,o,n,l,u,d,h,c,p,m,f,b,S,v,g,y,T,E,k,w,P,$,A,x,N,R,D,C,_,I,L,O,B;const M={video:[],audio:[],text:[]},V=(new DOMParser).parseFromString(e,'application/xml').children[0],F=V.getElementsByTagName('Period')[0],U=F.children;let q;const j=V.getAttribute('mediaPresentationDuration'),H=F.getAttribute('duration');if(j)q=ll(j);else if(H){const e=ll(H);t.isNonNullable(e)&&(q=e)}let G=0;const Y=null!==(a=null===(s=V.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==a?a:[],Q=Y.includes(In.WEBM_AS_IN_FFMPEG)||Y.includes(In.WEBM_AS_IN_SPEC)?Bn.WEBM:Bn.MP4;for(const t of U){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),a=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==e?void 0:e.split('/')[0],V=null!==(n=null===(o=t.getAttribute('profiles'))||void 0===o?void 0:o.split(','))&&void 0!==n?n:[],F=t.querySelectorAll('Representation');if('text'!==a)for(const r of F){const o=null!==(l=r.getAttribute('mimeType'))&&void 0!==l?l:e,n=null!==(d=null!==(u=r.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==d?d:'',F=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==o?void 0:o.split('/')[0])&&void 0!==c?c:a,U=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],j=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),H=parseInt(null!==(b=r.getAttribute('height'))&&void 0!==b?b:'',10),Q=parseInt(null!==(S=r.getAttribute('bandwidth'))&&void 0!==S?S:'',10)/1e3,z=null!==(v=r.getAttribute('frameRate'))&&void 0!==v?v:'',W=null!==(g=r.getAttribute('quality'))&&void 0!==g?g:void 0,J=z?Yo(z):void 0,X=`${null!==(y=r.getAttribute('id'))&&void 0!==y?y:(G++).toString(10)}@${'video'===F?`${H}p`:'audio'===F?`${Q}Kbps`:n}`,K=null!==(k=null===(E=null===(T=r.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',Z=new URL(K,i).toString(),tt=[...Y,...V,...U];let et;const it=r.querySelector('SegmentBase'),st=r.querySelector('SegmentTemplate');if(it){const t=null!==(P=null===(w=r.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=null===($=r.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[o,n]=a?a.split('-').map((t=>parseInt(t,10))):[],l=a?{from:o,to:n}:void 0;et={type:Ln.BYTE_RANGE,url:Z,initRange:s,indexRange:l}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(A=r.getAttribute('id'))&&void 0!==A?A:void 0,bandwidth:null!==(x=r.getAttribute('bandwidth'))&&void 0!==x?x:void 0},e=parseInt(null!==(N=st.getAttribute('timescale'))&&void 0!==N?N:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),a=null!==(C=parseInt(null!==(D=st.getAttribute('startNumber'))&&void 0!==D?D:'',10))&&void 0!==C?C:1,o=ul(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=null!==(_=st.querySelectorAll('SegmentTimeline S'))&&void 0!==_?_:[],l=[];let u=a,d=0;for(const i of n){const a=1e3*parseInt(null!==(I=i.getAttribute('d'))&&void 0!==I?I:'',10),r=parseInt(null!==(L=i.getAttribute('r'))&&void 0!==L?L:'',10)||0,o=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<r+1;i++){const i=ul(s,{...t,segmentNumber:u.toString(10),segmentTime:o.toString(10)}),r=o?o/e:d;d+=a/e;const n=d;u++,l.push({time:{from:r,to:n},url:i})}}et={type:Ln.TEMPLATE,baseUrl:Z,initUrl:o,segments:l}}}if(!F||!o)continue;const at={video:_n.VIDEO,audio:_n.AUDIO,text:_n.TEXT}[F];at&&M[at].push({id:X,kind:at,segmentReference:et,profiles:tt,duration:q,bitrate:Q,mime:o,codecs:n,width:j,height:H,fps:J,quality:W})}}return{duration:q,container:Q,representations:M}})(null!=s?s:'',i)}catch(e){this.error$.next({id:'ManifestParsing',category:t.ErrorCategory.PARSER,message:'Failed to parse MPD manifest',thrown:e})}if(!a)return null;const r=({mime:t,codecs:i})=>{var s,a,r;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(r=null===(a=window.MediaSource)||void 0===a?void 0:a.isTypeSupported)||void 0===r?void 0:r.call(a,`${t}; codecs="${i}"`)))};return this.manifest={...a,representations:ao(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(hl.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:t.ErrorCategory.PARSER,message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,async function*(e,i){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(hl.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new nl(_n.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new nl(_n.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),r=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:a,someBufferEnded:r}).pipe(t.filter((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var e;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)}))),t.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&t.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(e),this.state$.setState(hl.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...dl.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',category:t.ErrorCategory.WTF,message:'Internal logic error',thrown:e})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&Mn(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(e=>{this.error$.next({id:'GapWatchdog',category:t.ErrorCategory.WTF,message:'Error handling gaps',thrown:e})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Yn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[_n.VIDEO]:this.videoBufferManager,[_n.AUDIO]:this.audioBufferManager,[_n.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(e,i){var s,a,r,o,n;let l;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),l=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(r=null===(a=this.audioBufferManager)||void 0===a?void 0:a.findSegmentStartTime(e))&&void 0!==r?r:e),Mn(this.element.buffered,l)||(this.videoBufferManager.abort(),null===(o=this.audioBufferManager)||void 0===o||o.abort()),this.videoBufferManager.maintain(l),null===(n=this.audioBufferManager)||void 0===n||n.maintain(l),this.element.currentTime=l/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(hl.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=[];for(const i of this.bufferManagers)for(const s of i.gaps)i.playingRepresentation$.getValue()===s.representation&&s.from<=t&&s.to>t&&(1e3*this.element.duration-s.to<this.tuning.endGapTolerance?e.push(1/0):e.push(s.to));if(e.length){const t=Math.max(...e);t===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=t/1e3}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(cl||(cl={}));const ml=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{var o;const n=null!==(o=r?cn(r):void 0)&&void 0!==o?o:po({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},fl=(t,e,i)=>{var s;const a=e.indexOf(i);return null!==(s=Jo(t,Math.round(t.length*a/e.length)))&&void 0!==s?s:Jo(t,-1)};class bl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(cl.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Vo,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new an,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===u.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==cl.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===cl.STOPPED)return this.videoState.startTransitionTo(cl.READY),void this.prepare();switch(e){case cl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(cl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(cl.PLAYING),this.playIfAllowed()));case cl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(cl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case cl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(cl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==cl.STOPPED&&(this.videoState.startTransitionTo(cl.STOPPED),this.player.stop(),this.video.setAttribute('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(cl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Fo(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new pl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=Go(this.video),a=i=>{e.error$.next({id:'DashVKProvider',category:t.ErrorCategory.WTF,message:'DashVKProvider internal logic error',thrown:i})},r=(t,e)=>this.subscription.add(t.subscribe(e,a));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once(),t.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Lo(this.video,i.isLooped,a)),this.subscription.add(Oo(this.video,i.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Bo(this.video,i.playbackRate,s.playbackRateState$,a)),r(nn(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(cl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(cl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===cl.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===hl.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(cl.READY)})));const o=i=>e.error$.next({id:'RepresentationSwitch',category:t.ErrorCategory.WTF,message:'Switching representations threw',thrown:i});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,a,r,n,l,u,d,h;const c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c===hl.NONE||!this.videoTracks.length)return;const m=c===hl.MANIFEST_LOADED&&!p,f=c===hl.REPRESENTATION_SELECTED&&!p,b=i.autoVideoTrackSwitching.getState(),S=i.videoTrack.getState(),v=null===(s=this.videoTracks.find((({track:{id:t}})=>t===S)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=$n(this.video.buffered,1e3*this.video.currentTime),T=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),k=Math.max(v&&!b&&null!==(r=null===(a=this.audioRepresentations.get(v.id))||void 0===a?void 0:a.bitrate)&&void 0!==r?r:0,g&&null!==(l=null===(n=this.audioRepresentations.get(g.id))||void 0===n?void 0:n.bitrate)&&void 0!==l?l:0),w=rn(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=b?null!=w?w:v:null!=v?v:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(b),this.player.setBufferTarget(T)),m){const e=P&&(null===(u=this.videoTracks.find((({track:t})=>t===P)))||void 0===u?void 0:u.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(d=this.audioRepresentations.get(e.id))||void 0===d?void 0:d.id)}else if(f){const t=P&&(null===(h=this.videoTracks.find((({track:t})=>t===P)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(_n.VIDEO,t.id).catch(o),e&&this.player.switchRepresentation(_n.AUDIO,e.id).catch(o)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,a))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=ml(t);if(s){this.videoTracks.push({track:s,representation:t});const a=fl(e,i,t);a&&this.audioRepresentations.set(t.id,a)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(cl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const Sl={};var vl;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(vl||(vl={}));const gl=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class yl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(vl.INITIALIZING),this.textTracksManager=new Vo,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==vl.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===u.Requested&&this.seek(a.position),i){case exports.PlaybackState.STOPPED:switch(e){case vl.STOPPED:break;case vl.READY:case vl.PLAYING:case vl.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case vl.PLAYING:break;case vl.STOPPED:this.prepare();break;case vl.READY:case vl.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case vl.PAUSED:break;case vl.STOPPED:this.prepare();break;case vl.READY:this.videoState.setState(vl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case vl.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(on(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const s=i=>{e||this.params.output.error$.next({id:'timeout'===i?'HlsJsTimeout':'HlsJsLoadError',category:t.ErrorCategory.NETWORK,message:'Failed to load Hls.js',thrown:i}),e=!0},a=window.setTimeout((()=>s('timeout')),5e3);Promise.resolve().then((function(){return i(require('hls.js'))})).then((t=>{e||(Sl.Hls=t.default,Sl.Events=t.default.Events,this.init())}),s).finally((()=>{window.clearTimeout(a),e=!0}))}init(){t.assertNonNullable(Sl.Hls,'hls.js not loaded'),this.hls=new Sl.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(vl.STOPPED)}subscribe(){t.assertNonNullable(Sl.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=e=>{i.error$.next({id:'HlsJsProvider',category:t.ErrorCategory.WTF,message:'HlsJsProvider internal logic error',thrown:e})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,i.position$),r(a.durationChange$,i.duration$),r(a.ended$,i.endedEvent$),r(a.looped$,i.loopedEvent$),r(a.error$,i.error$),r(a.isBuffering$,i.isBuffering$),r(a.currentBuffer$,i.currentBuffer$),r(a.loadStart$,i.firstBytesEvent$),r(a.playing$,i.firstFrameEvent$),r(a.canplay$,i.canplay$),r(a.seeked$,i.seekedEvent$),this.subscription.add(Lo(this.video,e.isLooped,s)),this.subscription.add(Oo(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Bo(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(gl(this.hls,Sl.Events.ERROR).subscribe((e=>{var s;e.fatal&&i.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),category:t.ErrorCategory.WTF,message:`HlsJs fatal ${e.type} ${e.details}, ${null===(s=e.err)||void 0===s?void 0:s.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(vl.PLAYING),no(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(vl.PAUSED),no(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===vl.READY&&this.videoState.setState(vl.READY),this.videoState.getState()===vl.PLAYING&&this.playIfAllowed()}),s)),r(gl(this.hls,Sl.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const a=e.name||e.height.toString(10),{width:r,height:o}=e,n=null!==(s=cn(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:po({width:r,height:o});if(!n)return t;const l=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:a.toString(),quality:n,bitrate:e.bitrate/1e3,size:{width:r,height:o},fps:l};return this.trackLevels.set(a,{track:u,level:e}),t.push(u),t}),[])))),i.availableVideoTracks$),r(gl(this.hls,Sl.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>on(t)))),i.hostname$),this.subscription.add(Io(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const o=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},n=gl(this.hls,Sl.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>o(this.hls.levels[t]))));n.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(Io(e.videoTrack,(()=>{var t;return null===(t=o(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const a=this.hls.levels.indexOf(s),r=this.hls.currentLevel,o=this.hls.levels[r];!o||s.bitrate>o.bitrate?this.hls.nextLevel=a:(this.hls.loadLevel=a,this.hls.loadLevel=a)}),{changed$:n.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const l=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(vl.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(vl.PLAYING);await pn(this.video)||(this.videoState.setState(vl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(vl.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/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.setAttribute('src',''),this.video.load(),this.videoState.setState(vl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var Tl=async t=>{const e=await wo(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const El=t=>{let e=null;if(t.QUALITY&&(e=cn(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=po({width:i,height:s})}return null!=e?e:null},kl=async(t,e=t)=>{var i;const s=await wo(t),a=(await s.text()).split('\n'),r=[];for(let t=0;t<a.length;t++){const s=a[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const o=ao(s[1].split(',').map((t=>t.split('=')))),n=null!==(i=o.QUALITY)&&void 0!==i?i:`stream-${o.BANDWIDTH}`,l=El(o);let u;o.BANDWIDTH&&(u=parseInt(o.BANDWIDTH,10)/1e3||void 0),!u&&o['AVERAGE-BANDWIDTH']&&(u=parseInt(o['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const d=o['FRAME-RATE']?parseFloat(o['FRAME-RATE']):void 0;let h;if(o.RESOLUTION){const[t,e]=o.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(h={width:t,height:e})}const c=new URL(a[++t],e).toString();l&&r.push({id:n,quality:l,url:c,bandwidth:u,size:h,fps:d})}return r};var wl,Pl,$l;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(wl||(wl={}));class Al{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new fo(wl.STOPPED),this.textTracksManager=new Vo,this.manifests$=new t.ValueSubject([]),this.liveOffset=new Uo,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==wl.STOPPED&&(this.videoState.startTransitionTo(wl.STOPPED),this.video.setAttribute('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(wl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===wl.STOPPED)return this.videoState.startTransitionTo(wl.READY),void this.prepare();if(a||r){const t=this.videoState.getState();return this.videoState.setState(wl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(o.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested)return this.videoState.startTransitionTo(wl.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case wl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(wl.PAUSED),this.liveOffset.pause(),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(wl.PLAYING),this.playIfAllowed()));case wl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(wl.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case wl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(wl.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)):this.seek(-this.liveOffset.getTotalOffset())):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case wl.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),kl(oo(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(on(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const l=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===l))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsLiveProvider',category:t.ErrorCategory.WTF,message:'HlsLiveProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,e.endedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(wl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(wl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===wl.READY&&this.videoState.setState(wl.READY),this.videoState.getState()===wl.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(on(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===wl.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===u.Requested&&this.seek(e.position)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{var t,e,i;const s=null===(i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate)||void 0===e?void 0:e.call(t))||void 0===i?void 0:i.getTime();this.manifestStartTime$.next(s||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=oo(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),Tl(i).then((e=>{var s;if(t.isNullable(e)){const e=null!==(s=this.params.source.maxSeekBackTime)&&void 0!==s?s:this.maxSeekBackTime$.getValue();if(t.isNullable(e)||!isFinite(e))try{wo(i).then((t=>t.text())).then((e=>{var s;const a=null===(s=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(e))||void 0===s?void 0:s[1];if(a){const e=new URL(a,i).toString();Tl(e).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(e)}))}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(wl.PAUSED),this.liveOffset.pause(),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Pl||(Pl={}));class xl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(Pl.STOPPED),this.textTracksManager=new Vo,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Pl.STOPPED&&(this.videoState.startTransitionTo(Pl.STOPPED),this.video.setAttribute('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(Pl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===Pl.STOPPED)return this.videoState.startTransitionTo(Pl.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Pl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(o.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested&&this.seek(o.position),e){case Pl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Pl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pl.PLAYING),this.playIfAllowed()));case Pl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Pl.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(on(this.params.source.url)),kl(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const l=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===l))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsProvider',category:t.ErrorCategory.WTF,message:'HlsProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Pl.READY&&this.videoState.setState(Pl.READY),this.videoState.getState()===Pl.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(on(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Pl.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===u.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(Pl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}($l||($l={}));class Nl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo($l.STOPPED),this.trackUrls={},this.textTracksManager=new Vo,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==$l.STOPPED&&(this.videoState.startTransitionTo($l.STOPPED),this.video.setAttribute('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($l.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(e===$l.STOPPED)return this.videoState.startTransitionTo($l.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===u.Requested&&this.seek(r.position),e){case $l.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState($l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($l.PLAYING),this.playIfAllowed()));case $l.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($l.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $l.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($l.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'MpegProvider',category:t.ErrorCategory.WTF,message:'MpegProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState($l.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState($l.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===$l.READY&&this.videoState.setState($l.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===$l.PLAYING&&this.playIfAllowed()}),s)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:a}=this.trackUrls[s];t.assertNonNullable(a,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(a=Co(a)),this.video.setAttribute('src',a),this.video.load(),this.params.output.hostname$.next(on(a))}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState($l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}const Rl=['stun:videostun.mycdn.me:80'],Dl=()=>null;class Cl{constructor(t,e){this.ws=null,this.peerConnection=null,this.serverUrl='',this.streamKey='',this.stream=null,this.signalingType='JOIN',this.retryCount=0,this.externalStartCallback=Dl,this.externalStopCallback=Dl,this.externalErrorCallback=Dl,this.options=this.normalizeOptions(e);const i=t.split('/');this.serverUrl=i.slice(0,i.length-1).join('/'),this.streamKey=i[i.length-1]}onStart(t){try{this.externalStartCallback=t}catch(t){this.handleSystemError(t)}}onStop(t){try{this.externalStopCallback=t}catch(t){this.handleSystemError(t)}}onError(t){try{this.externalErrorCallback=t}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(t){this.handleSystemError(t)}}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(t){try{if(!this.ws)return;this.ws=null,t.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(t){try{this.externalErrorCallback(new Error(t.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(t){try{const e=this.parseMessage(t.data);switch(e.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(e);break;case'UPDATE':this.handleUpdateMessage(e);break;case'STATUS':this.handleStatusMessage(e)}}catch(t){this.handleRTCError(t)}}handleJoinMessage(t){switch(t.inviteType){case'ANSWER':this.handleAnswer(t.sdp);break;case'CANDIDATE':this.handleCandidate(t.candidate)}}handleStatusMessage(t){switch(t.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(t){try{const e=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(e),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const t={iceServers:[{urls:Rl}]};this.peerConnection=new RTCPeerConnection(t),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const e=await this.createOffer();await this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}async handleAnswer(t){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t}))}catch(t){this.handleRTCError(t)}}async handleCandidate(t){if(t)try{this.peerConnection&&await this.peerConnection.addIceCandidate(t)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:t.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(t){const e=t.streams[0];this.stream&&this.stream.id===e.id||(this.stream=e,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(t){t.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:t.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const t=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(t)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),e=t.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(e))throw new Error('No h264 codec support error');return t}handleRTCError(t){try{this.externalErrorCallback(t||new Error('RTC connection error'))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(t){this.handleSystemError(t)}}send(t){this.ws&&this.ws.send(JSON.stringify(t))}parseMessage(t){try{return JSON.parse(t)}catch(t){throw new Error('Can not parse socket message')}}closeConnections(){const t=this.ws;t&&(this.ws=null,t.close(1e3)),this.removePeerConnection()}removePeerConnection(){let t=this.peerConnection;t&&(this.peerConnection=null,t.close(),t.ontrack=null,t.onicecandidate=null,t.oniceconnectionstatechange=null,t=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(t={}){const e={stunServerList:Rl,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var _l,Il,Ll,Ol,Bl,Ml,Vl,Fl,Ul,ql,jl,Hl,Gl,Yl,Ql,zl,Wl,Jl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(_l||(_l={}));class Xl{constructor(e){this.videoState=new fo(_l.STOPPED),this.maxSeekBackTime$=new t.ValueSubject(0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==_l.STOPPED&&(this.videoState.startTransitionTo(_l.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(_l.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===_l.STOPPED)return this.videoState.startTransitionTo(_l.READY),void this.prepare();if(a)this.prepare();else switch(e){case _l.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(_l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(_l.PLAYING),this.playIfAllowed()));case _l.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(_l.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case _l.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(_l.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=Fo(e.container),this.liveStreamClient=new Cl(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'WebRTCLiveProvider',category:t.ErrorCategory.WTF,message:'WebRTCLiveProvider internal logic error',thrown:i})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.liveTime$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe((t=>{e.duration$.next(t===1/0?0:t)}))).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===_l.READY&&this.videoState.setState(_l.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(_l.PAUSED)}),s)).add(a.playing$.subscribe((()=>{this.videoState.setState(_l.PLAYING)}),s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Oo(this.video,i.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe((s=>{switch(s.to){case _l.STOPPED:e.position$.next(0),e.duration$.next(0),i.playbackState.setState(exports.PlaybackState.STOPPED);break;case _l.READY:break;case _l.PAUSED:i.playbackState.setState(exports.PlaybackState.PAUSED);break;case _l.PLAYING:i.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(s.to)}}),s)).add(t.merge(i.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s))}onLiveStreamStart(t){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.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=t,no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(_l.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:t.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(_l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}}class Kl{constructor(t){this.iterator=t[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 Boolean(this.current.done)}}const Zl=qo(),tu=(null===(Il=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Il?void 0:Il.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),eu=document.createElement('video'),iu={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Ol=null===(Ll=window.SourceBuffer)||void 0===Ll?void 0:Ll.prototype)||void 0===Ol?void 0:Ol.appendBuffer)),hls:Boolean((null===(Bl=eu.canPlayType)||void 0===Bl?void 0:Bl.call(eu,'application/x-mpegurl'))||(null===(Ml=eu.canPlayType)||void 0===Ml?void 0:Ml.call(eu,'vnd.apple.mpegURL'))),webrtc:Boolean(window.RTCPeerConnection)},su={mp4:Boolean(null===(Vl=eu.canPlayType)||void 0===Vl?void 0:Vl.call(eu,'video/mp4')),webm:Boolean(null===(Fl=eu.canPlayType)||void 0===Fl?void 0:Fl.call(eu,'video/webm'))},au={h264:Boolean(null===(ql=null===(Ul=window.MediaSource)||void 0===Ul?void 0:Ul.isTypeSupported)||void 0===ql?void 0:ql.call(Ul,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Hl=null===(jl=window.MediaSource)||void 0===jl?void 0:jl.isTypeSupported)||void 0===Hl?void 0:Hl.call(jl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Yl=null===(Gl=window.MediaSource)||void 0===Gl?void 0:Gl.isTypeSupported)||void 0===Yl?void 0:Yl.call(Gl,'video/webm; codecs="vp9"')),aac:Boolean(null===(zl=null===(Ql=window.MediaSource)||void 0===Ql?void 0:Ql.isTypeSupported)||void 0===zl?void 0:zl.call(Ql,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Jl=null===(Wl=window.MediaSource)||void 0===Wl?void 0:Wl.isTypeSupported)||void 0===Jl?void 0:Jl.call(Wl,'audio/webm; codecs="opus"'))},ru=(au.h264||au.h265)&&au.aac,ou=!Zl,nu=iu.hls&&su.mp4&&(tu||Zl),lu=Boolean(window.WebSocket);const uu=2e4,du=3,hu={cacheDuration:12e4},cu={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},pu={maxPausedTime:3e4},mu={maxPausedTime:3e4};class fu{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,canplay$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new Kl(((e,i=!1)=>e.filter((e=>{switch(e){case exports.VideoFormat.DASH:return iu.mse&&su.mp4&&ru&&ou;case exports.VideoFormat.DASH_SEP:return iu.mse&&su.mp4&&ru;case exports.VideoFormat.DASH_WEBM:return iu.mse&&su.webm&&au.vp9&&au.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return iu.mse&&su.mp4&&ru;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return nu||i&&iu.mse&&su.mp4&&ru;case exports.VideoFormat.MPEG:return su.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return iu.webrtc&&lu&&au.h264&&(su.mp4||su.webm);default:return t.assertNever(e)}})))(s.filter((i=>t.isNonNullable(e.sources[i]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Kl(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}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(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',category:t.ErrorCategory.WTF,message:'Failed to create provider',thrown:e})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==u.None;this.params.desiredState.seekState.setState({state:u.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case o.SCREEN:return this.createScreenProvider(i);case o.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:a}=this.params,r=this.providerOutput,o={container:s,source:null,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Cn({...o,source:s,config:hu})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),this.params.tuning.useDashJs?new hn({...o,source:s,format:e,config:mu}):new bl({...o,source:s})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),nu||!this.params.tuning.useHlsJs?new xl({...o,source:s}):new yl({...o,source:s})}case exports.VideoFormat.HLS_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Al({...o,source:s,config:pu})}case exports.VideoFormat.MPEG:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Nl({...o,source:s})}case exports.VideoFormat.DASH_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new wn({...o,source:s,config:cu})}case exports.VideoFormat.WEB_RTC_LIVE:{const o=this.applyFailoverHost(i[e]);return t.assertNonNullable(o),new Xl({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(n),new So({connection:n,meta:r,container:s,source:i,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?o.CHROMECAST:o.SCREEN}chooseFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case o.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case o.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case o.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}applyFailoverHost(t){if(void 0===this.failoverIndex)return t;const e=this.params.failoverHosts[this.failoverIndex];if(!e)return t;const i=t=>{const i=new URL(t);return i.host=e,i.toString()};if(void 0===t)return t;if('type'in t){if('raw'===t.type)return t;if('url'===t.type)return{...t,url:i(t.url)}}return ao(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const e=new t.Subscription;let i=!1,s=0;var a;return e.add(t.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:uu,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(t.filter((({type:t})=>void 0!==t)))},new t.Observable((e=>{const i=new t.Subscription,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(t.map((({from:t,to:e})=>`${t}-${e}`))),r=a.desiredPlaybackState$.stateChangeEnded$,o=a.providerChanged$,n=new t.Subject;let l=0,u='unknown';return i.add(s.subscribe((t=>{l&&window.clearTimeout(l),u=t,l=window.setTimeout((()=>n.next(t)),a.maxTransitionInterval)}))),i.add(r.subscribe((()=>{window.clearTimeout(l),u='provider change',l=0}))),i.add(o.subscribe((()=>{l&&(window.clearTimeout(l),l=window.setTimeout((()=>n.next(u)),a.maxTransitionInterval))}))),i.add(n.subscribe(e)),()=>{window.clearTimeout(l),i.unsubscribe()}}))).pipe(t.map((e=>({id:`ProviderHangup:${e}`,category:t.ErrorCategory.WTF,message:`A ${e} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),e.add(this.current$.subscribe((()=>{i=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>i=!0));e.add(s)}))),e.add(this.providerError$.subscribe((e=>{if(this.current$.getValue().destination===o.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const a=e.category===t.ErrorCategory.NETWORK,r=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),o=s<du;r&&(a&&i||!o)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}}))),e}}const bu=(t,e,i)=>i*e+(1-i)*t;class Su{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new en(`raw_${s}`),this.smoothedSeries$=new en(`smoothed_${s}`),this.reportedSeries$=new en(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=(this.pastMeasures[t]-this.smoothed)**2,s++);i/=s;const a=Math.sqrt(i),r=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=bu(this.slow,e,this.params.emaAlphaSlow),this.fast=bu(this.fast,e,this.params.emaAlphaFast);const n=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=n(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<o||(t.isNullable(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 vu;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(vu||(vu={}));const gu=new Map;let yu=vu.RUNTIME;const Tu=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Tu,'test'),localStorage.removeItem(Tu),yu=vu.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Tu),yu=vu.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;yu=vu.RUNTIME}}})();const Eu=(e,i)=>{switch(yu){case vu.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vu.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vu.RUNTIME:return void gu.set(e,i);default:t.assertNever(yu)}},ku=window.navigator.connection,wu=()=>{const e=null==ku?void 0:ku.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Pu=()=>{const e=null==ku?void 0:ku.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},$u=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Au{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Au.load('one_video_throughput')||(e.useBrowserEstimation?wu():void 0)||5e3,r=null!==(s=null!==(i=Au.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Pu():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(a),this.rtt$=new t.ValueSubject(r),this.rttAdjustedThroughput$=new t.ValueSubject($u(a,r,e.rttPenaltyRequestSize)),this.throughput=new Su({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Su({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=wu();e&&this.throughput.next(e);const i=Pu();t.isNonNullable(i)&&this.rtt.next(i)};ku&&'onchange'in ku&&this.subscription.add(t.fromEvent(ku,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Eu('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Eu('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>$u(t,i,e.rttPenaltyRequestSize))),t.filter((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const a=new t.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:a.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}a.add(t.fromEvent(e,'loadend').subscribe((r=>{if(200===e.status){const e=r.loaded,a=t.now(),o=e-i,n=a-s;this.addRawSpeed(o,n,1)}this.concurrentDownloads.delete(e),a.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const a=t.now();let r=0,o=t.now();const n=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},l=async({done:u,value:d})=>{u?(this.addRawSpeed(s,t.now()-a,1),this.concurrentDownloads.delete(e)):d&&(s+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&t.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,t.now()-o,this.concurrentDownloads.size),r=0,o=t.now()),await(null==i?void 0:i.read().then(l,n)))};this.concurrentDownloads.add(e),null==i||i.read().then(l,n)}addRawSpeed(t,e,i=1){if(Au.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(e){var i;const s=(e=>{var i,s;switch(yu){case vu.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case vu.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case vu.RUNTIME:return gu.get(e);default:t.assertNever(yu)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const xu={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const Nu=({playbackState:e,seekState:i,playbackAbort$:s,looped$:a,position$:r})=>new t.Observable((o=>{let n;const l=e.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),d=e.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=i.stateChangeEnded$.pipe(t.filter((({to:t})=>{var i,s;return t.state===u.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===exports.PlaybackState.PLAYING}))),c=i.stateChangeEnded$.pipe(t.filter((({from:t,to:i})=>{var s,a;return t.state===u.Applying&&i.state===u.None&&(null!==(a=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:e.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(l,c).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable)),m=t.merge(t.merge(d,h,s),a).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable));return(new t.Subscription).add(p.subscribe((t=>{n=t}))).add(m.subscribe((e=>{if(t.isNullable(n)||n===e)return;const i={from:n,to:e};n=void 0,o.next(i)})))})),Ru={[o.SCREEN]:{vod:[...nu?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...nu?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:nu?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new fo(exports.PlaybackState.STOPPED),seekState:new fo({state:u.None}),volume:new fo({volume:1,muted:!1}),videoTrack:new fo(void 0),autoVideoTrackSwitching:new fo(!0),autoVideoTrackLimits:new fo({}),isLooped:new fo(!1),playbackRate:new fo(1),externalTextTracks:new fo([]),currentTextTrack:new fo(void 0),textTrackCuesSettings:new fo({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentPlaybackRate$:new t.ValueSubject(1),currentBuffer$:new t.ValueSubject({start:0,end:0}),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={inited$:new t.Subject,started$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,canplay$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:Zo},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(xu)){const s=xu[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:null!=a?a:s}return e})(e),this.chromecastInitializer=new d({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Au(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,i,s)=>{const a=Reflect.get(e,i,s);return'function'!=typeof a?a:(...s)=>{try{return a.apply(e,s)}catch(e){const a=s.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(i)}`,o=`Exception calling ${r} (${a.join(', ')})`;throw this.events.fatalError$.next({id:r,category:t.ErrorCategory.WTF,message:o,thrown:e}),e}}}})}initVideo(e){var i,s,a;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new fu({screenFormatsPriority:[...Ru[o.SCREEN].live,...Ru[o.SCREEN].vod],chromecastFormatsPriority:[...Ru[o.CHROMECAST].live,...Ru[o.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},failoverHosts:null!==(a=e.failoverHosts)&&void 0!==a?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:u.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t,!1),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(e){var i;t.assertNonNullable(this.providerContainer);const s=null===(i=this.providerContainer)||void 0===i?void 0:i.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===u.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((()=>!this.isPlaybackStarted)),t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=t.now(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekState.getState();e.state===u.Requested?this.desiredState.seekState.setState({...e,state:u.Applying}):this.events.managedError$.next({id:`WillSeekIn${e.state}`,category:t.ErrorCategory.WTF,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===u.Applying&&(this.desiredState.seekState.setState({state:u.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>mo(t)?1:mo(e)?-1:uo(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).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.currentBuffer$.pipe(t.map((t=>t?{start:t.from,end:t.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===u.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===u.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).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(t.map((e=>({id:'NoProviders',category:t.ErrorCategory.VIDEO_PIPELINE,message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let a=0;const r=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),a=i.getValue()||s.getValue();return t&&!a})),t.filterChanged());this.subscription.add(r.subscribe((t=>{t?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new t.Subscription;this.subscription.add(o);const n=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),o.unsubscribe(),e){case!0:{const e=new t.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),o.add(Nu({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:e}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(Nu({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=rn(t,{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})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),Ko={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Xo=t})),this.providerContainer.current$.subscribe((({type:t})=>tn('provider',t))),i.duration$.subscribe((t=>tn('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>tn('tracks',t))),this.events.fatalError$.subscribe(new en('fatalError')),this.events.managedError$.subscribe(new en('managedError')),i.position$.subscribe(new en('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new en('quality')),this.info.currentBuffer$.subscribe(new en('buffer')),i.isBuffering$.subscribe(new en('isBuffering'))].forEach((t=>this.subscription.add(t))),tn('codecs',Object.keys(au).filter((t=>au[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.77';
|
|
6
|
+
"use strict";var qn=Object.create;var tr=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Qn=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty;var Jn=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zn(e))!Wn.call(s,r)&&r!==t&&tr(s,r,{get:()=>e[r],enumerable:!(i=Yn(e,r))||i.enumerable});return s};var ir=(s,e,t)=>(t=s!=null?qn(Qn(s)):{},Jn(e||!s||!s.__esModule?tr(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Kn=require("lodash/debounce.js");const Xn="2.0.78",Zn="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var D;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(D||(D={}));var eo=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class to{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||eo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.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 i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(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),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.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 a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([i.getCastState()])).pipe(a.filterChanged(),a.map(io),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const io=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(s)}};var sr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},De=function(s){try{return!!s()}catch(e){return!0}},so=De,wi=!so(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ta=wi,Ea=Function.prototype,bs=Ea.call,ro=Ta&&Ea.bind.bind(bs,bs),Xe=Ta?ro:function(s){return function(){return bs.apply(s,arguments)}},$a=Xe,ao=$a({}.toString),no=$a("".slice),_s=function(s){return no(ao(s),8,-1)},oo=Xe,lo=De,uo=_s,Li=Object,co=oo("".split),ho=lo(function(){return!Li("z").propertyIsEnumerable(0)})?function(s){return uo(s)=="String"?co(s,""):Li(s)}:Li,As=function(s){return s==null},fo=As,po=TypeError,ka=function(s){if(fo(s))throw po("Can't call method on "+s);return s},mo=ho,So=ka,Mt=function(s){return mo(So(s))},bo=function(){},mt={},Qt=function(s){return s&&s.Math==Math&&s},ke=Qt(typeof globalThis=="object"&&globalThis)||Qt(typeof window=="object"&&window)||Qt(typeof self=="object"&&self)||Qt(typeof sr=="object"&&sr)||function(){return this}()||Function("return this")(),vs=typeof document=="object"&&document.all,vo=typeof vs=="undefined"&&vs!==void 0,Pa={all:vs,IS_HTMLDDA:vo},wa=Pa,go=wa.all,Se=wa.IS_HTMLDDA?function(s){return typeof s=="function"||s===go}:function(s){return typeof s=="function"},yo=ke,To=Se,rr=yo.WeakMap,Eo=To(rr)&&/native code/.test(String(rr)),ar=Se,_a=Pa,$o=_a.all,St=_a.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ar(s)||s===$o}:function(s){return typeof s=="object"?s!==null:ar(s)},ko=De,Ue=!ko(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),bt={},Po=ke,nr=St,gs=Po.document,wo=nr(gs)&&nr(gs.createElement),Aa=function(s){return wo?gs.createElement(s):{}},_o=Ue,Ao=De,Ro=Aa,Ra=!_o&&!Ao(function(){return Object.defineProperty(Ro("div"),"a",{get:function(){return 7}}).a!=7}),Io=Ue,No=De,Ia=Io&&No(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Do=St,Co=String,Lo=TypeError,vt=function(s){if(Do(s))return s;throw Lo(Co(s)+" is not an object")},xo=wi,Wt=Function.prototype.call,Ze=xo?Wt.bind(Wt):function(){return Wt.apply(Wt,arguments)},Rs={},xi=Rs,Oi=ke,Oo=Se,or=function(s){return Oo(s)?s:void 0},Is=function(s,e){return arguments.length<2?or(xi[s])||or(Oi[s]):xi[s]&&xi[s][e]||Oi[s]&&Oi[s][e]},Bo=Xe,Na=Bo({}.isPrototypeOf),Mo=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Da=ke,Bi=Mo,lr=Da.process,ur=Da.Deno,dr=lr&&lr.versions||ur&&ur.version,cr=dr&&dr.v8,pe,Si;cr&&(pe=cr.split("."),Si=pe[0]>0&&pe[0]<4?1:+(pe[0]+pe[1]));!Si&&Bi&&(pe=Bi.match(/Edge\/(\d+)/),(!pe||pe[1]>=74)&&(pe=Bi.match(/Chrome\/(\d+)/),pe&&(Si=+pe[1])));var Vo=Si,hr=Vo,Fo=De,Ca=!!Object.getOwnPropertySymbols&&!Fo(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&hr&&hr<41}),Uo=Ca,La=Uo&&!Symbol.sham&&typeof Symbol.iterator=="symbol",jo=Is,Ho=Se,Go=Na,qo=La,Yo=Object,xa=qo?function(s){return typeof s=="symbol"}:function(s){var e=jo("Symbol");return Ho(e)&&Go(e.prototype,Yo(s))},zo=String,Ns=function(s){try{return zo(s)}catch(e){return"Object"}},Qo=Se,Wo=Ns,Jo=TypeError,Ds=function(s){if(Qo(s))return s;throw Jo(Wo(s)+" is not a function")},Ko=Ds,Xo=As,Cs=function(s,e){var t=s[e];return Xo(t)?void 0:Ko(t)},Mi=Ze,Vi=Se,Fi=St,Zo=TypeError,el=function(s,e){var t,i;if(e==="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s))||Vi(t=s.valueOf)&&!Fi(i=Mi(t,s))||e!=="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s)))return i;throw Zo("Can't convert object to primitive value")},bi={},tl={get exports(){return bi},set exports(s){bi=s}},il=!0,fr=ke,sl=Object.defineProperty,rl=function(s,e){try{sl(fr,s,{value:e,configurable:!0,writable:!0})}catch(t){fr[s]=e}return e},al=ke,nl=rl,pr="__core-js_shared__",ol=al[pr]||nl(pr,{}),Oa=ol,mr=Oa;(tl.exports=function(s,e){return mr[s]||(mr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var ll=ka,ul=Object,Ls=function(s){return ul(ll(s))},dl=Xe,cl=Ls,hl=dl({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return hl(cl(e),t)},fl=Xe,pl=0,ml=Math.random(),Sl=fl(1 .toString),Ba=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Sl(++pl+ml,36)},bl=ke,vl=bi,Sr=je,gl=Ba,yl=Ca,Tl=La,ot=bl.Symbol,Ui=vl("wks"),El=Tl?ot.for||ot:ot&&ot.withoutSetter||gl,Ce=function(s){return Sr(Ui,s)||(Ui[s]=yl&&Sr(ot,s)?ot[s]:El("Symbol."+s)),Ui[s]},$l=Ze,br=St,vr=xa,kl=Cs,Pl=el,wl=Ce,_l=TypeError,Al=wl("toPrimitive"),Rl=function(s,e){if(!br(s)||vr(s))return s;var t=kl(s,Al),i;if(t){if(e===void 0&&(e="default"),i=$l(t,s,e),!br(i)||vr(i))return i;throw _l("Can't convert object to primitive value")}return e===void 0&&(e="number"),Pl(s,e)},Il=Rl,Nl=xa,xs=function(s){var e=Il(s,"string");return Nl(e)?e:e+""},Dl=Ue,Cl=Ra,Ll=Ia,Jt=vt,gr=xs,xl=TypeError,ji=Object.defineProperty,Ol=Object.getOwnPropertyDescriptor,Hi="enumerable",Gi="configurable",qi="writable";bt.f=Dl?Ll?function(e,t,i){if(Jt(e),t=gr(t),Jt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&qi in i&&!i[qi]){var r=Ol(e,t);r&&r[qi]&&(e[t]=i.value,i={configurable:Gi in i?i[Gi]:r[Gi],enumerable:Hi in i?i[Hi]:r[Hi],writable:!1})}return ji(e,t,i)}:ji:function(e,t,i){if(Jt(e),t=gr(t),Jt(i),Cl)try{return ji(e,t,i)}catch(r){}if("get"in i||"set"in i)throw xl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var _i=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Bl=Ue,Ml=bt,Vl=_i,Vt=Bl?function(s,e,t){return Ml.f(s,e,Vl(1,t))}:function(s,e,t){return s[e]=t,s},Fl=bi,Ul=Ba,yr=Fl("keys"),Os=function(s){return yr[s]||(yr[s]=Ul(s))},Bs={},jl=Eo,Ma=ke,Hl=St,Gl=Vt,Yi=je,zi=Oa,ql=Os,Yl=Bs,Tr="Object already initialized",ys=Ma.TypeError,zl=Ma.WeakMap,vi,Bt,gi,Ql=function(s){return gi(s)?Bt(s):vi(s,{})},Wl=function(s){return function(e){var t;if(!Hl(e)||(t=Bt(e)).type!==s)throw ys("Incompatible receiver, "+s+" required");return t}};if(jl||zi.state){var ye=zi.state||(zi.state=new zl);ye.get=ye.get,ye.has=ye.has,ye.set=ye.set,vi=function(s,e){if(ye.has(s))throw ys(Tr);return e.facade=s,ye.set(s,e),e},Bt=function(s){return ye.get(s)||{}},gi=function(s){return ye.has(s)}}else{var rt=ql("state");Yl[rt]=!0,vi=function(s,e){if(Yi(s,rt))throw ys(Tr);return e.facade=s,Gl(s,rt,e),e},Bt=function(s){return Yi(s,rt)?s[rt]:{}},gi=function(s){return Yi(s,rt)}}var Jl={set:vi,get:Bt,has:gi,enforce:Ql,getterFor:Wl},Kl=wi,Va=Function.prototype,Er=Va.apply,$r=Va.call,Xl=typeof Reflect=="object"&&Reflect.apply||(Kl?$r.bind(Er):function(){return $r.apply(Er,arguments)}),Zl=_s,eu=Xe,Fa=function(s){if(Zl(s)==="Function")return eu(s)},Ua={},ja={},Ha={}.propertyIsEnumerable,Ga=Object.getOwnPropertyDescriptor,tu=Ga&&!Ha.call({1:2},1);ja.f=tu?function(e){var t=Ga(this,e);return!!t&&t.enumerable}:Ha;var iu=Ue,su=Ze,ru=ja,au=_i,nu=Mt,ou=xs,lu=je,uu=Ra,kr=Object.getOwnPropertyDescriptor;Ua.f=iu?kr:function(e,t){if(e=nu(e),t=ou(t),uu)try{return kr(e,t)}catch(i){}if(lu(e,t))return au(!su(ru.f,e,t),e[t])};var du=De,cu=Se,hu=/#|\.prototype\./,Ft=function(s,e){var t=pu[fu(s)];return t==Su?!0:t==mu?!1:cu(e)?du(e):!!e},fu=Ft.normalize=function(s){return String(s).replace(hu,".").toLowerCase()},pu=Ft.data={},mu=Ft.NATIVE="N",Su=Ft.POLYFILL="P",bu=Ft,Pr=Fa,vu=Ds,gu=wi,yu=Pr(Pr.bind),qa=function(s,e){return vu(s),e===void 0?s:gu?yu(s,e):function(){return s.apply(e,arguments)}},Kt=ke,Tu=Xl,Eu=Fa,$u=Se,ku=Ua.f,Pu=bu,at=Rs,wu=qa,nt=Vt,wr=je,_u=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Tu(s,this,arguments)};return e.prototype=s.prototype,e},Ms=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?Kt:r?Kt[t]:(Kt[t]||{}).prototype,l=i?at:at[t]||nt(at,t,{})[t],d=l.prototype,u,c,h,f,p,S,m,b,v;for(f in e)u=Pu(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&wr(o,f),S=l[f],c&&(s.dontCallGetSet?(v=ku(o,f),m=v&&v.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof S==typeof p)&&(s.bind&&c?b=wu(p,Kt):s.wrap&&c?b=_u(p):n&&$u(p)?b=Eu(p):b=p,(s.sham||p&&p.sham||S&&S.sham)&&nt(b,"sham",!0),nt(l,f,b),n&&(h=t+"Prototype",wr(at,h)||nt(at,h,{}),nt(at[h],f,p),s.real&&d&&(u||!d[f])&&nt(d,f,p)))},Ts=Ue,Au=je,Ya=Function.prototype,Ru=Ts&&Object.getOwnPropertyDescriptor,Vs=Au(Ya,"name"),Iu=Vs&&function(){}.name==="something",Nu=Vs&&(!Ts||Ts&&Ru(Ya,"name").configurable),Du={EXISTS:Vs,PROPER:Iu,CONFIGURABLE:Nu},za={},Cu=Math.ceil,Lu=Math.floor,xu=Math.trunc||function(e){var t=+e;return(t>0?Lu:Cu)(t)},Ou=xu,Fs=function(s){var e=+s;return e!==e||e===0?0:Ou(e)},Bu=Fs,Mu=Math.max,Vu=Math.min,Fu=function(s,e){var t=Bu(s);return t<0?Mu(t+e,0):Vu(t,e)},Uu=Fs,ju=Math.min,Hu=function(s){return s>0?ju(Uu(s),9007199254740991):0},Gu=Hu,Us=function(s){return Gu(s.length)},qu=Mt,Yu=Fu,zu=Us,_r=function(s){return function(e,t,i){var r=qu(e),n=zu(r),o=Yu(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Qu={includes:_r(!0),indexOf:_r(!1)},Wu=Xe,Qi=je,Ju=Mt,Ku=Qu.indexOf,Xu=Bs,Ar=Wu([].push),Zu=function(s,e){var t=Ju(s),i=0,r=[],n;for(n in t)!Qi(Xu,n)&&Qi(t,n)&&Ar(r,n);for(;e.length>i;)Qi(t,n=e[i++])&&(~Ku(r,n)||Ar(r,n));return r},Qa=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ed=Zu,td=Qa,id=Object.keys||function(e){return ed(e,td)},sd=Ue,rd=Ia,ad=bt,nd=vt,od=Mt,ld=id;za.f=sd&&!rd?Object.defineProperties:function(e,t){nd(e);for(var i=od(t),r=ld(t),n=r.length,o=0,l;n>o;)ad.f(e,l=r[o++],i[l]);return e};var ud=Is,dd=ud("document","documentElement"),cd=vt,hd=za,Rr=Qa,fd=Bs,pd=dd,md=Aa,Sd=Os,Ir=">",Nr="<",Es="prototype",$s="script",Wa=Sd("IE_PROTO"),Wi=function(){},Ja=function(s){return Nr+$s+Ir+s+Nr+"/"+$s+Ir},Dr=function(s){s.write(Ja("")),s.close();var e=s.parentWindow.Object;return s=null,e},bd=function(){var s=md("iframe"),e="java"+$s+":",t;return s.style.display="none",pd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Ja("document.F=Object")),t.close(),t.F},Xt,ci=function(){try{Xt=new ActiveXObject("htmlfile")}catch(e){}ci=typeof document!="undefined"?document.domain&&Xt?Dr(Xt):bd():Dr(Xt);for(var s=Rr.length;s--;)delete ci[Es][Rr[s]];return ci()};fd[Wa]=!0;var Ka=Object.create||function(e,t){var i;return e!==null?(Wi[Es]=cd(e),i=new Wi,Wi[Es]=null,i[Wa]=e):i=ci(),t===void 0?i:hd.f(i,t)},vd=De,gd=!vd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),yd=je,Td=Se,Ed=Ls,$d=Os,kd=gd,Cr=$d("IE_PROTO"),ks=Object,Pd=ks.prototype,Xa=kd?ks.getPrototypeOf:function(s){var e=Ed(s);if(yd(e,Cr))return e[Cr];var t=e.constructor;return Td(t)&&e instanceof t?t.prototype:e instanceof ks?Pd:null},wd=Vt,Za=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wd(s,e,t),s},_d=De,Ad=Se,Rd=St,Id=Ka,Lr=Xa,Nd=Za,Dd=Ce,Ps=Dd("iterator"),en=!1,Ie,Ji,Ki;[].keys&&(Ki=[].keys(),"next"in Ki?(Ji=Lr(Lr(Ki)),Ji!==Object.prototype&&(Ie=Ji)):en=!0);var Cd=!Rd(Ie)||_d(function(){var s={};return Ie[Ps].call(s)!==s});Cd?Ie={}:Ie=Id(Ie);Ad(Ie[Ps])||Nd(Ie,Ps,function(){return this});var tn={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:en},Ld=Ce,xd=Ld("toStringTag"),sn={};sn[xd]="z";var js=String(sn)==="[object z]",Od=js,Bd=Se,hi=_s,Md=Ce,Vd=Md("toStringTag"),Fd=Object,Ud=hi(function(){return arguments}())=="Arguments",jd=function(s,e){try{return s[e]}catch(t){}},Hs=Od?hi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=jd(e=Fd(s),Vd))=="string"?t:Ud?hi(e):(i=hi(e))=="Object"&&Bd(e.callee)?"Arguments":i},Hd=js,Gd=Hs,qd=Hd?{}.toString:function(){return"[object "+Gd(this)+"]"},Yd=js,zd=bt.f,Qd=Vt,Wd=je,Jd=qd,Kd=Ce,xr=Kd("toStringTag"),rn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Wd(r,xr)||zd(r,xr,{configurable:!0,value:e}),i&&!Yd&&Qd(r,"toString",Jd)}},Xd=tn.IteratorPrototype,Zd=Ka,ec=_i,tc=rn,ic=mt,sc=function(){return this},rc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Zd(Xd,{next:ec(+!i,t)}),tc(s,r,!1,!0),ic[r]=sc,s},ac=Ms,nc=Ze,an=Du,oc=rc,lc=Xa,uc=rn,Or=Za,dc=Ce,Br=mt,nn=tn,cc=an.PROPER;an.CONFIGURABLE;nn.IteratorPrototype;var Zt=nn.BUGGY_SAFARI_ITERATORS,Xi=dc("iterator"),Mr="keys",ei="values",Vr="entries",hc=function(){return this},fc=function(s,e,t,i,r,n,o){oc(t,e,i);var l=function(v){if(v===r&&f)return f;if(!Zt&&v in c)return c[v];switch(v){case Mr:return function(){return new t(this,v)};case ei:return function(){return new t(this,v)};case Vr:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[Xi]||c["@@iterator"]||r&&c[r],f=!Zt&&h||l(r),p=e=="Array"&&c.entries||h,S,m,b;if(p&&(S=lc(p.call(new s)),S!==Object.prototype&&S.next&&(uc(S,d,!0,!0),Br[d]=hc)),cc&&r==ei&&h&&h.name!==ei&&(u=!0,f=function(){return nc(h,this)}),r)if(m={values:l(ei),keys:n?f:l(Mr),entries:l(Vr)},o)for(b in m)(Zt||u||!(b in c))&&Or(c,b,m[b]);else ac({target:e,proto:!0,forced:Zt||u},m);return o&&c[Xi]!==f&&Or(c,Xi,f,{name:r}),Br[e]=f,m},pc=function(s,e){return{value:s,done:e}},mc=Mt,Gs=bo,Fr=mt,on=Jl,Sc=bt.f,bc=fc,ti=pc,vc=il,gc=Ue,ln="Array Iterator",yc=on.set,Tc=on.getterFor(ln);bc(Array,"Array",function(s,e){yc(this,{type:ln,target:mc(s),index:0,kind:e})},function(){var s=Tc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ti(void 0,!0)):t=="keys"?ti(i,!1):t=="values"?ti(e[i],!1):ti([i,e[i]],!1)},"values");var Ur=Fr.Arguments=Fr.Array;Gs();Gs();Gs();if(!vc&&gc&&Ur.name!=="values")try{Sc(Ur,"name",{value:"values"})}catch(s){}var Ec=Ce,$c=mt,kc=Ec("iterator"),Pc=Array.prototype,wc=function(s){return s!==void 0&&($c.Array===s||Pc[kc]===s)},_c=Hs,jr=Cs,Ac=As,Rc=mt,Ic=Ce,Nc=Ic("iterator"),un=function(s){if(!Ac(s))return jr(s,Nc)||jr(s,"@@iterator")||Rc[_c(s)]},Dc=Ze,Cc=Ds,Lc=vt,xc=Ns,Oc=un,Bc=TypeError,Mc=function(s,e){var t=arguments.length<2?Oc(s):e;if(Cc(t))return Lc(Dc(t,s));throw Bc(xc(s)+" is not iterable")},Vc=Ze,Hr=vt,Fc=Cs,Uc=function(s,e,t){var i,r;Hr(s);try{if(i=Fc(s,"return"),!i){if(e==="throw")throw t;return t}i=Vc(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Hr(i),t},jc=qa,Hc=Ze,Gc=vt,qc=Ns,Yc=wc,zc=Us,Gr=Na,Qc=Mc,Wc=un,qr=Uc,Jc=TypeError,fi=function(s,e){this.stopped=s,this.result=e},Yr=fi.prototype,Kc=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=jc(e,i),u,c,h,f,p,S,m,b=function(g){return u&&qr(u,"normal",g),new fi(!0,g)},v=function(g){return r?(Gc(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=Wc(s),!c)throw Jc(qc(s)+" is not iterable");if(Yc(c)){for(h=0,f=zc(s);f>h;h++)if(p=v(s[h]),p&&Gr(Yr,p))return p;return new fi(!1)}u=Qc(s,c)}for(S=n?s.next:u.next;!(m=Hc(S,u)).done;){try{p=v(m.value)}catch(g){qr(u,"throw",g)}if(typeof p=="object"&&p&&Gr(Yr,p))return p}return new fi(!1)},Xc=xs,Zc=bt,eh=_i,th=function(s,e,t){var i=Xc(e);i in s?Zc.f(s,i,eh(0,t)):s[i]=t},ih=Ms,sh=Kc,rh=th;ih({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sh(e,function(i,r){rh(t,i,r)},{AS_ENTRIES:!0}),t}});var ah=Rs,nh=ah.Object.fromEntries,oh={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},lh=oh,uh=ke,dh=Hs,ch=Vt,zr=mt,hh=Ce,Qr=hh("toStringTag");for(var Zi in lh){var Wr=uh[Zi],es=Wr&&Wr.prototype;es&&dh(es)!==Qr&&ch(es,Qr,Zi),zr[Zi]=zr.Array}var fh=nh,ph=fh,mh=ph,Sh=mh,Ut=Sh,ut;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ut||(ut={}));var ct=(s,e=0,t=ut.OFFSET_P)=>{switch(t){case ut.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ut.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:a.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const me={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},pi=(s,e)=>me[s].height>me[e].height,bh=(s,e)=>me[s].height>=me[e].height,Lt=(s,e)=>me[s].height<me[e].height,vh=(s,e)=>me[s].height<=me[e].height,gh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Lt(e,t)?1:-1)[0],yh=Object.keys(me).sort((s,e)=>Lt(s,e)?-1:1),et=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return yh.find(r=>{const n=me[r];return n.width>=i&&n.height>=t})},Th=s=>me[s].height,yi=s=>s===exports.VideoQuality.INVARIANT;class J{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Eh=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(s)}};var F;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(F||(F={}));const $h=5,kh=5,Ph=500,Jr=7e3;class wh{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(F.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&i!==F.STOPPED){this.seek(l.position);return}switch(n){case exports.PlaybackState.PLAYING:{switch(i){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Eh(e.format)),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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Ph)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===D.Applying||Math.abs(l-n)>$h)&&r.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<kh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,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(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:D.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===F.READY&&this.videoState.setState(F.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];a.assertNonNullable(c);const h=gh(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=i[e];a.assertNonNullable(c),r=ct(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===D.Applying||i.state===D.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Jr).subscribe(()=>n(`timeout(${Jr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Kr{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class dn extends Kr{constructor(){super(),this.listeners||Kr.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 cn=class{constructor(){Object.defineProperty(this,"signal",{value:new dn,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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(cn.prototype[Symbol.toStringTag]="AbortController",dn.prototype[Symbol.toStringTag]="AbortSignal");function hn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function _h(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!hn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,S)=>{c.addEventListener("abort",()=>S(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ai=hn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),fn=Ai?_h({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ai?fn.fetch:window.fetch;Ai?fn.Request:window.Request;const Je=Ai?cn:window.AbortController,It=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class xt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[n,o]=It(r.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);r&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(It),r=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const p=i[f][1];p-r<=2*this.params.minDataSize&&(n=Math.max(n,p))}r===0?n=Math.max(n,r+this.params.minInitSize):n=Math.max(n,r+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${r}-${n}`);const l=o.toString(),d=new Je,u=d.signal,c={url:e,from:r,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,S;throw(S=(p=this.params).onError)===null||S===void 0||S.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return ht(l,{signal:u}).then(f=>{var p,S,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,v]=f.body.tee();(S=(p=this.params).onDownloadStream)===null||S===void 0||S.call(p,v);const g=b.getReader(),P=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-r+1;c.data=new ArrayBuffer(P);const T=new Uint8Array(c.data),E=async({done:_,value:x})=>{_?this.onBigRequestProgress(c):x&&(T.set(x,c.loaded),c.loaded+=x.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(E,xt.suppressStreamErrors).catch(h)))};g==null||g.read().then(E,xt.suppressStreamErrors).catch(h)},xt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:n,response:o}){var l,d,u,c,h,f,p,S;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of m){const{request:v}=b,[g,P]=It(v),T=g>=t&&P<=t+r,E=t>=g&&t+r<P,_=n.slice(g-t,Math.min(P-t+1,r));if((T||E)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=_.byteLength,v.bytesTotal=i-t),T){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(N=>N!==b)),(h=b.success)===null||h===void 0||h.call(b,_,"",e);const x=o?Array.from(o.headers.entries()).map(([N,R])=>`${N}: ${R}`).join(`\r
|
|
7
|
+
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(v,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,x,[])}else E&&((S=b.progress)===null||S===void 0||S.call(b,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=It(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,n;if(!this.activeRequests.has(e))return;const o=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const l of o){const[d,u]=It(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ti{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ti.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ti.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ah=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Ti(r,e,i)}}),Rh=(s,e)=>{const t=new xt(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:n=>{const o=r(n);return Ah(o,t)}}},!0),()=>t.destroy()};var Ih=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Nh=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,S,m;const b=Ut(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const v=(S=b["x-delivery-type"])!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[b["x-reused"]])!==null&&m!==void 0?m:void 0;i.next(v),r.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,S=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),S(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ft=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Dh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ft}),!0),Ch=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const $e=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},tt=(s,e,t)=>$e(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),Le=(s,e,t,i)=>$e(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),He=(s,e,t,i)=>$e(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Lh=s=>["__",s.language,s.label].join("|"),xh=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add($e(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:r})),this.subscription.add($e(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:r})),this.subscription.add($e(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:Lh(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&xh(t,e)?t.mode="showing":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){a.assertNonNullable(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),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var xe=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class qs{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var pn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const ws=3;class Oh{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<ws&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||ws))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var mn=(s,e,t=ws)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const Oe=s=>{const e=p=>a.fromEvent(s,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(p=>a.fromEvent(s,p))).pipe(a.map(p=>p.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>mn(s.buffered,s.currentTime))),n=pn()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),l=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),d=a.fromEvent(s,"error").pipe(a.filter(()=>Boolean(s.error||s.played.length)),a.map(()=>{var p;const S=s.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(p=s.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{s.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=s.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:a.fromEvent(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:l}},Ys=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Bh=Ms,Mh=Ls,Vh=Us,Fh=Fs;Bh({target:"Array",proto:!0},{at:function(e){var t=Mh(this),i=Vh(t),r=Fh(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var Uh=Is,jh=Uh,Hh=jh,Gh=Hh("Array","at"),qh=Gh,Yh=qh,zh=Yh,Qh=zh,_e=Qh;let zs=!1,Ae={};const Wh=s=>{zs=s},Jh=()=>{Ae={}},Kh=s=>{s(Ae)},ii=(s,e)=>{var t;zs&&(Ae.meta=(t=Ae.meta)!==null&&t!==void 0?t:{},Ae.meta[s]=e)};class Ee{constructor(e){this.name=e}next(e){var t,i;if(!zs)return;Ae.series=(t=Ae.series)!==null&&t!==void 0?t:{};const r=(i=Ae.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ae.series[this.name]=r}}const Xh=new Ee("best_bitrate"),Zh=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class ef{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const jt=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const S=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*i.containerSizeFactor,height:e.height*S*i.containerSizeFactor},b=m&&et(m),v=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=s.filter(I=>!yi(I.quality)).sort((I,A)=>pi(I.quality,A.quality)?-1:1),P=(h=_e(g,-1))===null||h===void 0?void 0:h.quality,T=(f=_e(g,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&Lt(r.max,r.min)||a.isNonNullable(r.min)&&T&&pi(r.min,T)||a.isNonNullable(r.max)&&P&&Lt(r.max,P),_=v*Zh(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),N=g.filter(I=>{const A=b?Lt(I.quality,b):!0,O=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*_:!0,V=i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!yi(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&pi(I.quality,d.quality),q=E||(a.isNullable(r.max)||vh(I.quality,r.max))&&(a.isNullable(r.min)||bh(I.quality,r.min));return A&&O&&!V&&q})[0];N&&N.bitrate&&Xh.next(N.bitrate);const R=(p=N!=null?N:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:s[0],M=R&&u&&u.history[R.id]&&a.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!M&&u.recordSelection(R),M&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const tf=300,Ei=(s,e=tf)=>new a.Observable(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Kn(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()}),sf=5e3,Nt={};var U;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const te=(s,e)=>new a.Observable(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class rf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(U.DOWNLOADING_LIB),this.textTracksManager=new Pe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new qs,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===U.DOWNLOADING_LIB||t===U.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&t!==U.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case U.STOPPED:break;case U.PLAYING:case U.PAUSED:case U.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case U.PLAYING:break;case U.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case U.READY:this.play();break;case U.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case U.PLAYING:this.pause(),this.liveOffset.pause();break;case U.PAUSED:break;case U.READY:this.videoState.setState(U.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case U.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(i)}},this.video=xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),sf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Nt.MediaPlayer=r.MediaPlayer,Nt.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(Nt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Nt.Debug,"dashjs not loaded"),this.player=Nt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Ys(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Rh(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Ch(this.player),Ih(this.player),this.params.tuning.requestQuick&&Dh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,b)=>this.subscription.add(m.subscribe(b,i));r(Ei(this.video),this.elementSize$),r(te(this.player,"error").pipe(a.map(m=>{const b=typeof m.error=="object"?m.error.code:m.error,v=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${b}`,message:v}})),e.error$),r(te(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:v})=>v.qualityIndex===m))===null||b===void 0?void 0:b.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===U.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add($e(t.videoTrack,()=>{var m,b;const v=this.player.getQualityFor("video");return(b=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===v))===null||m===void 0?void 0:m.track)===null||b===void 0?void 0:b.id},m=>{var b;if(a.isNullable(m))return;const v=(b=this.videoTracks.find(({track:g})=>g.id===m))===null||b===void 0?void 0:b.bitrateInfo;v&&this.player.setQualityFor("video",v.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add($e(t.autoVideoTrackSwitching,()=>{var m,b,v;return(v=(b=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||v===void 0?void 0:v.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(te(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(te(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:b}})=>{var v,g;const P=this.player.getDashMetrics(),T=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),E=(v=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,_=(g={1:!0,0:!1}[T])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(_),e.hostname$.next(ne(b))}),r(te(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:b,availableFrom:v}}})=>{this.isLive$.next(b),this.availableFrom$.next(v.getTime()),b||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),_=et(T),x=T.bitrate/1e3,N={width:T.width,height:T.height},R=this.frameRatesByFrameHeight[T.height];if(_){const M={id:E,quality:_,bitrate:x,size:N,fps:R};this.videoTracks.push({track:M,bitrateInfo:T}),T.qualityIndex===g&&(P=M)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(U.STREAM_INITIALIZED),this.videoState.startTransitionTo(U.READY)}),r(te(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const b=m.requestEndDate.getTime()-m.firstByteDate.getTime(),v=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,b)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=jt(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),v=this.videoTracks.find(({track:g})=>g===b);v!=null&&v.bitrateInfo&&this.player.setQualityFor("video",v==null?void 0:v.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:b})=>this.params.output.liveTime$.next(m+b*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(te(this.player,"playbackEnded"),e.endedEvent$),r(te(this.player,"playbackProgress").pipe(a.map(()=>mn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(U.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),r(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(U.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(te(this.player,"playbackPaused"),()=>{this.videoState.setState(U.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),r(te(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===U.READY&&this.videoState.setState(U.READY)}),r(this.isLive$,e.isLive$),r(Ei(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Nh(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:b})=>{const v=!m&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),r(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(tt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:S}=Oe(this.video);this.subscription.add(Le(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(He(this.video,t.playbackRate,S,i))}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.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(U.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(U.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=ct(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ut.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(U.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ht=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},Ge=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function re(){return a.now()}function Sn(s){return re()-s}function Xr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function af(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function mi(s,e,t,i){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",S=7e3,m=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const A=Sn(c);let O;if(A<m){O=m-A,setTimeout(b,O);return}m*=2,m>S&&(m=S),o&&o.abort(),o=new r,_()};const v=A=>(n=A,I),g=A=>(h=A,I),P=()=>(p="json",I),T=()=>{if(!d){if(--u>=0){b(),i&&i();return}d=!0,h&&h(),t&&t()}},E=A=>(f=A,I),_=()=>{c=re(),o=new r,o.open("get",s);let A=0,O,V=0;const q=()=>(a.assertNonNullable(c),Math.max(c,Math.max(O||0,V||0)));if(n&&o.addEventListener("progress",$=>{const C=re();n.updateChunk&&$.loaded>A&&(n.updateChunk(q(),$.loaded-A),A=$.loaded,O=C)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const C=o.response.byteLength-A;C&&n.updateChunk&&n.updateChunk(q(),C)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(V=re(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),I},I={withBitrateReporting:v,withParallel:E,withJSONResponse:P,withRetryCount:A=>(u=A,I),withRetryInterval:(A,O)=>(a.isNonNullable(A)&&(m=A),a.isNonNullable(O)&&(S=O),I),withTimeout:A=>(l=A,I),withFinally:g,send:_,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const nf=100,of=2e3,lf=500;let uf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-lf;if(t-e>of){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&i>0){const n=r*8/(i/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>nf&&(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 df{constructor(e,t,i,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}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 i=re(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=re()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=mi(t,n,()=>r("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=re()}_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=re();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){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,i,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}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 si=1e4,ri=3,cf=300,hf=2e3,ff=6e4,pf=10,mf=1,Sf=500;class bf{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 uf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Xr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){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(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):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=Xr(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!i||i.bitrate>n.bitrate)&&(i=n));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("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 o=()=>{af(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new df(ri,si,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,_)=>{d&&d.abort(),d=mi(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withTimeout(si).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ri).withFinally(()=>{d=null}).send()},p=(T,E,_)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},S=T=>{const E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),b()},b=()=>{if(!this.lowLatency)S(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const _=re()-6e4;let x=0;for(let R=0;R<this.bufferStates.length;R++){const M=this.bufferStates[R];T=Math.min(T,M.buf),M.ts<_&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let N=T-mf;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?S(1.15):N>1?S(1.1):N>.3?S(1.01):S(1)}},v=T=>{let E;const _=()=>E&&E.start?E.start.length:0,x=$=>E.start[$]/1e3,N=$=>E.dur[$]/1e3,R=$=>E.fragIndex+$,M=($,C)=>({chunkIdx:R($),startTS:x($),dur:N($),discontinuity:C}),I=()=>{let $=0;if(E&&E.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=C;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ee=E.dur.length-1;for(;ee>=0&&(Z-=E.dur[ee],!(Z<=0));--ee);$=Math.min(ee,E.dur.length-1-Q),$=Math.max($,0)}return M($,!0)},A=$=>{const C=_();if(!(C<=0)){if(a.isNonNullable($)){for(let Q=0;Q<C;Q++)if(x(Q)>$)return M(Q)}return I()}},O=$=>{const C=_(),Q=$?$.chunkIdx+1:0,Z=Q-E.fragIndex;if(!(C<=0)){if(!$||Z<0||Z-C>pf)return t(`Resync: offset=${Z} bChunks=${C} chunk=`+JSON.stringify($)),I();if(!(Z>=C))return M(Q-E.fragIndex,!1)}},V=($,C,Q)=>{u&&u.abort(),u=mi(this.urlResolver.resolve($,!0,this.lowLatency),C,Q,()=>this._retryCallback()).withTimeout(si).withRetryCount(ri).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,C)=>{V(T,Q=>{if(!h())return;E=Q;const Z=Boolean(E.lowLatency);Z!==this.lowLatency&&m(Z);let ee=0;for(let oe=0;oe<E.dur.length;++oe)ee+=E.dur[oe];ee>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(A(C))},()=>this._handleNetworkError())},nextChunk:O}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:_}=this.params;let x=v(e.jidxUrl),N,R,M,I,A=0,O,V,q;const $=()=>{O&&(clearTimeout(O),O=void 0);const j=Math.max(Sf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=A+j,ae=re(),ue=Math.min(1e4,ie-ae);A=ae;const qe=()=>{u||h()&&x.seek(()=>{h()&&(A=re(),C(),$())})};ue>0?O=window.setTimeout(()=>{this.paused?$():qe()},ue):qe()},C=()=>{let j;for(;j=x.nextChunk(I);)I=j,be(j);const ie=x.nextChunk(M);if(ie){if(M&&ie.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}oe(ie)}else $()},Q=(j,ie)=>{if(!h()||!this.sourceBuffer)return;let ae,ue,qe;const ve=Be=>{window.setTimeout(()=>{h()&&Q(j,ie)},Be)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),ve(100);else{const Be=re(),Ye=E.currentTime;!this.paused&&E.buffered.length>1&&V===Ye&&Be-q>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),V!==Ye&&(V=Ye,q=Be);const yt=this._getBufferSizeSec();if(yt>30)_(`Buffered ${yt} seconds; delaying appendBuffer`),ve(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Be,buf:yt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(it){if(it.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ae=this.sourceBuffer.buffered.start(0),ue=Ye,ue-ae>4&&this.sourceBuffer.remove(ae,ue-3)),ve(1e3);else throw it}}},Z=()=>{R&&N&&(_([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(M)]),Q(R,function(){R=null,C()}))},ee=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),oe=j=>{h()&&p(ee(j),(ie,ae)=>{if(h()){if(ae/=1e3,R=ie,M=j,o=j.startTS,ae){const ue=Math.min(10,j.dur/ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}Z()}},()=>this._handleNetworkError())},be=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(j),!1)))},gt=j=>{h()&&(e.cachedHeader=j,Q(j,()=>{N=!0,Z()}))};n=!0,x.seek(j=>{if(h()){if(A=re(),!j){$();return}I=j,!a.isNullable(T)||j.startTS>T?oe(j):(M=j,C())}},T),e.cachedHeader?gt(e.cachedHeader):f(e.headerUrl,gt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(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,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),S=h/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const S=re();if(this.chunkRateEstimator.addInterval(f,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Sn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=re();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=mi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(si).withRetryCount(ri).withRetryInterval(cf,hf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ge(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ff))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var L;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const vf=[L.PAUSED,L.PLAYING,L.READY],gf=[L.PAUSED,L.PLAYING,L.READY];class yf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Pe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new qs,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ht(h.name))!==null&&o!==void 0?o:et(h.video),S=h.bitrate/1e3,m={...h.video};if(!p)continue;const b={id:f,quality:p,bitrate:S,size:m};c.push({track:b,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(L.STOPPED));return}if(!o){if(gf.includes(n)){const c=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&vf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(ct(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:l===exports.PlaybackState.PAUSED?this.videoState.setState(L.PAUSED):l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(L.PAUSED)}));return;case L.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(L.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=xe(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.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Oe(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const n=r&&Th(r);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.READY:break;case L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new bf({videoElement:this.video,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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,n,o;const l=this.representations$.getValue(),d=(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(),u=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=jt(l.map(({track:f})=>f),{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()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.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=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.dash.reinit(ct(this.params.source.url,i))}}var bn=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},dt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,n=s.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Tf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Ef=s=>{const e=document.createElement("a");return e.href=s,e.host};class vn{constructor(e,t=[],i,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=Ut(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(Ef(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class $i{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{r($i._str2ua(m.substr(d))),d=m.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=ft(S)),this._lastXhr=new vn(S,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const b=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:b,speed:8*m.length/(b/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,b,v)=>this._params.onError(m,b,v))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=$i._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class $f{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:i(r==null?void 0:r[2],n),months:i(r==null?void 0:r[3],n),weeks:i(r==null?void 0:r[4],n),days:i(r==null?void 0:r[5],n),hours:i(r==null?void 0:r[6],n),minutes:i(r==null?void 0:r[7],n),seconds:i(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ft(i)),new vn(i,t,r=>{this.attachManifest(r,t,Tf(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,S,m,b,v,g,P,T,E,_,x,N,R,M,I,A;const O=u.getElementsByTagName("SegmentBase")[0],V=O&&o(O,"indexRange").split("-"),q=O&&O.getElementsByTagName("Initialization")[0],$=q&&o(q,"range").split("-");if(!$||!V){const be=u.parentElement;if((be==null?void 0:be.getAttribute("contentType"))==="text"){const gt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(i?i+"/":"")+((S=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||S===void 0?void 0:S.data),ie=(m=be.getAttribute("lang"))!==null&&m!==void 0?m:void 0;j&&d.push({id:gt,url:j,language:ie})}return}const C=.1,Q=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),Z=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(g=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&g!==void 0?g:void 0;ee=oe?Ys(oe):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:Q,baseURL:Z,failoverHosts:t,indexFrom:Number(V[0]),indexTo:Number(V[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(_=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&_!==void 0?_:void 0,mimeType:(N=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&N!==void 0?N:void 0,fps:ee,bufferSize:C*Q/8,bufferLength:C,name:(M=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&M!==void 0?M:void 0,id:(A=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&A!==void 0?A:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),S=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:S/l,fromOffset:u,toOffset:p-1}),u=p,d=S}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new $i({mediaSource:i,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<i.to+n){const o=this._findRef(r.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=i[i.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const kf=[B.PAUSED,B.PLAYING];class Pf{constructor(e){this.videoState=new J(B.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Pe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var i,r,n;const o=[];for(const l of t){const d=(r=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&r!==void 0?r:l.height.toString(10),u=(n=l.name&&Ht(l.name))!==null&&n!==void 0?n:et(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(B.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("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(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===D.Requested&&kf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=xe(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Oh(this.video),this.dash=new $f({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Oe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==D.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(Ei(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),S=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),b=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let v;if(!b&&a.isNonNullable(p))v=p;else{const g=dt(this.video.buffered,this.video.currentTime*1e3),P=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(g/P,1);v=(d=jt(h.map(({track:E})=>E),{container:m,throughput:S,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:E})=>E===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(v)?(u=h.find(({track:g})=>g.id===v))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,i)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=dt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=bn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ce;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ce||(ce={}));var ki;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ki||(ki={}));var he;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(he||(he={}));var H;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(H||(H={}));var pt;(function(s){s.MP4="mp4",s.WEBM="webm"})(pt||(pt={}));var Zr=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const wf=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},_f=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ea=_f?wf:window.requestIdleCallback;var ts,is;let gn=!1;try{gn=pn()&&parseInt((is=(ts=navigator.userAgent.match(/Version\/(\d+)/))===null||ts===void 0?void 0:ts[1])!==null&&is!==void 0?is:"",10)<16}catch(s){console.error(s)}class Af{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;gn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),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:a.assertNever(t)}}}var ta=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const yn=new TextDecoder("ascii"),Tn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=yn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:r,size:t,contents:o}},Rf=s=>yn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",If=s=>{const e=Tn(s),t=[];let i=0;const r=()=>{const p=e.contents.getUint32(i);return i+=4,p};if((r()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");r();const l=r(),d=r(),u=r(),c=r()&4294967295;let h=d/l*1e3,f=s.byteOffset+s.byteLength+u;for(let p=0;p<c;p++){const S=r(),m=S>>>31,b=S<<1>>>1,v=r();if(r(),m!==0)throw new Error("Unsupported multilevel sidx");const g=v/l*1e3;t.push({status:H.NONE,time:{from:h,to:h+g},byte:{from:f,to:f+b-1}}),h+=g,f+=b}return t},Nf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const n=Tn(r);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Df={validateData:Rf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:If,parseFeedableSegmentChunk:Nf};var y;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(y||(y={}));var w;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(w||(w={}));const ia={[y.EBML]:{type:w.Master},[y.EBMLVersion]:{type:w.UnsignedInteger},[y.EBMLReadVersion]:{type:w.UnsignedInteger},[y.EBMLMaxIDLength]:{type:w.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[y.DocType]:{type:w.String},[y.DocTypeVersion]:{type:w.UnsignedInteger},[y.DocTypeReadVersion]:{type:w.UnsignedInteger},[y.Void]:{type:w.Binary},[y.Segment]:{type:w.Master},[y.SeekHead]:{type:w.Master},[y.Seek]:{type:w.Master},[y.SeekID]:{type:w.Binary},[y.SeekPosition]:{type:w.UnsignedInteger},[y.Info]:{type:w.Master},[y.TimestampScale]:{type:w.UnsignedInteger},[y.Duration]:{type:w.Float},[y.Tracks]:{type:w.Master},[y.Chapters]:{type:w.Master},[y.Cluster]:{type:w.Master},[y.Timestamp]:{type:w.UnsignedInteger},[y.SilentTracks]:{type:w.Master},[y.SilentTrackNumber]:{type:w.UnsignedInteger},[y.Position]:{type:w.UnsignedInteger},[y.PrevSize]:{type:w.UnsignedInteger},[y.SimpleBlock]:{type:w.Binary},[y.BlockGroup]:{type:w.Master},[y.EncryptedBlock]:{type:w.Binary},[y.Attachments]:{type:w.Master},[y.Tags]:{type:w.Master},[y.Cues]:{type:w.Master},[y.CuePoint]:{type:w.Master},[y.CueTime]:{type:w.UnsignedInteger},[y.CueTrackPositions]:{type:w.Master},[y.CueTrack]:{type:w.UnsignedInteger},[y.CueClusterPosition]:{type:w.UnsignedInteger},[y.CueRelativePosition]:{type:w.UnsignedInteger},[y.CueDuration]:{type:w.UnsignedInteger},[y.CueBlockNumber]:{type:w.UnsignedInteger},[y.CueCodecState]:{type:w.UnsignedInteger},[y.CueReference]:{type:w.Master},[y.CueRefTime]:{type:w.UnsignedInteger}},En=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Pi(s,t),r=i in ia,n=r?ia[i].type:w.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Pi(d),c=t+l;let h;return c+u>s.byteLength?h=new DataView(s.buffer,s.byteOffset+c):h=new DataView(s.buffer,s.byteOffset+c,u),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Pi=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint16(0)<<8|s.getUint8(2);case 4:return s.getUint32(0);case 5:return s.getUint32(0)<<8|s.getUint8(4);case 6:return s.getUint32(0)<<16|s.getUint16(4);case 7:return s.getUint32(0)<<32|s.getUint16(4)<<8|s.getUint8(6);case 8:return s.getUint32(0)<<32|s.getUint32(4)}return 0},Re=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return Pi(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:a.assertNever(e)}},Gt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=En(i);if(!e(r))return;r.type===w.Master&&Gt(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Cf=s=>{if(s.getUint32(0)!==y.EBML)return!1;let e,t,i;const r=En(s);return Gt(r.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Re(l,o):n===y.DocType?t=Re(l,o):n===y.DocTypeReadVersion&&(i=Re(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},$n=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Lf=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],xf=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u;return Gt(s,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const S=Re(f,h);u=Pi(S)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?i=Re(f,h):c===y.Duration?r=Re(f,h):c===y.SeekPosition&&u===y.Cues?d=Re(f,h):n&&o&&$n.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d}},Of=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Bf=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Gt(s,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&r(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Re(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Re(u,d));break;default:t&&$n.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:H.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Mf=s=>{let e=0,t=!1;try{Gt(s,i=>i.tag===y.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Lf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Vf={validateData:Cf,parseInit:xf,getIndexRange:Of,parseSegments:Bf,parseFeedableSegmentChunk:Mf};class sa{constructor(e,t,i,r,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Je,this.destroyAbortController=new Je,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Af(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),S=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,ta(this.sourceBuffer.buffered));this.bufferLimit=m,this.pruneBuffer(S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let p=0;for(const S of f)S.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:S.time.from}),p=S.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=i,i){case pt.MP4:this.containerParser=Df;break;case pt.WEBM:this.containerParser=Vf;break;default:a.assertNever(i)}this.initData=new Map(r.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(r.map(u=>[u.id,u])),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 Je,this.abortBuffer()}maintain(e){if(a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=dt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ta(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),r&&r.status!==H.NONE))return;let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=_e(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.allInitsLoaded&&r&&r.status===H.FED&&!l.length&&dt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=_e(i,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}destroy(){var e;this.initData.clear(),this.segments.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:d,time:{from:u,to:c}})=>d===H.NONE&&(u>i||u<=i&&c>=i)&&c<=i+this.forwardBufferTarget);if(r===-1)return[];if(t!==he.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0;const l=[];for(let d=r;d<n.length&&o<=this.tuning.dash.segmentRequestSize;d++){const u=n[d];if(o+=u.byte.to+1-u.byte.from,u.status===H.NONE||u.status===H.PARTIALLY_EJECTED)l.push(u);else break}return l}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case he.BYTE_RANGE:{r=t.segmentReference.url,n={from:_e(e,0).byte.from,to:_e(e,-1).byte.to};break}case he.TEMPLATE:{const u=_e(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await a.abortable(d,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=dt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,n){if(!this.activeSegments.size)return;const o=h=>{this.abortSegment(h.segment)},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const S of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])S.status===H.FED&&S.time.from===h.segment.time.from&&S.time.to===h.segment.time.to&&(S.status=H.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===he.BYTE_RANGE,S=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o(h);continue}const b=p?f.byte.from-i:0,v=p?f.byte.to-i:e.byteLength,g=b<r,P=v<=r;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(S,r-b),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===S?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(_=>{if(n.aborted)o(h);else if(_)h.fedBytes+=E.byteLength,h.fedBytes===S&&l(h);else{if(h.feedingBytes<S)return;o(h)}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ea(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(t)||this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let r=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of i){if(u.time.to>=t||r>=e)break;u.status===H.FED&&d(u)}if(l=isFinite(n)&&isFinite(o),!l){r=0,n=1/0,o=-1/0;for(const u of i){if(u.time.from<t+this.forwardBufferTarget||r>e)break;u.status===H.FED&&d(u)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of i)if(f.status===H.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!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)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>=1&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ea(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),l=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?r.status=H.PARTIALLY_EJECTED:r.status=H.NONE)}}}var lt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(lt||(lt={}));class Ff{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Je,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=ft(n));const o=yield ht(n,{signal:this.abortAllController.signal}).catch(Dt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?lt.HEADER:lt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,S;let m=r;const b=new Headers;if(o)switch(n){case lt.HEADER:{b.append("Range",`${o.from}-${o.to}`);break}case lt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=ft(m));let v=this.abortAllController.signal;if(u){const $=new Je;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(C){Dt(C)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(C){Dt(C)}v=$.signal}const g=a.now(),P=yield ht(m,{priority:d,headers:b,signal:v}).catch(Dt),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-g),!P)return null;if(!P.ok||!P.body)return Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`));this.onHeadersReceived(P.headers);const E=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const $=yield P.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return P.arrayBuffer();const[_,x]=P.body.tee(),N=_.getReader();c&&((S=this.throughputEstimator)===null||S===void 0||S.trackStream(x));let R=0;const M=new ArrayBuffer(E),I=new Uint8Array(M),A=new DataView(M);let O=!1;const V=$=>{O=!0,Dt($)},q=a.abortable(v,async function*({done:$,value:C}){R===0&&this.lastRequestFirstBytes$.next(a.now()-g),!v.aborted&&($?l==null||l(A,R):C&&(I.set(C,R),R+=C.byteLength,l==null||l(A,R),yield N==null?void 0:N.read().then(q,V)))}.bind(this));return yield N==null?void 0:N.read().then(q,V),O?null:M}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){if(r.type!==he.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(p,d))),u=Math.min(u,0);const S=yield this.fetch(r.url,{range:{from:u,to:c},priority:o,measureThroughput:!1});if(!S)return null;const m=new DataView(S,l-u,d-u+1);if(!n.validateData(m))throw new Error("Invalid media file");const b=n.parseInit(m);let v;if(h&&f!==void 0&&p!==void 0)v=new DataView(S,f-u,p-f+1);else{const P=n.getIndexRange(b);if(P){const T=yield this.fetch(r.url,{range:P,priority:o,measureThroughput:!1});if(!T)return null;v=new DataView(T)}}if(!v)throw new ReferenceError("No way to load representation index");const g=n.parseSegments(v,b);return{dataView:new DataView(S),segments:g}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==he.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:r.segments.map(u=>({...u,status:H.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=bn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case he.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case he.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Dt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s},ra=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},ss=(s,e)=>{let t=s;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Uf=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,S,m,b,v,g,P,T,E,_,x,N,R,M,I,A,O,V,q,$,C,Q,Z,ee,oe,be;const j=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},ae=j.children[0],ue=ae.getElementsByTagName("Period")[0],qe=ue.children;let ve;const Be=ae.getAttribute("mediaPresentationDuration"),Ye=ue.getAttribute("duration");if(Be)ve=ra(Be);else if(Ye){const ge=ra(Ye);a.isNonNullable(ge)&&(ve=ge)}let yt=0;const it=(i=(t=ae.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_n=it.includes(ki.WEBM_AS_IN_FFMPEG)||it.includes(ki.WEBM_AS_IN_SPEC)?pt.WEBM:pt.MP4;for(const ge of qe){const qt=ge.getAttribute("mimeType"),An=ge.getAttribute("codecs"),Qs=(r=ge.getAttribute("contentType"))!==null&&r!==void 0?r:qt==null?void 0:qt.split("/")[0],Rn=(o=(n=ge.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],In=ge.querySelectorAll("Representation"),Nn=ge.querySelector("SegmentTemplate");if(Qs!=="text")for(const se of In){const Tt=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:qt,Ws=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:An)!==null&&u!==void 0?u:"",Yt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:Tt==null?void 0:Tt.split("/")[0])!==null&&h!==void 0?h:Qs,Dn=(p=(f=ge.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],Cn=parseInt((S=se.getAttribute("width"))!==null&&S!==void 0?S:"",10),Js=parseInt((m=se.getAttribute("height"))!==null&&m!==void 0?m:"",10),Ks=parseInt((b=se.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Xs=(v=se.getAttribute("frameRate"))!==null&&v!==void 0?v:"",Ln=(g=se.getAttribute("quality"))!==null&&g!==void 0?g:void 0,xn=Xs?Ys(Xs):void 0,On=(P=se.getAttribute("id"))!==null&&P!==void 0?P:(yt++).toString(10),Bn=Yt==="video"?`${Js}p`:Yt==="audio"?`${Ks}Kbps`:Ws,Mn=`${On}@${Bn}`,Vn=(_=(E=(T=se.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&_!==void 0?_:"",Zs=new URL(Vn,e).toString(),Fn=[...it,...Rn,...Dn];let Ii;const Un=se.querySelector("SegmentBase"),ze=(x=se.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Nn;if(Un){const Et=(R=(N=se.querySelector("SegmentBase Initialization"))===null||N===void 0?void 0:N.getAttribute("range"))!==null&&R!==void 0?R:"",[$t,Di]=Et.split("-").map(Qe=>parseInt(Qe,10)),kt={from:$t,to:Di},Pt=(M=se.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ci,zt]=Pt?Pt.split("-").map(Qe=>parseInt(Qe,10)):[],wt=Pt?{from:Ci,to:zt}:void 0;Ii={type:he.BYTE_RANGE,url:Zs,initRange:kt,indexRange:wt}}else if(ze){const Et={representationId:(I=se.getAttribute("id"))!==null&&I!==void 0?I:void 0,bandwidth:(A=se.getAttribute("bandwidth"))!==null&&A!==void 0?A:void 0},$t=parseInt((O=ze.getAttribute("timescale"))!==null&&O!==void 0?O:"",10),Di=(V=ze.getAttribute("initialization"))!==null&&V!==void 0?V:"",kt=ze.getAttribute("media"),Pt=($=parseInt((q=ze.getAttribute("startNumber"))!==null&&q!==void 0?q:"",10))!==null&&$!==void 0?$:1,Ci=ss(Di,Et);if(!kt)throw new ReferenceError("No media attribute in SegmentTemplate");const zt=(C=ze.querySelectorAll("SegmentTimeline S"))!==null&&C!==void 0?C:[],wt=[];if(zt.length){let Qe=Pt,We=0;for(const _t of zt){const st=parseInt((Q=_t.getAttribute("d"))!==null&&Q!==void 0?Q:"",10)*1e3,At=parseInt((Z=_t.getAttribute("r"))!==null&&Z!==void 0?Z:"",10)||0,Rt=(oe=parseInt((ee=_t.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let er=0;er<At+1;er++){const jn=ss(kt,{...Et,segmentNumber:Qe.toString(10),segmentTime:Rt.toString(10)}),Hn=Rt?Rt/$t:We;We+=st/$t;const Gn=We;Qe++,wt.push({time:{from:Hn,to:Gn},url:jn})}}}else if(a.isNonNullable(ve)){const We=parseInt((be=ze.getAttribute("duration"))!==null&&be!==void 0?be:"",10)/$t*1e3,_t=Math.ceil(ve/We);let st=0;for(let At=1;At<_t;At++){const Rt=ss(kt,{...Et,segmentNumber:At.toString(10),segmentTime:st.toString(10)});wt.push({time:{from:st,to:st+We},url:Rt}),st+=We}}Ii={type:he.TEMPLATE,baseUrl:Zs,initUrl:Ci,segments:wt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Yt||!Tt)continue;const Ni={video:ce.VIDEO,audio:ce.AUDIO,text:ce.TEXT}[Yt];Ni&&ie[Ni].push({id:Mn,kind:Ni,segmentReference:Ii,profiles:Fn,duration:ve,bitrate:Ks,mime:Tt,codecs:Ws,width:Cn,height:Js,fps:xn,quality:Ln})}}return{duration:ve,container:_n,representations:ie}},jf=["timeupdate","progress","play","seeked","stalled"];var de;(function(s){s.NONE="none",s.MANIFEST_LOADED="manifest_loaded",s.REPRESENTATION_SELECTED="representation_selected"})(de||(de={}));let Hf=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new J(de.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Je,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(de.MANIFEST_LOADED);const r=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!r)return null;let n;try{n=Uf(r!=null?r:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return null;const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};return this.manifest={...n,representations:Ut(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(de.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"}),this.manifest}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(de.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new sa(ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new sa(ce.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(de.REPRESENTATION_SELECTED),a.assertNonNullable(this.element),this.subscription.add(a.merge(...jf.map(l=>a.fromEvent(this.element,l)),a.fromEvent(window,"online")).subscribe(this.tick,l=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:l})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Zr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}.bind(this)),this.tick=()=>{var t,i;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||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ff({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async switchRepresentation(e,t){const i={[ce.VIDEO]:this.videoBufferManager,[ce.AUDIO]:this.audioBufferManager,[ce.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Zr(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(de.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const Gf=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ht(n):void 0)!==null&&o!==void 0?o:et({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},qf=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=_e(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:_e(s,-1)};class Yf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(K.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Pe,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ef,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===D.Requested&&(r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&t!==K.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.player.stop(),this.video.setAttribute("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(K.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}switch(t){case K.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=xe(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Hf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Oe(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:d})},n=(d,u)=>this.subscription.add(d.subscribe(u,r));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),n(Ei(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(a.filter(({to:d})=>d===de.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(K.READY)}));const o=d=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{var d,u,c,h,f,p,S,m;const b=this.player.state$.getState(),v=this.player.state$.getTransition();if(b===de.NONE||!this.videoTracks.length)return;const g=b===de.MANIFEST_LOADED&&!v,P=b===de.REPRESENTATION_SELECTED&&!v,T=t.autoVideoTrackSwitching.getState(),E=t.videoTrack.getState(),_=(d=this.videoTracks.find(({track:{id:V}})=>V===E))===null||d===void 0?void 0:d.track,x=e.currentVideoTrack$.getValue(),N=dt(this.video.buffered,this.video.currentTime*1e3),R=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,M=Math.min(N/Math.min(R,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),I=Math.max(_&&!T&&(c=(u=this.audioRepresentations.get(_.id))===null||u===void 0?void 0:u.bitrate)!==null&&c!==void 0?c:0,x&&(f=(h=this.audioRepresentations.get(x.id))===null||h===void 0?void 0:h.bitrate)!==null&&f!==void 0?f:0),A=jt(this.videoTracks.map(({track:V})=>V),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:M,current:x,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),O=T?A!=null?A:_:_!=null?_:A;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(T),this.player.setBufferTarget(R)),g){const V=O&&((p=this.videoTracks.find(({track:q})=>q===O))===null||p===void 0?void 0:p.representation);a.assertNonNullable(V),this.player.initRepresentations(V.id,(S=this.audioRepresentations.get(V.id))===null||S===void 0?void 0:S.id)}else if(P){const V=O&&((m=this.videoTracks.find(({track:q})=>q===O))===null||m===void 0?void 0:m.representation);if(V){const q=this.audioRepresentations.get(V.id);this.player.switchRepresentation(ce.VIDEO,V.id).catch(o),q&&this.player.switchRepresentation(ce.AUDIO,q.id).catch(o)}}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(d=>{var u;return d&&((u=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const l=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((r,n)=>n.bitrate-r.bitrate),i=Array.from(e.representations.video).sort((r,n)=>n.bitrate-r.bitrate);for(const r of i){const n=Gf(r);if(n){this.videoTracks.push({track:n,representation:r});const o=qf(t,i,r);o&&this.audioRepresentations.set(r.id,o)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:r})=>r))}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const zf=5e3,we={};var G;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(G||(G={}));const ai=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Qf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(G.INITIALIZING),this.textTracksManager=new Pe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==G.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case G.STOPPED:break;case G.READY:case G.PLAYING:case G.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case G.PLAYING:break;case G.STOPPED:this.prepare();break;case G.READY:case G.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case G.PAUSED:break;case G.STOPPED:this.prepare();break;case G.READY:this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case G.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ne(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),zf);import("hls.js").then(r=>{e||(we.Hls=r.default,we.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(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(G.STOPPED)}subscribe(){a.assertNonNullable(we.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=Oe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(tt(this.video,e.isLooped,i)),this.subscription.add(Le(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(ai(this.hls,we.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},i)),n(ai(this.hls,we.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const S=h.name||h.height.toString(10),{width:m,height:b}=h,v=(p=Ht((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:et({width:m,height:b});if(!v)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:S.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:m,height:b},fps:g};return this.trackLevels.set(S,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(ai(this.hls,we.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add($e(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=ai(this.hls,we.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add($e(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,S=this.hls.levels[p];!S||h.bitrate>S.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:i})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(G.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(G.PLAYING),await Ge(this.video)||(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(G.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.setAttribute("src",""),this.video.load(),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const aa="X-Playback-Duration";var na=async s=>{const e=await ht(s,{method:"HEAD"});return e.headers.has(aa)?parseInt(e.headers.get(aa),10):void 0};const Wf=s=>{let e=null;if(s.QUALITY&&(e=Ht(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=et({width:t,height:i})}return e!=null?e:null},kn=async(s,e=s)=>{var t;const n=(await(await ht(s)).text()).split(`
|
|
8
|
+
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=Ut(u[1].split(",").map(v=>v.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Wf(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[v,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));v&&g&&(m={width:v,height:g})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:p,size:m,fps:S})}return o};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Y||(Y={}));class Jf{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Y.STOPPED),this.textTracksManager=new Pe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new qs,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){r!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.setAttribute("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(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===D.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case Y.READY:n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),kn(ct(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,n=i.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===D.Requested&&this.seek(l.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=ct(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),na(t).then(i=>{var r;if(!a.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{ht(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();na(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var W;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(W||(W={}));class Kf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(W.STOPPED),this.textTracksManager=new Pe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===exports.PlaybackState.STOPPED){i!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.setAttribute("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(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&this.seek(u.position),i){case W.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(i)}},this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ne(this.params.source.url)),kn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,n=i.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===D.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));class Xf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(X.STOPPED),this.trackUrls={},this.textTracksManager=new Pe,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.video.setAttribute("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(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===X.STOPPED){this.videoState.startTransitionTo(X.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&this.seek(l.position),t){case X.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===X.READY&&this.videoState.setState(X.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();a.assertNonNullable(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];a.assertNonNullable(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=ft(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(ne(r))}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const oa=["stun:videostun.mycdn.me:80"],Zf=1e3,ep=3,rs=()=>null;class tp{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=rs,this.externalStopCallback=rs,this.externalErrorCallback=rs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{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}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:oa}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(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),Zf)}normalizeOptions(e={}){const t={stunServerList:oa,maxRetryNumber:ep,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));class ip{constructor(e){this.videoState=new J(z.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==z.STOPPED&&(this.videoState.startTransitionTo(z.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(z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case z.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=xe(e.container),this.liveStreamClient=new tp(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const r=Oe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.READY&&this.videoState.setState(z.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Le(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case z.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case z.READY:break;case z.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case z.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(z.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:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class la{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 Boolean(this.current.done)}}var sp=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},as,ns,os,ls,us,ds,ni,cs,oi,hs,li,fs,ui,ps,di,ms;const Pn=sp(),Ve=document.createElement("video"),Me={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ns=(as=window.SourceBuffer)===null||as===void 0?void 0:as.prototype)===null||ns===void 0?void 0:ns.appendBuffer)),hls:Boolean(((os=Ve.canPlayType)===null||os===void 0?void 0:os.call(Ve,"application/x-mpegurl"))||((ls=Ve.canPlayType)===null||ls===void 0?void 0:ls.call(Ve,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Te={mp4:Boolean((us=Ve.canPlayType)===null||us===void 0?void 0:us.call(Ve,"video/mp4")),webm:Boolean((ds=Ve.canPlayType)===null||ds===void 0?void 0:ds.call(Ve,"video/webm"))},Fe={h264:Boolean((cs=(ni=window.MediaSource)===null||ni===void 0?void 0:ni.isTypeSupported)===null||cs===void 0?void 0:cs.call(ni,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((hs=(oi=window.MediaSource)===null||oi===void 0?void 0:oi.isTypeSupported)===null||hs===void 0?void 0:hs.call(oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((fs=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||fs===void 0?void 0:fs.call(li,'video/webm; codecs="vp9"')),aac:Boolean((ps=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||ps===void 0?void 0:ps.call(ui,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ms=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||ms===void 0?void 0:ms.call(di,'audio/webm; codecs="opus"'))},Ct=(Fe.h264||Fe.h265)&&Fe.aac,Ri=Me.hls&&Te.mp4,rp=Boolean(window.WebSocket),ap=()=>Object.keys(Fe).filter(s=>Fe[s]),np=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_SEP:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_WEBM:return Me.mse&&Te.webm&&Fe.vp9&&Fe.opus;case exports.VideoFormat.DASH_LIVE:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_ONDEMAND:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return Ri||e&&Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.MPEG:return Te.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Me.webrtc&&rp&&Fe.h264&&(Te.mp4||Te.webm);default:return a.assertNever(t)}}),op=()=>Pn?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Ri?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],lp=()=>Pn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:Ri?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],ua=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var up=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const da={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},dp={cacheDuration:12e4},cp={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},hp={maxPausedTime:3e4},fp={maxPausedTime:3e4};class pp{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=np([...lp(),...op()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new la(r);const n=[...ua(!0),...ua(!1)];this.chromecastFormatsIterator=new la(n.filter(o=>a.isNonNullable(e.sources[o])))}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(a.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(e,"No current provider"),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,i=this.params.desiredState.seekState.getState(),r=i.state!==D.None;this.params.desiredState.seekState.setState({state:D.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Pf({...o,source:l,config:dp})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new rf({...o,source:l,format:e,config:fp}):new Yf({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),Ri||!this.params.tuning.useHlsJs?new Kf({...o,source:l}):new Qf({...o,source:l})}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Jf({...o,source:l,config:hp})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Xf({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yf({...o,source:l,config:cp})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new ip({container:i,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new wh({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ut(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;return e.add(a.merge(this.providerOutput.error$,up({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:da.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:r})=>r!==void 0))}).pipe(a.map(r=>({id:`ProviderHangup:${r}`,category:a.ErrorCategory.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(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<da.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const ca=(s,e,t)=>t*e+(1-t)*s;class ha{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ee(`raw_${i}`),this.smoothedSeries$=new Ee(`smoothed_${i}`),this.reportedSeries$=new Ee(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let d=0;d<this.pastMeasures.length;d++)this.pastMeasures[d]!==void 0&&(t+=(this.pastMeasures[d]-this.smoothed)**2,i++);t/=i;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=ca(this.slow,e,this.params.emaAlphaSlow),this.fast=ca(this.fast,e,this.params.emaAlphaFast);const l=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=l(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(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 fe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(fe||(fe={}));const wn=new Map;let Ke=fe.RUNTIME;const Ss=`vk-videoplayer-dummy-key-${Math.random()}`,mp=()=>{try{localStorage.setItem(Ss,"test"),localStorage.removeItem(Ss),Ke=fe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Ss),Ke=fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Ke=fe.RUNTIME;else throw e}else throw s}};mp();const Sp=s=>{var e,t;switch(Ke){case fe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case fe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case fe.RUNTIME:return wn.get(s);default:a.assertNever(Ke)}},fa=(s,e)=>{switch(Ke){case fe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case fe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case fe.RUNTIME:return void wn.set(s,e);default:a.assertNever(Ke)}},bp=5e3,pa="one_video_throughput",ma="one_video_rtt",Ne=window.navigator.connection,Sa=()=>{const s=Ne==null?void 0:Ne.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},ba=()=>{const s=Ne==null?void 0:Ne.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},va=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Ot{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ot.load(pa)||(e.useBrowserEstimation?Sa():void 0)||bp,n=(i=(t=Ot.load(ma))!==null&&t!==void 0?t:e.useBrowserEstimation?ba():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(va(r,n,e.rttPenaltyRequestSize)),this.throughput=new ha({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new ha({initial:n,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const o=()=>{const d=Sa();d&&this.throughput.next(d);const u=ba();a.isNonNullable(u)&&this.rtt.next(u)};Ne&&"onchange"in Ne&&this.subscription.add(a.fromEvent(Ne,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{fa(pa,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{fa(ma,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>va(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,a.now()-r,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Ot.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Sp(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const ga={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}},vp=s=>{const e={};for(const t of Object.keys(ga)){const i=ga[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var gp=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===D.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===D.None))),yp=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const ya=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new a.Observable(n=>{let o;const l=s.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var S,m;return p.state===D.Requested&&((m=(S=s.getTransition())===null||S===void 0?void 0:S.from)!==null&&m!==void 0?m:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:S})=>{var m,b;return p.state===D.Applying&&S.state===D.None&&((b=(m=s.getTransition())===null||m===void 0?void 0:m.from)!==null&&b!==void 0?b:s.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>r.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),i).pipe(a.map(()=>r.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const S={from:o,to:p};o=void 0,n.next(S)}))});class Tp{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new J(exports.PlaybackState.STOPPED),seekState:new J({state:D.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:Kh},this.initLogs(),this.tuning=vp(e),this.chromecastInitializer=new to({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ot(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=yp(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new pp({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},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},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:D.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){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===D.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=a.now(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===D.Requested?this.desiredState.seekState.setState({...d,state:D.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===D.Applying&&(this.desiredState.seekState.setState({state:D.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>yi(u)?1:yi(c)?-1:pi(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate);const u=e.providerOutput.element$.getValue();u&&this.info.intrinsicVideoSize$.next({width:u.videoWidth,height:u.videoHeight})})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).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.currentBuffer$.pipe(a.map(d=>d?{start:d.from,end:d.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(gp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).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(a.map(d=>({id:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(ya({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ya({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(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 a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=jt(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(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;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),Jh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Wh(i)),this.providerContainer.current$.subscribe(({type:i})=>ii("provider",i)),t.duration$.subscribe(i=>ii("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>ii("tracks",i)),this.events.fatalError$.subscribe(new Ee("fatalError")),this.events.managedError$.subscribe(new Ee("managedError")),t.position$.subscribe(new Ee("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new Ee("quality")),this.info.currentBuffer$.subscribe(new Ee("buffer")),t.isBuffering$.subscribe(new Ee("isBuffering"))].forEach(i=>this.subscription.add(i)),ii("codecs",ap())}}const Ep=`${Zn}@${Xn}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=Tp;exports.SDK_VERSION=Ep;
|