@vkontakte/videoplayer-core 2.0.45 → 2.0.46
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 +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/package.json +1 -1
- package/player/Player.d.ts +1 -0
- package/player/types.d.ts +8 -0
- package/providers/ProviderContainer/index.d.ts +1 -0
- package/providers/types.d.ts +1 -0
package/es2015.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/playersdk/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.46
|
|
3
|
+
* Mon, 28 Mar 2022 12:12:14 GMT
|
|
4
|
+
* https://st.mycdn.me/static/playersdk/2-0-46/doc/
|
|
5
5
|
*/
|
|
6
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2015.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'));var r,a,n,o,u,d;exports.PlaybackState=void 0,(r=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',r.PLAYING='playing',r.PAUSED='paused',exports.VideoFormat=void 0,(a=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',a.DASH='DASH',a.DASH_SEP='DASH_SEP',a.DASH_SEP_VK='DASH_SEP_VK',a.DASH_WEBM='DASH_WEBM',a.DASH_WEBM_VK='DASH_WEBM_VK',a.DASH_ONDEMAND='DASH_ONDEMAND',a.DASH_LIVE='DASH_LIVE',a.DASH_LIVE_WEBM='DASH_LIVE_WEBM',a.HLS='HLS',a.HLS_ONDEMAND='HLS_ONDEMAND',a.HLS_JS='HLS_JS',a.HLS_LIVE='HLS_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(n||(n={})),exports.ChromecastState=void 0,(o=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',o.AVAILABLE='AVAILABLE',o.CONNECTING='CONNECTING',o.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(d=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',d.HTTP2='http2',d.QUIC='quic';const l={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],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};class c{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;var r;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(r='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',r),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',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,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.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,r;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(r=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===r?void 0:r.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((r=>{var a;const n=r===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const r=s.getCurrentSession();t.assertNonNullable(r);const n=r.getCastDevice(),o=null===(a=r.getMediaSession())||void 0===a?void 0:a.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:r,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}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)}};function p(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{u(s.next(t))}catch(t){a(t)}}function o(t){try{u(s.throw(t))}catch(t){a(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}u((s=s.apply(t,e||[])).next())}))}var m='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},f=function(t){return t&&t.Math==Math&&t},v=f('object'==typeof globalThis&&globalThis)||f('object'==typeof window&&window)||f('object'==typeof self&&self)||f('object'==typeof m&&m)||function(){return this}()||Function('return this')(),b=function(t){try{return!!t()}catch(t){return!0}},S=!b((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),g=S,y=Function.prototype,T=y.apply,E=y.call,P='object'==typeof Reflect&&Reflect.apply||(g?E.bind(T):function(){return E.apply(T,arguments)}),w=S,k=Function.prototype,$=k.bind,A=k.call,x=w&&$.bind(A,A),N=w?function(t){return t&&x(t)}:function(t){return t&&function(){return A.apply(t,arguments)}},_=function(t){return'function'==typeof t},D={},R=!b((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),I=S,L=Function.prototype.call,C=I?L.bind(L):function(){return L.apply(L,arguments)},O={},V={}.propertyIsEnumerable,M=Object.getOwnPropertyDescriptor,B=M&&!V.call({1:2},1);O.f=B?function(t){var e=M(this,t);return!!e&&e.enumerable}:V;var F,U,j=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},H=N,q=H({}.toString),G=H(''.slice),Y=function(t){return G(q(t),8,-1)},z=N,Q=b,W=Y,J=v.Object,K=z(''.split),X=Q((function(){return!J('z').propertyIsEnumerable(0)}))?function(t){return'String'==W(t)?K(t,''):J(t)}:J,Z=v.TypeError,tt=function(t){if(null==t)throw Z('Can\'t call method on '+t);return t},et=X,it=tt,st=function(t){return et(it(t))},rt=_,at=function(t){return'object'==typeof t?null!==t:rt(t)},nt={},ot=nt,ut=v,dt=_,lt=function(t){return dt(t)?t:void 0},ct=function(t,e){return arguments.length<2?lt(ot[t])||lt(ut[t]):ot[t]&&ot[t][e]||ut[t]&&ut[t][e]},ht=N({}.isPrototypeOf),pt=ct('navigator','userAgent')||'',mt=v,ft=pt,vt=mt.process,bt=mt.Deno,St=vt&&vt.versions||bt&&bt.version,gt=St&&St.v8;gt&&(U=(F=gt.split('.'))[0]>0&&F[0]<4?1:+(F[0]+F[1])),!U&&ft&&(!(F=ft.match(/Edge\/(\d+)/))||F[1]>=74)&&(F=ft.match(/Chrome\/(\d+)/))&&(U=+F[1]);var yt=U,Tt=yt,Et=b,Pt=!!Object.getOwnPropertySymbols&&!Et((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Tt&&Tt<41})),wt=Pt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,kt=ct,$t=_,At=ht,xt=wt,Nt=v.Object,_t=xt?function(t){return'symbol'==typeof t}:function(t){var e=kt('Symbol');return $t(e)&&At(e.prototype,Nt(t))},Dt=v.String,Rt=function(t){try{return Dt(t)}catch(t){return'Object'}},It=_,Lt=Rt,Ct=v.TypeError,Ot=function(t){if(It(t))return t;throw Ct(Lt(t)+' is not a function')},Vt=Ot,Mt=function(t,e){var i=t[e];return null==i?void 0:Vt(i)},Bt=C,Ft=_,Ut=at,jt=v.TypeError,Ht={exports:{}},qt=v,Gt=Object.defineProperty,Yt=function(t,e){try{Gt(qt,t,{value:e,configurable:!0,writable:!0})}catch(i){qt[t]=e}return e},zt=v['__core-js_shared__']||Yt('__core-js_shared__',{}),Qt=zt;(Ht.exports=function(t,e){return Qt[t]||(Qt[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.21.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.21.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Wt=tt,Jt=v.Object,Kt=function(t){return Jt(Wt(t))},Xt=Kt,Zt=N({}.hasOwnProperty),te=Object.hasOwn||function(t,e){return Zt(Xt(t),e)},ee=N,ie=0,se=Math.random(),re=ee(1..toString),ae=function(t){return'Symbol('+(void 0===t?'':t)+')_'+re(++ie+se,36)},ne=v,oe=Ht.exports,ue=te,de=ae,le=Pt,ce=wt,he=oe('wks'),pe=ne.Symbol,me=pe&&pe.for,fe=ce?pe:pe&&pe.withoutSetter||de,ve=function(t){if(!ue(he,t)||!le&&'string'!=typeof he[t]){var e='Symbol.'+t;le&&ue(pe,t)?he[t]=pe[t]:he[t]=ce&&me?me(e):fe(e)}return he[t]},be=C,Se=at,ge=_t,ye=Mt,Te=function(t,e){var i,s;if('string'===e&&Ft(i=t.toString)&&!Ut(s=Bt(i,t)))return s;if(Ft(i=t.valueOf)&&!Ut(s=Bt(i,t)))return s;if('string'!==e&&Ft(i=t.toString)&&!Ut(s=Bt(i,t)))return s;throw jt('Can\'t convert object to primitive value')},Ee=ve,Pe=v.TypeError,we=Ee('toPrimitive'),ke=function(t,e){if(!Se(t)||ge(t))return t;var i,s=ye(t,we);if(s){if(void 0===e&&(e='default'),i=be(s,t,e),!Se(i)||ge(i))return i;throw Pe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Te(t,e)},$e=_t,Ae=function(t){var e=ke(t,'string');return $e(e)?e:e+''},xe=at,Ne=v.document,_e=xe(Ne)&&xe(Ne.createElement),De=function(t){return _e?Ne.createElement(t):{}},Re=De,Ie=!R&&!b((function(){return 7!=Object.defineProperty(Re('div'),'a',{get:function(){return 7}}).a})),Le=R,Ce=C,Oe=O,Ve=j,Me=st,Be=Ae,Fe=te,Ue=Ie,je=Object.getOwnPropertyDescriptor;D.f=Le?je:function(t,e){if(t=Me(t),e=Be(e),Ue)try{return je(t,e)}catch(t){}if(Fe(t,e))return Ve(!Ce(Oe.f,t,e),t[e])};var He=b,qe=_,Ge=/#|\.prototype\./,Ye=function(t,e){var i=Qe[ze(t)];return i==Je||i!=We&&(qe(e)?He(e):!!e)},ze=Ye.normalize=function(t){return String(t).replace(Ge,'.').toLowerCase()},Qe=Ye.data={},We=Ye.NATIVE='N',Je=Ye.POLYFILL='P',Ke=Ye,Xe=Ot,Ze=S,ti=N(N.bind),ei=function(t,e){return Xe(t),void 0===e?t:Ze?ti(t,e):function(){return t.apply(e,arguments)}},ii={},si=R&&b((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ri=v,ai=at,ni=ri.String,oi=ri.TypeError,ui=function(t){if(ai(t))return t;throw oi(ni(t)+' is not an object')},di=R,li=Ie,ci=si,hi=ui,pi=Ae,mi=v.TypeError,fi=Object.defineProperty,vi=Object.getOwnPropertyDescriptor;ii.f=di?ci?function(t,e,i){if(hi(t),e=pi(e),hi(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=vi(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 fi(t,e,i)}:fi:function(t,e,i){if(hi(t),e=pi(e),hi(i),li)try{return fi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw mi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var bi=ii,Si=j,gi=R?function(t,e,i){return bi.f(t,e,Si(1,i))}:function(t,e,i){return t[e]=i,t},yi=v,Ti=P,Ei=N,Pi=_,wi=D.f,ki=Ke,$i=nt,Ai=ei,xi=gi,Ni=te,_i=function(t){var e=function(i,s,r){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,r)}return Ti(t,this,arguments)};return e.prototype=t.prototype,e},Di=function(t,e){var i,s,r,a,n,o,u,d,l=t.target,c=t.global,h=t.stat,p=t.proto,m=c?yi:h?yi[l]:(yi[l]||{}).prototype,f=c?$i:$i[l]||xi($i,l,{})[l],v=f.prototype;for(r in e)i=!ki(c?r:l+(h?'.':'#')+r,t.forced)&&m&&Ni(m,r),n=f[r],i&&(o=t.noTargetGet?(d=wi(m,r))&&d.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(u=t.bind&&i?Ai(a,yi):t.wrap&&i?_i(a):p&&Pi(a)?Ei(a):a,(t.sham||a&&a.sham||n&&n.sham)&&xi(u,'sham',!0),xi(f,r,u),p&&(Ni($i,s=l+'Prototype')||xi($i,s,{}),xi($i[s],r,a),t.real&&v&&!v[r]&&xi(v,r,a)))},Ri=Math.ceil,Ii=Math.floor,Li=function(t){var e=+t;return e!=e||0===e?0:(e>0?Ii:Ri)(e)},Ci=Li,Oi=Math.min,Vi=function(t){return t>0?Oi(Ci(t),9007199254740991):0},Mi=function(t){return Vi(t.length)},Bi=Kt,Fi=Mi,Ui=Li;Di({target:'Array',proto:!0},{at:function(t){var e=Bi(this),i=Fi(e),s=Ui(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var ji,Hi,qi,Gi,Yi=ct,zi=Yi('Array','at');!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ji||(ji={})),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'}(Hi||(Hi={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(qi||(qi={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Gi||(Gi={}));var Qi=t=>p(void 0,void 0,void 0,(function*(){const e=t.muted;try{yield 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{yield t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0}));const Wi=(e,i,s,{equal:r=((t,e)=>t===e),changed$:a,onError:n}={})=>{const o=e.getState(),u=i(),d=t.isNullable(a),l=new t.Subscription;return a&&l.add(a.subscribe((t=>{const i=e.getState();r(t,i)&&e.setState(t)}),n)),r(u,o)||(s(o),d&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),d&&e.setState(t.to)}),n)),l},Ji=(e,i,s)=>Wi(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Ki=(e,i,s,r)=>Wi(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:r}),Xi=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class Zi{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 r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};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(Wi(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:r})),this.subscription.add(Wi(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:r})),this.subscription.add(Wi(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 r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),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(Zi.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)&&Xi(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 ts=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},es=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class is{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({start:i,end:s,i:e})}return this._buffer.sort((function(t,e){return t.start-e.start})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.start&&t<e.end))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.start-t.end<(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((({start:s,end:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var ss=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{start:s,end:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{start:s,end:r}},rs=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const as=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),r=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>ss(e.buffered,e.currentTime)))),a=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),o=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let d;return o.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&u.next(d),d=i})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:n,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:o,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:a,firstBytes$:rs(e),firstFrame$:es(e)}};var ns;exports.VideoQuality=void 0,(ns=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',ns.Q_144P='144p',ns.Q_240P='240p',ns.Q_360P='360p',ns.Q_480P='480p',ns.Q_720P='720p',ns.Q_1080P='1080p',ns.Q_1440P='1440p',ns.Q_2160P='2160p',ns.Q_4320P='4320p';var os=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}},us=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const ds={[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:854,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}},ls=(t,e)=>ds[t].height>ds[e].height,cs=(t,e)=>ds[t].height>=ds[e].height,hs=(t,e)=>ds[t].height<ds[e].height,ps=(t,e)=>ds[t].height<=ds[e].height,ms=Object.keys(ds).sort(((t,e)=>hs(t,e)?-1:1)),fs=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return ms.find((t=>{const e=ds[t];return e.width>=s&&e.height>=i}))},vs=t=>t===exports.VideoQuality.INVARIANT;let bs=!1,Ss={};const gs=t=>{t(Ss)},ys=(t,e)=>{var i;bs&&(Ss.meta=null!==(i=Ss.meta)&&void 0!==i?i:{},Ss.meta[t]=e)};class Ts{constructor(t){this.name=t}next(t){var e,i;if(!bs)return;Ss.series=null!==(e=Ss.series)&&void 0!==e?e:{};const s=null!==(i=Ss.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Ss.series[this.name]=s}}const Es=new Ts('best_bitrate'),Ps=(e,{container:i,throughput:s,tuning:r,limits:a,forwardBufferHealth:n,currentRepresentation:o})=>{var u,d,l,c;const h=r.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,p=r.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*h*r.containerSizeFactor,height:i.height*h*r.containerSizeFactor},m=p&&fs(p),f=e.filter((t=>!vs(t.quality))).sort(((t,e)=>ls(t.quality,e.quality)?-1:1)),v=null===(d=zi(f,-1))||void 0===d?void 0:d.quality,b=null===(l=zi(f,0))||void 0===l?void 0:l.quality,S=t.isNullable(a)||t.isNonNullable(a.min)&&t.isNonNullable(a.max)&&hs(a.max,a.min)||t.isNonNullable(a.min)&&b&&ls(a.min,b)||t.isNonNullable(a.max)&&v&&hs(a.max,v),g=f.filter((e=>{var i;const u=!m||hs(e.quality,m),d=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s>=e.bitrate*(l=null!=n?n:.5,c=r.bitrateFactorAtEmptyBuffer,h=r.bitrateFactorAtFullBuffer,(c-h)*Math.pow(2,-10*l)+h);var l,c,h;const p=!r.lazyQualitySwitch||!o||(null!=n?n:.5)>=.5||((null===(i=e.size)||void 0===i?void 0:i.height)||0)<=((null==o?void 0:o.height)||0),f=S||(t.isNullable(a.max)||ps(e.quality,a.max))&&(t.isNullable(a.min)||cs(e.quality,a.min));return u&&d&&p&&f}))[0];return g&&g.bitrate&&Es.next(g.bitrate),null!==(c=null!=g?g:f[Math.ceil((f.length-1)/2)])&&void 0!==c?c:e[0]};var ws=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)},ks=t=>new URL(t).hostname;const $s=(e,i=300)=>new t.Observable((r=>{const{width:a,height:n}=e.getBoundingClientRect();if(r.next({width:a,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,a;i.contentBoxSize&&i.contentBoxSize[0]?(a=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,a=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(a)&&r.next({width:s,height:a})}),i));return o.observe(e),()=>o.disconnect()}));class As{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 xs={},Ns=_,_s=zt,Ds=N(Function.toString);Ns(_s.inspectSource)||(_s.inspectSource=function(t){return Ds(t)});var Rs,Is,Ls,Cs=_s.inspectSource,Os=_,Vs=Cs,Ms=v.WeakMap,Bs=Os(Ms)&&/native code/.test(Vs(Ms)),Fs=Ht.exports,Us=ae,js=Fs('keys'),Hs=function(t){return js[t]||(js[t]=Us(t))},qs={},Gs=Bs,Ys=v,zs=N,Qs=at,Ws=gi,Js=te,Ks=zt,Xs=Hs,Zs=qs,tr=Ys.TypeError,er=Ys.WeakMap;if(Gs||Ks.state){var ir=Ks.state||(Ks.state=new er),sr=zs(ir.get),rr=zs(ir.has),ar=zs(ir.set);Rs=function(t,e){if(rr(ir,t))throw new tr('Object already initialized');return e.facade=t,ar(ir,t,e),e},Is=function(t){return sr(ir,t)||{}},Ls=function(t){return rr(ir,t)}}else{var nr=Xs('state');Zs[nr]=!0,Rs=function(t,e){if(Js(t,nr))throw new tr('Object already initialized');return e.facade=t,Ws(t,nr,e),e},Is=function(t){return Js(t,nr)?t[nr]:{}},Ls=function(t){return Js(t,nr)}}var or={set:Rs,get:Is,has:Ls,enforce:function(t){return Ls(t)?Is(t):Rs(t,{})},getterFor:function(t){return function(e){var i;if(!Qs(e)||(i=Is(e)).type!==t)throw tr('Incompatible receiver, '+t+' required');return i}}},ur=R,dr=te,lr=Function.prototype,cr=ur&&Object.getOwnPropertyDescriptor,hr=dr(lr,'name'),pr={EXISTS:hr,PROPER:hr&&'something'===function(){}.name,CONFIGURABLE:hr&&(!ur||ur&&cr(lr,'name').configurable)},mr={},fr=Li,vr=Math.max,br=Math.min,Sr=st,gr=function(t,e){var i=fr(t);return i<0?vr(i+e,0):br(i,e)},yr=Mi,Tr=function(t){return function(e,i,s){var r,a=Sr(e),n=yr(a),o=gr(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},Er={includes:Tr(!0),indexOf:Tr(!1)},Pr=te,wr=st,kr=Er.indexOf,$r=qs,Ar=N([].push),xr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Nr=function(t,e){var i,s=wr(t),r=0,a=[];for(i in s)!Pr($r,i)&&Pr(s,i)&&Ar(a,i);for(;e.length>r;)Pr(s,i=e[r++])&&(~kr(a,i)||Ar(a,i));return a},_r=xr,Dr=Object.keys||function(t){return Nr(t,_r)},Rr=R,Ir=si,Lr=ii,Cr=ui,Or=st,Vr=Dr;mr.f=Rr&&!Ir?Object.defineProperties:function(t,e){Cr(t);for(var i,s=Or(e),r=Vr(e),a=r.length,n=0;a>n;)Lr.f(t,i=r[n++],s[i]);return t};var Mr,Br=ct('document','documentElement'),Fr=ui,Ur=mr,jr=xr,Hr=qs,qr=Br,Gr=De,Yr=Hs('IE_PROTO'),zr=function(){},Qr=function(t){return'<script>'+t+'<\/script>'},Wr=function(t){t.write(Qr('')),t.close();var e=t.parentWindow.Object;return t=null,e},Jr=function(){try{Mr=new ActiveXObject('htmlfile')}catch(t){}var t,e;Jr='undefined'!=typeof document?document.domain&&Mr?Wr(Mr):((e=Gr('iframe')).style.display='none',qr.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Qr('document.F=Object')),t.close(),t.F):Wr(Mr);for(var i=jr.length;i--;)delete Jr.prototype[jr[i]];return Jr()};Hr[Yr]=!0;var Kr,Xr,Zr,ta=Object.create||function(t,e){var i;return null!==t?(zr.prototype=Fr(t),i=new zr,zr.prototype=null,i[Yr]=t):i=Jr(),void 0===e?i:Ur.f(i,e)},ea=!b((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ia=v,sa=te,ra=_,aa=Kt,na=ea,oa=Hs('IE_PROTO'),ua=ia.Object,da=ua.prototype,la=na?ua.getPrototypeOf:function(t){var e=aa(t);if(sa(e,oa))return e[oa];var i=e.constructor;return ra(i)&&e instanceof i?i.prototype:e instanceof ua?da:null},ca=gi,ha=function(t,e,i,s){s&&s.enumerable?t[e]=i:ca(t,e,i)},pa=b,ma=_,fa=ta,va=la,ba=ha,Sa=ve('iterator'),ga=!1;[].keys&&('next'in(Zr=[].keys())?(Xr=va(va(Zr)))!==Object.prototype&&(Kr=Xr):ga=!0);var ya=null==Kr||pa((function(){var t={};return Kr[Sa].call(t)!==t}));ma((Kr=ya?{}:fa(Kr))[Sa])||ba(Kr,Sa,(function(){return this}));var Ta={IteratorPrototype:Kr,BUGGY_SAFARI_ITERATORS:ga},Ea={};Ea[ve('toStringTag')]='z';var Pa='[object z]'===String(Ea),wa=v,ka=Pa,$a=_,Aa=Y,xa=ve('toStringTag'),Na=wa.Object,_a='Arguments'==Aa(function(){return arguments}()),Da=ka?Aa: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=Na(t),xa))?i:_a?Aa(e):'Object'==(s=Aa(e))&&$a(e.callee)?'Arguments':s},Ra=Da,Ia=Pa?{}.toString:function(){return'[object '+Ra(this)+']'},La=Pa,Ca=ii.f,Oa=gi,Va=te,Ma=Ia,Ba=ve('toStringTag'),Fa=function(t,e,i,s){if(t){var r=i?t:t.prototype;Va(r,Ba)||Ca(r,Ba,{configurable:!0,value:e}),s&&!La&&Oa(r,'toString',Ma)}},Ua=Ta.IteratorPrototype,ja=ta,Ha=j,qa=Fa,Ga=xs,Ya=function(){return this},za=v,Qa=(za.String,za.TypeError,N);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Qa(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Wa=Di,Ja=C,Ka=function(t,e,i,s){var r=e+' Iterator';return t.prototype=ja(Ua,{next:Ha(+!s,i)}),qa(t,r,!1,!0),Ga[r]=Ya,t},Xa=la,Za=Fa,tn=ha,en=xs,sn=pr.PROPER,rn=Ta.BUGGY_SAFARI_ITERATORS,an=ve('iterator'),nn=function(){return this},on=st,un=xs,dn=or;ii.f;var ln=function(t,e,i,s,r,a,n){Ka(i,e,s);var o,u,d,l=function(t){if(t===r&&f)return f;if(!rn&&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)}},c=e+' Iterator',h=!1,p=t.prototype,m=p[an]||p['@@iterator']||r&&p[r],f=!rn&&m||l(r),v='Array'==e&&p.entries||m;if(v&&(o=Xa(v.call(new t)))!==Object.prototype&&o.next&&(Za(o,c,!0,!0),en[c]=nn),sn&&'values'==r&&m&&'values'!==m.name&&(h=!0,f=function(){return Ja(m,this)}),r)if(u={values:l('values'),keys:a?f:l('keys'),entries:l('entries')},n)for(d in u)(rn||h||!(d in p))&&tn(p,d,u[d]);else Wa({target:e,proto:!0,forced:rn||h},u);return n&&p[an]!==f&&tn(p,an,f,{name:r}),en[e]=f,u},cn=dn.set,hn=dn.getterFor('Array Iterator');ln(Array,'Array',(function(t,e){cn(this,{type:'Array Iterator',target:on(t),index:0,kind:e})}),(function(){var t=hn(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'),un.Arguments=un.Array;var pn=xs,mn=ve('iterator'),fn=Array.prototype,vn=Da,bn=Mt,Sn=xs,gn=ve('iterator'),yn=function(t){if(null!=t)return bn(t,gn)||bn(t,'@@iterator')||Sn[vn(t)]},Tn=C,En=Ot,Pn=ui,wn=Rt,kn=yn,$n=v.TypeError,An=C,xn=ui,Nn=Mt,_n=ei,Dn=C,Rn=ui,In=Rt,Ln=function(t){return void 0!==t&&(pn.Array===t||fn[mn]===t)},Cn=Mi,On=ht,Vn=function(t,e){var i=arguments.length<2?kn(t):e;if(En(i))return Pn(Tn(i,t));throw $n(wn(t)+' is not iterable')},Mn=yn,Bn=function(t,e,i){var s,r;xn(t);try{if(!(s=Nn(t,'return'))){if('throw'===e)throw i;return i}s=An(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return xn(s),i},Fn=v.TypeError,Un=function(t,e){this.stopped=t,this.result=e},jn=Un.prototype,Hn=function(t,e,i){var s,r,a,n,o,u,d,l=i&&i.that,c=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=_n(e,l),f=function(t){return s&&Bn(s,'normal',t),new Un(!0,t)},v=function(t){return c?(Rn(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(h)s=t;else{if(!(r=Mn(t)))throw Fn(In(t)+' is not iterable');if(Ln(r)){for(a=0,n=Cn(t);n>a;a++)if((o=v(t[a]))&&On(jn,o))return o;return new Un(!1)}s=Vn(t,r)}for(u=s.next;!(d=Dn(u,s)).done;){try{o=v(d.value)}catch(t){Bn(s,'throw',t)}if('object'==typeof o&&o&&On(jn,o))return o}return new Un(!1)},qn=Ae,Gn=ii,Yn=j,zn=Hn,Qn=function(t,e,i){var s=qn(e);s in t?Gn.f(t,s,Yn(0,i)):t[s]=i};Di({target:'Object',stat:!0},{fromEntries:function(t){var e={};return zn(t,(function(t,i){Qn(e,t,i)}),{AS_ENTRIES:!0}),e}});var Wn=nt.Object.fromEntries,Jn={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},Kn=v,Xn=Da,Zn=gi,to=xs,eo=ve('toStringTag');for(var io in Jn){var so=Kn[io],ro=so&&so.prototype;ro&&Xn(ro)!==eo&&Zn(ro,eo,io),to[io]=to.Array}var ao=Wn,no={};function oo(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function uo(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,'value'in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}function lo(t,e,i){return e&&uo(t.prototype,e),i&&uo(t,i),t}function co(t){return(co=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function ho(t,e){return(ho=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function po(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function mo(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?po(t):e}function fo(t){var e=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,s=co(t);if(e){var r=co(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return mo(this,i)}}function vo(t,e,i){return(vo='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var s=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=co(t)););return t}(t,e);if(s){var r=Object.getOwnPropertyDescriptor(s,e);return r.get?r.get.call(i):r.value}})(t,e,i||t)}Object.defineProperty(no,'__esModule',{value:!0});var bo=function(){function t(){oo(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return lo(t,[{key:'addEventListener',value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:'removeEventListener',value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],s=0,r=i.length;s<r;s++)if(i[s].callback===e)return void i.splice(s,1)}},{key:'dispatchEvent',value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,s=e.length;i<s;i++){var r=e[i];try{r.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}r.options&&r.options.once&&this.removeEventListener(t.type,r.callback)}return!t.defaultPrevented}}}]),t}(),So=function(t){!function(t,e){if('function'!=typeof e&&null!==e)throw new TypeError('Super expression must either be null or a function');t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&ho(t,e)}(i,bo);var e=fo(i);function i(){var t;return oo(this,i),(t=e.call(this)).listeners||bo.call(po(t)),Object.defineProperty(po(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(po(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return lo(i,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),vo(co(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),go=function(){function t(){oo(this,t),Object.defineProperty(this,'signal',{value:new So,writable:!0,configurable:!0})}return lo(t,[{key:'abort',value:function(){var t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event')).initEvent('abort',!1,!1):(t=document.createEventObject()).type='abort':t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}},{key:'toString',value:function(){return'[object AbortController]'}}]),t}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(go.prototype[Symbol.toStringTag]='AbortController',So.prototype[Symbol.toStringTag]='AbortSignal');var yo=no.AbortController=go;no.AbortSignal=So;var To=no.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e=t,i=e.fetch,s=e.Request,r=void 0===s?i.Request:s,a=e.AbortController,n=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,o=void 0!==n&&n;if(!function(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}({fetch:i,Request:r,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:i,Request:u};var u=r;(u&&!u.prototype.hasOwnProperty('signal')||o)&&((u=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var s=new r(t,e);return i&&Object.defineProperty(s,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),s}).prototype=r.prototype);var d=i;return{fetch:function(t,e){var i=u&&u.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var s;try{s=new DOMException('Aborted','AbortError')}catch(t){(s=new Error('Aborted')).name='AbortError'}if(i.aborted)return Promise.reject(s);var r=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,d(t,e)])}return d(t,e)},Request:u}},Eo=v.Promise,Po=ha,wo=ct,ko=ii,$o=R,Ao=ve('species'),xo=ht,No=v.TypeError,_o=ve('iterator'),Do=!1;try{var Ro=0,Io={next:function(){return{done:!!Ro++}},return:function(){Do=!0}};Io[_o]=function(){return this},Array.from(Io,(function(){throw 2}))}catch(t){}var Lo=N,Co=b,Oo=_,Vo=Da,Mo=Cs,Bo=function(){},Fo=[],Uo=ct('Reflect','construct'),jo=/^\s*(?:class|function)\b/,Ho=Lo(jo.exec),qo=!jo.exec(Bo),Go=function(t){if(!Oo(t))return!1;try{return Uo(Bo,Fo,t),!0}catch(t){return!1}},Yo=function(t){if(!Oo(t))return!1;switch(Vo(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return qo||!!Ho(jo,Mo(t))}catch(t){return!0}};Yo.sham=!0;var zo,Qo,Wo,Jo,Ko=!Uo||Co((function(){var t;return Go(Go.call)||!Go(Object)||!Go((function(){t=!0}))||t}))?Yo:Go,Xo=Rt,Zo=v.TypeError,tu=ui,eu=function(t){if(Ko(t))return t;throw Zo(Xo(t)+' is not a constructor')},iu=ve('species'),su=function(t,e){var i,s=tu(t).constructor;return void 0===s||null==(i=tu(s)[iu])?e:eu(i)},ru=N([].slice),au=v.TypeError,nu=/(?:ipad|iphone|ipod).*applewebkit/i.test(pt),ou='process'==Y(v.process),uu=v,du=P,lu=ei,cu=_,hu=te,pu=b,mu=Br,fu=ru,vu=De,bu=function(t,e){if(t<e)throw au('Not enough arguments');return t},Su=nu,gu=ou,yu=uu.setImmediate,Tu=uu.clearImmediate,Eu=uu.process,Pu=uu.Dispatch,wu=uu.Function,ku=uu.MessageChannel,$u=uu.String,Au=0,xu={};try{zo=uu.location}catch(t){}var Nu=function(t){if(hu(xu,t)){var e=xu[t];delete xu[t],e()}},_u=function(t){return function(){Nu(t)}},Du=function(t){Nu(t.data)},Ru=function(t){uu.postMessage($u(t),zo.protocol+'//'+zo.host)};yu&&Tu||(yu=function(t){bu(arguments.length,1);var e=cu(t)?t:wu(t),i=fu(arguments,1);return xu[++Au]=function(){du(e,void 0,i)},Qo(Au),Au},Tu=function(t){delete xu[t]},gu?Qo=function(t){Eu.nextTick(_u(t))}:Pu&&Pu.now?Qo=function(t){Pu.now(_u(t))}:ku&&!Su?(Jo=(Wo=new ku).port2,Wo.port1.onmessage=Du,Qo=lu(Jo.postMessage,Jo)):uu.addEventListener&&cu(uu.postMessage)&&!uu.importScripts&&zo&&'file:'!==zo.protocol&&!pu(Ru)?(Qo=Ru,uu.addEventListener('message',Du,!1)):Qo='onreadystatechange'in vu('script')?function(t){mu.appendChild(vu('script')).onreadystatechange=function(){mu.removeChild(this),Nu(t)}}:function(t){setTimeout(_u(t),0)});var Iu,Lu,Cu,Ou,Vu,Mu,Bu,Fu,Uu={set:yu,clear:Tu},ju=v,Hu=/ipad|iphone|ipod/i.test(pt)&&void 0!==ju.Pebble,qu=/web0s(?!.*chrome)/i.test(pt),Gu=v,Yu=ei,zu=D.f,Qu=Uu.set,Wu=nu,Ju=Hu,Ku=qu,Xu=ou,Zu=Gu.MutationObserver||Gu.WebKitMutationObserver,td=Gu.document,ed=Gu.process,id=Gu.Promise,sd=zu(Gu,'queueMicrotask'),rd=sd&&sd.value;rd||(Iu=function(){var t,e;for(Xu&&(t=ed.domain)&&t.exit();Lu;){e=Lu.fn,Lu=Lu.next;try{e()}catch(t){throw Lu?Ou():Cu=void 0,t}}Cu=void 0,t&&t.enter()},Wu||Xu||Ku||!Zu||!td?!Ju&&id&&id.resolve?((Bu=id.resolve(void 0)).constructor=id,Fu=Yu(Bu.then,Bu),Ou=function(){Fu(Iu)}):Xu?Ou=function(){ed.nextTick(Iu)}:(Qu=Yu(Qu,Gu),Ou=function(){Qu(Iu)}):(Vu=!0,Mu=td.createTextNode(''),new Zu(Iu).observe(Mu,{characterData:!0}),Ou=function(){Mu.data=Vu=!Vu}));var ad=rd||function(t){var e={fn:t,next:void 0};Cu&&(Cu.next=e),Lu||(Lu=e,Ou()),Cu=e},nd={},od=Ot,ud=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw TypeError('Bad Promise constructor');e=t,i=s})),this.resolve=od(e),this.reject=od(i)};nd.f=function(t){return new ud(t)};var dd=ui,ld=at,cd=nd,hd=function(t,e){if(dd(t),ld(e)&&e.constructor===t)return e;var i=cd.f(t);return(0,i.resolve)(e),i.promise},pd=v,md=function(){this.head=null,this.tail=null};md.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}};var fd,vd,bd,Sd='object'==typeof window,gd=Di,yd=v,Td=ct,Ed=C,Pd=Eo,wd=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Po(t,s,e[s],i);return t},kd=Fa,$d=function(t){var e=wo(t),i=ko.f;$o&&e&&!e[Ao]&&i(e,Ao,{configurable:!0,get:function(){return this}})},Ad=Ot,xd=_,Nd=at,_d=function(t,e){if(xo(e,t))return t;throw No('Incorrect invocation')},Dd=Cs,Rd=Hn,Id=function(t,e){if(!e&&!Do)return!1;var i=!1;try{var s={};s[_o]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},Ld=su,Cd=Uu.set,Od=ad,Vd=hd,Md=function(t,e){var i=pd.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},Bd=nd,Fd=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Ud=md,jd=or,Hd=Ke,qd=Sd,Gd=ou,Yd=yt,zd=ve('species'),Qd='Promise',Wd=jd.getterFor(Qd),Jd=jd.set,Kd=jd.getterFor(Qd),Xd=Pd&&Pd.prototype,Zd=Pd,tl=Xd,el=yd.TypeError,il=yd.document,sl=yd.process,rl=Bd.f,al=rl,nl=!!(il&&il.createEvent&&yd.dispatchEvent),ol=xd(yd.PromiseRejectionEvent),ul=Hd(Qd,(function(){var t=Dd(Zd),e=t!==String(Zd);if(!e&&66===Yd)return!0;if(!tl.finally)return!0;if(Yd>=51&&/native code/.test(t))return!1;var i=new Zd((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[zd]=s,!(i.then((function(){}))instanceof s)||!e&&qd&&!ol})),dl=ul||!Id((function(t){Zd.all(t).catch((function(){}))})),ll=function(t){var e;return!(!Nd(t)||!xd(e=t.then))&&e},cl=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,u=t.resolve,d=t.reject,l=t.domain;try{o?(n||(2===e.rejection&&vl(e),e.rejection=1),!0===o?i=a:(l&&l.enter(),i=o(a),l&&(l.exit(),r=!0)),i===t.promise?d(el('Promise-chain cycle')):(s=ll(i))?Ed(s,i,u,d):u(i)):d(a)}catch(t){l&&!r&&l.exit(),d(t)}},hl=function(t,e){t.notified||(t.notified=!0,Od((function(){for(var i,s=t.reactions;i=s.get();)cl(i,t);t.notified=!1,e&&!t.rejection&&ml(t)})))},pl=function(t,e,i){var s,r;nl?((s=il.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),yd.dispatchEvent(s)):s={promise:e,reason:i},!ol&&(r=yd['on'+t])?r(s):'unhandledrejection'===t&&Md('Unhandled promise rejection',i)},ml=function(t){Ed(Cd,yd,(function(){var e,i=t.facade,s=t.value;if(fl(t)&&(e=Fd((function(){Gd?sl.emit('unhandledRejection',s,i):pl('unhandledrejection',i,s)})),t.rejection=Gd||fl(t)?2:1,e.error))throw e.value}))},fl=function(t){return 1!==t.rejection&&!t.parent},vl=function(t){Ed(Cd,yd,(function(){var e=t.facade;Gd?sl.emit('rejectionHandled',e):pl('rejectionhandled',e,t.value)}))},bl=function(t,e,i){return function(s){t(e,s,i)}},Sl=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,hl(t,!0))},gl=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw el('Promise can\'t be resolved itself');var s=ll(e);s?Od((function(){var i={done:!1};try{Ed(s,e,bl(gl,i,t),bl(Sl,i,t))}catch(e){Sl(i,e,t)}})):(t.value=e,t.state=1,hl(t,!1))}catch(e){Sl({done:!1},e,t)}}};ul&&(tl=(Zd=function(t){_d(this,tl),Ad(t),Ed(fd,this);var e=Wd(this);try{t(bl(gl,e),bl(Sl,e))}catch(t){Sl(e,t)}}).prototype,(fd=function(t){Jd(this,{type:Qd,done:!1,notified:!1,parent:!1,reactions:new Ud,rejection:!1,state:0,value:void 0})}).prototype=wd(tl,{then:function(t,e){var i=Kd(this),s=rl(Ld(this,Zd));return i.parent=!0,s.ok=!xd(t)||t,s.fail=xd(e)&&e,s.domain=Gd?sl.domain:void 0,0==i.state?i.reactions.add(s):Od((function(){cl(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),vd=function(){var t=new fd,e=Wd(t);this.promise=t,this.resolve=bl(gl,e),this.reject=bl(Sl,e)},Bd.f=rl=function(t){return t===Zd||t===bd?new vd(t):al(t)}),gd({global:!0,wrap:!0,forced:ul},{Promise:Zd}),kd(Zd,Qd,!1,!0),$d(Qd),bd=Td(Qd),gd({target:Qd,stat:!0,forced:ul},{reject:function(t){var e=rl(this);return Ed(e.reject,void 0,t),e.promise}}),gd({target:Qd,stat:!0,forced:true},{resolve:function(t){return Vd(this===bd?Zd:this,t)}}),gd({target:Qd,stat:!0,forced:dl},{all:function(t){var e=this,i=rl(e),s=i.resolve,r=i.reject,a=Fd((function(){var i=Ad(e.resolve),a=[],n=0,o=1;Rd(t,(function(t){var u=n++,d=!1;o++,Ed(i,e,t).then((function(t){d||(d=!0,a[u]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=rl(e),s=i.reject,r=Fd((function(){var r=Ad(e.resolve);Rd(t,(function(t){Ed(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var yl=Eo,Tl=ct,El=_,Pl=su,wl=hd;Di({target:'Promise',proto:!0,real:!0,forced:!!yl&&b((function(){yl.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=Pl(this,Tl('Promise')),i=El(t);return this.then(i?function(i){return wl(e,t()).then((function(){return i}))}:t,i?function(i){return wl(e,t()).then((function(){throw i}))}:t)}});var kl,$l=Yi('Promise','finally'),Al=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(kl||(kl={}));class xl{constructor({throughputEstimator:e}={}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new yo,this.subscription=new t.Subscription,this.fetchRepresentation=(t,e,i=0)=>p(this,void 0,void 0,(function*(){const{from:s,to:r}=t.initRange;let a,n,o=s,u=r,d=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,d=r+1===a,d&&(o=Math.min(a,s),u=Math.max(n,r))),o=Math.min(o,0),u+=i;const l=yield this.fetchRange(t.url,o,u,{method:kl.PARAM});if(!l)return null;const c=new DataView(l,s-o,r-o);if(!e.validateData(c))throw new Error('Invalid media file');const h=e.parseInit(c);let p;if(d&&void 0!==a&&void 0!==n)p=new DataView(l,a-o,n-a);else{const i=e.getIndexRange(h);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:kl.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,h);return{dataView:new DataView(l),segments:m}})),this.throughputEstimator=e}onHeadersReceived(t){const{type:e,reused:i}=Al(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest(t){return p(this,void 0,void 0,(function*(){const e=yield To(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Nl);return e?(this.onHeadersReceived(e.headers),e.text()):null}))}fetchRange(e,i,s,{method:r=kl.HEADER,onProgress:a,signal:n}={}){var o,u,d;return p(this,void 0,void 0,(function*(){let l=e;const c=new Headers;switch(r){case kl.HEADER:c.append('Range',`${i}-${s}`);break;case kl.PARAM:{const t=new URL(l,location.href);t.searchParams.append('bytes',`${i}-${s}`),l=t.toString();break}default:t.assertNever(r)}let h=this.abortAllController.signal;if(n){const e=new yo;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(n,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||n.aborted)&&e.abort(),h=e.signal}const m=t.now(),f=yield To(fetch).fetch(l,{headers:c,signal:h}).catch(Nl);if(null===(o=this.throughputEstimator)||void 0===o||o.addRawRtt(t.now()-m),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const[v,b]=f.body.tee(),S=v.getReader();null===(u=this.throughputEstimator)||void 0===u||u.trackStream(b);const g=parseInt(null!==(d=f.headers.get('Content-Length'))&&void 0!==d?d:'',10);let y=0;const T=new ArrayBuffer(g),E=new Uint8Array(T),P=new DataView(T);let w=!1;const k=t=>{w=!0,Nl(t)},$=({done:e,value:i})=>p(this,void 0,void 0,(function*(){0===y&&this.lastRequestFirstBytes$.next(t.now()-m),e?null==a||a(P,y):i&&(E.set(i,y),y+=i.byteLength,null==a||a(P,y),yield null==S?void 0:S.read().then($,k))}));return yield null==S?void 0:S.read().then($,k),w?null:T}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Nl=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var _l,Dl;!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.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'}(_l||(_l={})),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'}(Dl||(Dl={}));const Rl={[_l.EBML]:{type:Dl.Master},[_l.EBMLVersion]:{type:Dl.UnsignedInteger},[_l.EBMLReadVersion]:{type:Dl.UnsignedInteger},[_l.EBMLMaxIDLength]:{type:Dl.UnsignedInteger},[_l.EBMLMaxSizeLength]:{type:Dl.UnsignedInteger},[_l.DocType]:{type:Dl.String},[_l.DocTypeVersion]:{type:Dl.UnsignedInteger},[_l.DocTypeReadVersion]:{type:Dl.UnsignedInteger},[_l.Void]:{type:Dl.Binary},[_l.Segment]:{type:Dl.Master},[_l.SeekHead]:{type:Dl.Master},[_l.Seek]:{type:Dl.Master},[_l.SeekID]:{type:Dl.Binary},[_l.SeekPosition]:{type:Dl.UnsignedInteger},[_l.Info]:{type:Dl.Master},[_l.TimestampScale]:{type:Dl.UnsignedInteger},[_l.Duration]:{type:Dl.Float},[_l.Tracks]:{type:Dl.Master},[_l.Chapters]:{type:Dl.Master},[_l.Cluster]:{type:Dl.Master},[_l.Attachments]:{type:Dl.Master},[_l.Tags]:{type:Dl.Master},[_l.Cues]:{type:Dl.Master},[_l.CuePoint]:{type:Dl.Master},[_l.CueTime]:{type:Dl.UnsignedInteger},[_l.CueTrackPositions]:{type:Dl.Master},[_l.CueTrack]:{type:Dl.UnsignedInteger},[_l.CueClusterPosition]:{type:Dl.UnsignedInteger},[_l.CueRelativePosition]:{type:Dl.UnsignedInteger},[_l.CueDuration]:{type:Dl.UnsignedInteger},[_l.CueBlockNumber]:{type:Dl.UnsignedInteger},[_l.CueCodecState]:{type:Dl.UnsignedInteger},[_l.CueReference]:{type:Dl.Master},[_l.CueRefTime]:{type:Dl.UnsignedInteger}},Il=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=Ll(t,i),r=s in Rl,a=r?Rl[s].type:Dl.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const u=new DataView(t.buffer,t.byteOffset+i+1,o-1),d=((n&255>>o)<<8*(o-1))+Ll(u),l=i+o;let c;return c=l+d>t.byteLength?new DataView(t.buffer,t.byteOffset+l):new DataView(t.buffer,t.byteOffset+l,d),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,value:c,valueSize:d}},Ll=(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},Cl=(e,i)=>{switch(i){case Dl.SignedInteger:return e.getInt8(0);case Dl.UnsignedInteger:return Ll(e);case Dl.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Dl.String:return new TextDecoder('ascii').decode(e);case Dl.UTF8:return new TextDecoder('utf-8').decode(e);case Dl.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Dl.Master:case Dl.Binary:return e;default:t.assertNever(i)}},Ol=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Il(s);if(!e(r))return;r.type===Dl.Master&&Ol(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Vl=[_l.Info,_l.SeekHead,_l.Tracks,_l.Chapters,_l.Cluster,_l.Cues,_l.Attachments,_l.Tags],Ml={validateData:t=>{if(t.getUint32(0)!==_l.EBML)return!1;let e,i,s;const r=Il(t);return Ol(r.value,(({tag:t,type:r,value:a})=>(t===_l.EBMLReadVersion?e=Cl(a,r):t===_l.DocType?i=Cl(a,r):t===_l.DocTypeReadVersion&&(s=Cl(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,r,a,n,o,u=!1,d=!1,l=!1;return Ol(e,(({tag:t,type:e,value:c,valueSize:h})=>{if(t===_l.SeekID){const t=Cl(c,e);o=Ll(t)}else t!==_l.SeekPosition&&(o=void 0);return t===_l.Segment?(i=c.byteOffset,s=c.byteOffset+h):t===_l.Info?u=!0:t===_l.SeekHead?d=!0:t===_l.TimestampScale?r=Cl(c,e):t===_l.Duration?a=Cl(c,e):t===_l.SeekPosition&&o===_l.Cues?n=Cl(c,e):u&&d&&Vl.includes(t)&&(l=!0),!l})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(a,'Failed to parse webm Segment duration'),r=null!=r?r:1e6,{segmentStart:Math.round(i/1e9*r*1e3),segmentEnd:Math.round(s/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:n}},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,r=!1;const a=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return Ol(e,(({tag:t,type:e,value:i})=>{switch(t){case _l.Cues:s=!0;break;case _l.CuePoint:o&&a(o)&&n.push(o),o={};break;case _l.CueTime:o&&(o.time=Cl(i,e));break;case _l.CueTrackPositions:break;case _l.CueClusterPosition:o&&(o.position=Cl(i,e));break;default:s&&Vl.includes(t)&&(r=!0)}return!(s&&r)})),o&&a(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:r}=t,a=n[e+1];return{status:qi.NONE,time:{from:s,to:a?a.time:i.segmentDuration},byte:{from:i.segmentStart+r,to:a?i.segmentStart+a.position-1:i.segmentEnd-1}}}))}},Bl=new TextDecoder('ascii'),Fl={validateData:t=>'ftyp'===Bl.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=(t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=Bl.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e+1;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}})(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),u=255&r();let d=n/a*1e3,l=t.byteOffset+t.byteLength+o+1;for(let t=0;t<u;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:qi.NONE,time:{from:d,to:d+o},byte:{from:l,to:l+s-1}}),d+=o,l+=s}return i}};class Ul{constructor(e,i,s,r,{fetcher:a,tuning:n}){switch(this.ended$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.abortController=new yo,this.allInitsLoaded=!1,this.fetcher=a,this.tuning=n,this.container=s,s){case Gi.MP4:this.containerParser=Fl;break;case Gi.WEBM:this.containerParser=Ml;break;default:t.assertNever(s)}this.initData=new Map,this.segments=new Map,this.representations=new Map(r.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith(e){return p(this,void 0,void 0,(function*(){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`);const s=Math.ceil(1e3*i.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateEnd').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejecte by browser',thrown:t})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const r=yield this.fetcher.fetchRepresentation(i,this.containerParser,s).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!r)return!1;const{dataView:a,segments:n}=r,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength-s);this.initData.set(e,o);const u=n.filter((t=>t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength)),d=zi(u,-1),l=new DataView(a.buffer,a.byteOffset,u.length&&d?Math.min(d.byte.to-a.byteOffset+1,a.byteLength):a.byteLength-s);return yield this.appendDataToBuffer(l),this.segments.set(e,n.map((t=>Object.assign(Object.assign({},t),{status:t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength?qi.FED:qi.NONE})))),this.maintain(0),!0}))}switchTo(e){var i;return p(this,void 0,void 0,(function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=e,!this.initData.has(e))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const i=this.representations.get(e);t.assertNonNullable(i);const s=yield this.fetcher.fetchRepresentation(i,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:r,segments:a}=s,n=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);this.initData.set(e,n),this.segments.set(e,a)}const s=this.initData.get(e);t.assertNonNullable(s,`No init buffer for ${e}`),t.assertNonNullable(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abortController.abort(),this.abortController=new yo,this.abortBuffer(),yield this.appendDataToBuffer(s,this.abortController.signal),t.isNonNullable(this.playingRepresentationId)&&(null===(i=this.segments.get(this.playingRepresentationId))||void 0===i||i.forEach((t=>{t.status===qi.FED&&(t.status=qi.NONE)})))}))}maintain(e){return p(this,void 0,void 0,(function*(){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer)||this.ended$.getValue())return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);t.assertNonNullable(i),t.assertNonNullable(s);const r=s.find((t=>e>=t.time.from&&e<t.time.to));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=ws(this.sourceBuffer.buffered,e);a=e+Math.min(t,this.tuning.representationSwitchForwardBufferGap)}const n=this.selectForwardBufferSegments(s,a);n.length&&(yield this.loadSegments(n,i)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&r&&r.status===qi.FED&&!n.length&&ws(this.sourceBuffer.buffered,e)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=zi(s,-1);o&&r===o&&o.status===qi.FED&&this.ended$.next(!0)}))}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.abortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===qi.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.forwardBufferTarget));if(-1===i)return[];let s=0;const r=[];for(let e=i;e<t.length&&s<=this.tuning.segmentRequestSize;e++){const i=t[e];if(s+=i.byte.to+1-i.byte.from,i.status===qi.NONE)r.push(i);else if([qi.DOWNLOADING,qi.DOWNLOADED,qi.FED].includes(i.status))break}return r}loadSegments(t,e){return p(this,void 0,void 0,(function*(){if(!t.length)return;const i=zi(t,0).byte.from,s=zi(t,-1).byte.to;for(const e of t)e.status=qi.DOWNLOADING;const{signal:r}=this.abortController,a=(t,i)=>{t.status=qi.DOWNLOADED,this.appendDataToBuffer(i,r).then((i=>{!i||r.aborted?t.status=qi.NONE:(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=qi.FED)}))},n=(e,s)=>{for(const r of t)r.status===qi.DOWNLOADING&&r.byte.from-i>=0&&r.byte.to+1-i<=s&&a(r,new DataView(e.buffer,e.byteOffset+r.byte.from-i,r.byte.to+1-r.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((()=>p(this,void 0,void 0,(function*(){if(r.aborted){for(const e of t)e.status===qi.DOWNLOADING&&(e.status=qi.NONE);return}const o=yield this.fetcher.fetchRange(e.url,i,s,{method:kl.PARAM,onProgress:n,signal:r}),u=zi(t,-1),d=zi(this.segments.get(e.id),-1);if(!o)for(const e of t)e.status===qi.DOWNLOADING&&(e.status=qi.NONE);o&&!r.aborted&&u&&d&&u.status===qi.DOWNLOADING&&u===d&&a(u,new DataView(o,u.byte.from-i))})))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}))}loadAllInits(){return p(this,void 0,void 0,(function*(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=$l(Promise.all(Array.from(this.representations.entries()).map((([t,e])=>this.initData.has(t)?Promise.resolve():this.fetcher.fetchRepresentation(e,this.containerParser).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,r),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})),(()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}))}appendDataToBuffer(e,i){return p(this,void 0,void 0,(function*(){if(t.assertNonNullable(this.sourceBuffer),i&&i.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return yield Ul.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(e,i);try{this.sourceBuffer.appendBuffer(e)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),!1}return yield Ul.waitForBufferUpdate(this.sourceBuffer),!0}))}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(t){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:t})}}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=this.segments.get(this.playingRepresentationId);t.assertNonNullable(e);const i=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),r=1e3*(s%1>.9?Math.round(s):s);i.push({from:e,to:r})}for(const t of e){const e=i.some((e=>e.from<=t.time.from&&e.to>=t.time.to));t.status!==qi.FED||e||(t.status=qi.NONE)}}static waitForBufferUpdate(t){return p(this,void 0,void 0,(function*(){return new Promise((e=>t?t.addEventListener('update',(()=>e())):e()))}))}}const jl=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},Hl=['timeupdate','progress','play','seeked','stalled'];var ql,Gl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(ql||(ql={}));class Yl{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new As(ql.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.tick=()=>{var t,e;if(!this.element)return;const i=1e3*this.element.currentTime;null===(t=this.videoBufferManager)||void 0===t||t.maintain(i),null===(e=this.audioBufferManager)||void 0===e||e.maintain(i)},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new xl({throughputEstimator:this.throughputEstimator})}initManifest(e,i){return p(this,void 0,void 0,(function*(){this.element=e,this.subscription.add(t.fromEvent(e,'waiting').subscribe((()=>{e.duration-e.currentTime<this.tuning.endGapTolerance/1e3&&this.forceEnded$.next()}),(t=>this.error$.next({id:'ForceEnd',message:'Error when forcing stream end',thrown:t})))),this.state$.startTransitionTo(ql.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i);let r;try{r=((t,e)=>{var i,s,r,a,n,o,u,d,l,c,h,p,m,f,v,b,S,g,y,T,E,P,w,k;const $={video:[],audio:[],text:[]},A=(new DOMParser).parseFromString(t,'application/xml').children[0],x=A.getElementsByTagName('Period')[0].children;let N=0;const _=null!==(s=null===(i=A.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==s?s:[],D=_.includes(Hi.WEBM_AS_IN_FFMPEG)||_.includes(Hi.WEBM_AS_IN_SPEC)?Gi.WEBM:Gi.MP4;for(const t of x){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),A=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==i?void 0:i.split('/')[0],x=null!==(n=null===(a=t.getAttribute('profiles'))||void 0===a?void 0:a.split(','))&&void 0!==n?n:[],D=t.querySelectorAll('Representation');for(const r of D){const a=null!==(o=r.getAttribute('mimeType'))&&void 0!==o?o:i,n=null!==(d=null!==(u=r.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==d?d:'',D=null!==(c=null!==(l=r.getAttribute('contentType'))&&void 0!==l?l:null==a?void 0:a.split('/')[0])&&void 0!==c?c:A,R=null!==(p=null===(h=t.getAttribute('profiles'))||void 0===h?void 0:h.split(','))&&void 0!==p?p:[],I=parseInt(null!==(m=r.getAttribute('width'))&&void 0!==m?m:'',10),L=parseInt(null!==(f=r.getAttribute('height'))&&void 0!==f?f:'',10),C=parseInt(null!==(v=r.getAttribute('bandwidth'))&&void 0!==v?v:'',10)/1e3,O=null!==(b=r.getAttribute('frameRate'))&&void 0!==b?b:'',V=null!==(S=r.getAttribute('quality'))&&void 0!==S?S:void 0,M=O?jl(O):void 0,B=`${null!==(g=r.getAttribute('id'))&&void 0!==g?g:(N++).toString(10)}@${'video'===D?`${L}p`:'audio'===D?`${C}Kbps`:n}`,F=null!==(E=null===(T=null===(y=r.querySelector('BaseURL'))||void 0===y?void 0:y.textContent)||void 0===T?void 0:T.trim())&&void 0!==E?E:'',U=new URL(F,e).toString(),j=[..._,...x,...R],H=null!==(w=null===(P=r.querySelector('SegmentBase Initialization'))||void 0===P?void 0:P.getAttribute('range'))&&void 0!==w?w:'',[q,G]=H.split('-').map((t=>parseInt(t,10))),Y={from:q,to:G},z=null===(k=r.querySelector('SegmentBase'))||void 0===k?void 0:k.getAttribute('indexRange'),[Q,W]=z?z.split('-').map((t=>parseInt(t,10))):[],J=z?{from:Q,to:W}:void 0;if(!D||!a)continue;const K={video:ji.VIDEO,audio:ji.AUDIO,text:ji.TEXT}[D];K&&$[K].push({id:B,kind:K,profiles:j,initRange:Y,indexRange:J,bitrate:C,mime:a,codecs:n,width:I,height:L,fps:M,quality:V,url:U})}}return{container:D,representations:$}})(null!=s?s:'',i)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}t.assertNonNullable(r);const a=({mime:t,codecs:i})=>{var s,r,a;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${t}; codecs="${i}"`)))};return this.manifest=Object.assign(Object.assign({},r),{representations:ao(Object.entries(r.representations).map((([t,e])=>[t,e.filter(a)])))}),this.manifest.representations.video.length?this.state$.setState(ql.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}))}initRepresentations(e,i){return p(this,void 0,void 0,(function*(){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(ql.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash};this.videoBufferManager=new Ul(ji.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.audioBufferManager=new Ul(ji.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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$)),this.subscription.add(t.merge(this.forceEnded$,t.combine({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(t.filter((t=>Object.values(t).every((t=>!0===t)))))).subscribe((()=>{var t,e;if('open'===(null===(t=this.source)||void 0===t?void 0:t.readyState))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(t.merge(this.videoBufferManager.error$,this.audioBufferManager.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)})));(yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)])).some((t=>!t))||(this.state$.setState(ql.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...Hl.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),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.tick())}))}switchRepresentation(e,i){return p(this,void 0,void 0,(function*(){const s={[ji.VIDEO]:this.videoBufferManager,[ji.AUDIO]:this.audioBufferManager,[ji.TEXT]:null}[e];return t.assertNonNullable(s),s.switchTo(i)}))}seek(e){t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),t.assertNonNullable(this.audioBufferManager),this.videoBufferManager.maintain(e),this.audioBufferManager.maintain(e),this.element.currentTime=e/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.state$.setState(ql.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Gl||(Gl={}));const zl=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?os(a):void 0)&&void 0!==n?n:fs({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Ql=(t,e,i)=>{var s;const r=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=zi(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:zi(t,-1)};class Wl{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(Gl.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Zi,this.videoTracks=[],this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const a=null==r?void 0:r.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(a)&&e!==Gl.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a),i!==exports.PlaybackState.STOPPED){if(e===Gl.STOPPED)return this.videoState.startTransitionTo(Gl.READY),void this.prepare();switch(e){case Gl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Gl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Gl.PLAYING),this.playIfAllowed()));case Gl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Gl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Gl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Gl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Gl.STOPPED&&(this.videoState.startTransitionTo(Gl.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(Gl.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=ts(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ks(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new Yl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=as(this.video),r=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.firstFrame$,e.firstFrameEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ji(this.video,i.isLooped,r)),this.subscription.add(Ki(this.video,i.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),a($s(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(Gl.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),r)).add(s.pause$.subscribe((()=>{this.videoState.setState(Gl.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),r)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===Gl.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===ql.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Gl.READY)}))),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 e,s,r;const a=this.player.state$.getState(),n=this.player.state$.getTransition();if(a===ql.NONE||!this.videoTracks.length)return;const o=a===ql.MANIFEST_LOADED&&!n,u=i.autoVideoTrackSwitching.getState(),d=i.videoTrack.getState(),l=null===(e=this.videoTracks.find((({track:{id:t}})=>t===d)))||void 0===e?void 0:e.track;i.autoVideoTrackSwitching.getTransition()&&i.autoVideoTrackSwitching.setState(u);const c=ws(this.video.buffered,1e3*this.video.currentTime),h=Math.min(c/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),p=Ps(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(),forwardBufferHealth:h}),m=u?null!=p?p:l:null!=l?l:p;if(o){const e=m&&(null===(s=this.videoTracks.find((({track:t})=>t===m)))||void 0===s?void 0:s.representation);t.assertNonNullable(e);const i=Ql(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),e);t.assertNonNullable(i),this.player.initRepresentations(e.id,i.id)}else{const t=m&&(null===(r=this.videoTracks.find((({track:t})=>t===m)))||void 0===r?void 0:r.representation);if(t){const e=Ql(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(ji.VIDEO,t.id),e&&this.player.switchRepresentation(ji.AUDIO,e.id)}}}),r)),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$,r)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}prepare(){return p(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=zl(e);t&&this.videoTracks.push({track:t,representation:e})}this.audioRepresentations=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t){this.params.output.willSeekEvent$.next(),this.player.seek(1e3*t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(Gl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Jl;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Jl||(Jl={}));var Kl=(e,i=0,s=Jl.OFFSET_P)=>{switch(s){case Jl.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case Jl.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};var Xl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Xl||(Xl={}));class Zl{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new As(Xl.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(a)};`}),s===exports.PlaybackState.STOPPED)return void(e!==Xl.STOPPED&&(this.videoState.startTransitionTo(Xl.STOPPED),this.stop()));if(i)return;const n=null==a?void 0:a.to;if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&e!==Xl.STOPPED)this.seek(n);else switch(s){case exports.PlaybackState.PLAYING:switch(e){case Xl.PLAYING:break;case Xl.PAUSED:case Xl.READY:this.videoState.startTransitionTo(Xl.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Xl.STOPPED:this.videoState.startTransitionTo(Xl.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Xl.PLAYING:this.videoState.startTransitionTo(Xl.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Xl.PAUSED:break;case Xl.READY:this.videoState.startTransitionTo(Xl.PAUSED),this.videoState.setState(Xl.PAUSED);break;case Xl.STOPPED:this.videoState.startTransitionTo(Xl.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}},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_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM: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((e=>{this.logRemoteEvent(e);const r=e.value;this.params.output.position$.next(r);const a=this.params.desiredState.seekPosition.getTransition();(t.isNonNullable(a)&&t.isNullable(a.to)||Math.abs(r-s)>5)&&i.next(r),s=r}))),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,r=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(r!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),us(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.seekPosition.stateChangeStarted$,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(Xl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Xl.PLAYING),us(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.seekPosition.setState(void 0)}}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)!==Xl.PAUSED&&t!==Xl.PLAYING||(this.videoState.setState(Xl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Xl.PLAYING&&t!==Xl.PAUSED||(this.videoState.setState(Xl.PLAYING),us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Xl.READY&&this.videoState.setState(Xl.READY)}handleRemoteStop(){this.videoState.getState()!==Xl.STOPPED&&this.videoState.setState(Xl.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}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 r,a,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:hs(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),r=u,a='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),r=Kl(i.url),a='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(t){var e;const i=new chrome.cast.media.LoadRequest(t);i.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return i.currentTime=s?this.params.output.isLive$.getValue()?0:null!==(e=s.to)&&void 0!==e?e:0:0,i}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)'))))}));$l(Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});const t=this.params.desiredState.seekPosition;t.getTransition()&&t.setState(void 0),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})),(()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}var tc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(tc||(tc={}));class ec{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(tc.STOPPED),this.trackUrls={},this.textTracksManager=new Zi,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!==tc.STOPPED&&(this.videoState.startTransitionTo(tc.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(tc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(e===tc.STOPPED)return this.videoState.startTransitionTo(tc.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a||this.params.desiredState.seekPosition.startTransitionTo(t))}const n=null==a?void 0:a.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&this.seek(n),e){case tc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(tc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(tc.PLAYING),this.playIfAllowed()));case tc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(tc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case tc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(tc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=ts(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.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(tc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(tc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===tc.READY&&this.videoState.setState(tc.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()===tc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.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');const{url:r}=this.trackUrls[s];t.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.video.setAttribute('src',r),this.video.load(),this.params.output.hostname$.next(ks(r))}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(tc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}class ic{constructor(t,e=[],i,s,r,a){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=r,this._errorCb=a,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,r,a,n,o,u,d;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===(r=this._xhr)||void 0===r?void 0:r.status}`,`XHR response code ${null===(a=this._xhr)||void 0===a?void 0:a.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===(n=this._headersCb)||void 0===n||n.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(o=this._completeCb)||void 0===o||o.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.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 sc{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,r,a,n){this.abort((()=>{let o=0;const u=Date.now();let d=0,l=0,c=0;const h=t=>{s(sc._str2ua(t.substr(o))),o=t.length};this._lastXhr=new ic(t.baseURL+'&bytes='+e+'-'+i,t.failoverHosts,(t=>{this._lastXhr=void 0,h(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&h(t),0===l)return void(l=Date.now());c=t.length-d;const e=Date.now()-l;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,d=t.length,l=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((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=sc._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 rc{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){new ic(t,e,(i=>{this.attachManifest(i,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(t))}),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,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,u,d,l,c,h,p,m,f,v,b,S,g,y,T,E,P,w;const k=t.getElementsByTagName('SegmentBase')[0],$=k&&r(k,'indexRange').split('-'),A=k&&k.getElementsByTagName('Initialization')[0],x=A&&r(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(l=null===(d=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===d?void 0:d[0])||void 0===l?void 0:l.data),h=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:h})}return}const N=Number(null===(h=t.attributes.getNamedItem('bandwidth'))||void 0===h?void 0:h.value),_=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=R?jl(R):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:N,baseURL:_,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(S=null===(b=t.attributes.getNamedItem('codecs'))||void 0===b?void 0:b.value)&&void 0!==S?S: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===(P=t.attributes.getNamedItem('id'))||void 0===P?void 0:P.value)&&void 0!==w?w:void 0})})),a.length?(this._representations=a,n.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 r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const u=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const d=t.refs[t.refs.length-1];d.toTime-d.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,r;const a=()=>{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 a;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');a=e.end-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.end&&(r=e.end,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.start)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new sc({mediaSource:i,sourceBuffer:e,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||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!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){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const s=this._findRef(e);if(s){if(i){this._isLastRef(s)&&e>=s.toTime&&(e=s.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:s.fromTime}this._appendVector[String(s.fromTime)]=t,this._stream.load(t,s.fromOffset,s.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=s.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 r=.1;if(s.toTime<i.end+r){const e=this._findRef(s.toTime);e&&e.toTime<i.end+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((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=!1){this._stream&&this._buffer.getByTime(t)&&!e?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0)}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 r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}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 ac;!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'}(ac||(ac={}));const nc=[ac.PAUSED,ac.PLAYING];class oc{constructor(e){this.videoState=new As(ac.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Zi,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 r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&os(a.name))&&void 0!==s?s:fs(a),o=a.bandwidth/1e3,u={width:a.width,height:a.height},d=a.fps;if(!n)continue;const l={id:t,quality:n,bitrate:o,size:u,fps:d};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(ac.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(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekPositionTransition: ${JSON.stringify(a)};`}),s===exports.PlaybackState.STOPPED)return void(e!==ac.STOPPED&&(this.videoState.startTransitionTo(ac.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(ac.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(i)return;const n=null==a?void 0:a.to;switch((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&nc.includes(e)&&this.seek(n),e){case ac.STOPPED:return this.videoState.startTransitionTo(ac.MANIFEST_LOADED),void this.prepare();case ac.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ac.INITIAL_REPRESENTATION_SELECTED);case ac.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ac.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ac.METADATA_LOADED:return this.videoState.startTransitionTo(ac.READY),void this.dash.seek(null!=n?n:0);case ac.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(ac.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ac.PLAYING),this.playIfAllowed()));case ac.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ac.PAUSED),this.video.pause()):(null==r?void 0:r.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ac.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ac.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},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=ts(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(ks(this.params.source.url)),this.buffer=new is(this.video),this.dash=new rc({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,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},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}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},r=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},a=as(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.firstFrame$,e.firstFrameEvent$),this.subscription.add(a.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===ac.PLAYING||this.videoState.getState()===ac.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),n($s(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===ac.READY&&this.videoState.setState(ac.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(ac.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(a.playing$.subscribe((()=>{this.videoState.setState(ac.PLAYING),us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.loadedMetadata$.subscribe((()=>{this.videoState.setState(ac.METADATA_LOADED)}),s)).add(a.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).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;const s=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),l=r();let c;if(n&&this.params.desiredState.autoVideoTrackSwitching.setState(n.to),!l&&t.isNonNullable(o))c=o;else{const t=ws(this.video.buffered,1e3*this.video.currentTime),i=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);c=null===(e=Ps(a.map((({track:t})=>t)),{container:d,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:s}))||void 0===e?void 0:e.id}return t.isNonNullable(c)?null===(i=a.find((({track:t})=>t.id===c)))||void 0===i?void 0:i.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===ac.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(ac.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?t.height<=e.height:t===e))).subscribe((t=>{const e=ws(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!r())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(ks(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Al(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).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.seekPosition.stateChangeStarted$,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){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(ac.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var uc=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,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},dc=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 lc=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class cc{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)}executeNextRequests(){return p(this,void 0,void 0,(function*(){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[r,a]=lc(s.request);if(r>=i.from&&a<=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),r=this.activeRequests.get(i.url);s&&r&&r.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(t,e){const i=e.map(lc),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const n=a.toString(),o=new yo,u=o.signal,d={url:t,from:s,to:r,loaded:0,data:null,abortController:o};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const l=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return To(fetch).fetch(n,{signal:u}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(d);const[r,a]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,a);const n=r.getReader(),o=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);d.data=new ArrayBuffer(o);const u=new Uint8Array(d.data),c=({done:t,value:e})=>p(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(d):e&&(u.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),yield null==n?void 0:n.read().then(c,cc.suppressStreamErrors).catch(l))}));null==n||n.read().then(c,cc.suppressStreamErrors).catch(l)}),cc.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r}){var a,n,o,u,d,l,c;if(!this.activeRequests.has(t)||!r)return;const h=null!==(a=this.dashJsRequestQueue.get(t))&&void 0!==a?a:[];for(const a of h){const{request:h}=a,[p,m]=lc(h),f=p>=e&&m<=e+s,v=e>=p&&e+s<m,b=r.slice(p-e,Math.min(m-e+1,s));(f||v)&&(h.requestStartDate=null!==(n=h.requestStartDate)&&void 0!==n?n:new Date,h.firstByteDate=null!==(o=h.firstByteDate)&&void 0!==o?o:new Date,h.bytesLoaded=b.byteLength,h.bytesTotal=i-e),f?(h.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==a))),null===(d=a.success)||void 0===d||d.call(a,b,'',t),null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(h,t,200,{},[])):v&&(null===(c=a.progress)||void 0===c||c.call(a,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,n,o;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const u=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of u){const[r,a]=lc(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=lc(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.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 hc{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(hc.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;hc.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const pc=(t,e)=>{const i=new cc(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new hc(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var mc=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject;let r=NaN,a=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,n=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const n=e.onload,o=e.progress;e.onload=function(...e){return(e=>{var s,r,a;if(!e.getAllResponseHeaders().includes('x-playback-duration'))return;const n=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),o=parseInt(null!==(r=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==r?r:'',10),u=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)})(this),n(...e)},e.progress=function(...t){return this.readyState>=2&&!a&&(a=!0,s.next(Date.now()-r)),o(...t)},r=Date.now(),a=!1}return n(e)}}}),!0),{playbackDuration$:i,ping$:s}};class fc{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}}const vc={};var bc;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(bc||(bc={}));const Sc=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class gc{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(bc.DOWNLOADING_LIB),this.textTracksManager=new Zi,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 fc,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition(),a=this.isLive$.getValue();if(this.videoState.getTransition())return;if(e===bc.DOWNLOADING_LIB||e===bc.STREAM_INITIALIZED)return;const n=null==r?void 0:r.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&e!==bc.STOPPED&&i!==exports.PlaybackState.STOPPED&&(a?this.seek(n+yc(this.liveOffset.getTotalPausedTime())):this.seek(n)),i){case exports.PlaybackState.STOPPED:switch(e){case bc.STOPPED:break;case bc.PLAYING:case bc.PAUSED:case bc.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case bc.PLAYING:break;case bc.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(yc(this.liveOffset.getTotalOffset()))):this.seek(yc(this.liveOffset.getTotalOffset()))),this.play();break;case bc.READY:this.play();break;case bc.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case bc.PLAYING:this.pause(),this.liveOffset.pause();break;case bc.PAUSED:break;case bc.READY:this.videoState.setState(bc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case bc.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=ts(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ks(this.params.source.url)),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);$l(Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(vc.MediaPlayer=e.MediaPlayer,vc.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(vc.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(vc.Debug,'dashjs not loaded'),this.player=vc.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?jl(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=pc(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&&dc(this.player),uc(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(bc.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r($s(this.video),this.elementSize$),r(Sc(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$),r(Sc(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const a=Sc(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})));a.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===bc.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Wi(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$:a.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Wi(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})),r(Sc(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),r(Sc(this.player,'fragmentLoadingStarted').pipe(t.map((t=>ks(t.request.url)))),e.hostname$),r(Sc(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 r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=fs(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===r&&(a=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&e.currentVideoTrack$.next(a),this.videoState.setState(bc.STREAM_INITIALIZED),this.videoState.startTransitionTo(bc.READY)})),r(Sc(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)})),r(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=Ps(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)})),r(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>yc(t)))),this.params.output.duration$);const n=Sc(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));r(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),r(Sc(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),r(Sc(this.player,'playbackEnded'),e.endedEvent$),r(Sc(this.player,'playbackProgress').pipe(t.map((()=>ss(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),r(Sc(this.player,'playbackPlaying'),(()=>{this.videoState.setState(bc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)})),r(Sc(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(bc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Sc(this.player,'playbackPaused'),(()=>{this.videoState.setState(bc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)})),r(Sc(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===bc.READY&&this.videoState.setState(bc.READY)})),r(this.isLive$,e.isLive$),r($s(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u}=mc(this.player);r(o,this.maxSeekBackTime$),r(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(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}}})})),r(n.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(Sc(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(Sc(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(Ji(this.video,i.isLooped,s));const{volumeState$:d,looped$:l}=as(this.video);this.subscription.add(Ki(this.video,i.volume,d,s)),this.subscription.add(d.subscribe(e.volume$,s)),this.subscription.add(l.subscribe(e.loopedEvent$))}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(bc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(bc.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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(yc(i));const s=Kl(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Jl.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(bc.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(bc.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)}}const yc=t=>-t/1e3;function Tc(){return t.now()}function Ec(t){return Tc()-t}function Pc(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function wc(e,i,s,r){const a=window.XMLHttpRequest;let n,o,u,d,l,c=!1,h=0,p=!1,m='arraybuffer',f=7e3,v=2e3,b=()=>{if(c)return;t.assertNonNullable(d);const e=Ec(d);let i;if(e<v)return i=v-e,void setTimeout(b,i);v*=2,v>f&&(v=f),o&&o.abort(),o=new a,g()};const S=()=>{if(!c){if(--h>=0)return b(),void(r&&r());c=!0,l&&l(),s&&s()}},g=()=>{d=Tc(),o=new a,o.open('get',e);let s,r=0,h=0;const f=()=>(t.assertNonNullable(d),Math.max(d,Math.max(s||0,h||0)));if(n&&o.addEventListener('progress',(t=>{const e=Tc();n.updateChunk&&t.loaded>r&&(n.updateChunk(f(),t.loaded-r),r=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>S()))),o.addEventListener('load',(()=>{if(c)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-r;t&&n.updateChunk&&n.updateChunk(f(),t)}l&&l(),o&&i(o.response)}else S()})),o.addEventListener('error',(()=>{S()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(h=Tc(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(h=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(v=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(l=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),c=!0,l&&l()}};return y}class kc{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 r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/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 $c{constructor(t,e,i,s,r){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=r}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=Tc(),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=wc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Tc()-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=Tc()}_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=Tc();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 r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._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(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}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 Ac{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 kc(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Pc(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=Pc(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',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.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,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));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(e,i){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s('setting video src'),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{t.assertNonNullable(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],i()})),this.videoPlayStarted=!1,r.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const n=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(r,'progress',(()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:'playing'})):n()}))};n()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new $c(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const t=a&&(!l||l===this.rep);return t||i('Not running!'),t},h=(t,e,i)=>{u&&u.abort(),u=wc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=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}`),v()},v=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=Tc()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const r=this.bufferStates[i];t=Math.min(t,r.buf),r.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,m(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else m(1)},b=e=>{let s;const a=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,l=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),h=()=>{let t=0;if(s&&s.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=s.dur.length-1;t>=0&&(e-=s.dur[t]/1e3,!(e<=0));--t);}return l(t,!0)},p=(t,e,i)=>{d&&d.abort(),d=wc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{d=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!c())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let d=0;for(let t=0;t<s.dur.length;++t)d+=s.dur[t];d>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(d/s.dur.length)),r({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=a();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return l(t);return h()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=a(),r=t?t.chunkIdx+1:0,n=r-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),h();if(!(n>=e))return l(r-s.fragIndex,!1)}}}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:i=>{const{videoElement:s,logger:r}=this.params;let o,u,l,m,f,g,y,T=b(e.jidxUrl),E=0;const P=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=Tc(),s=Math.min(1e4,e-i);E=i;const r=()=>{d||c()&&T.seek((()=>{c()&&(E=Tc(),w(),P())}))};s>0?f=window.setTimeout((()=>{this.paused?P():r()}),s):r()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(l);if(i){if(l&&i.discontinuity)return r('Detected discontinuity; restarting playback'),void(this.paused?P():(S(),this._initPlayerWith(e)));x(i)}else P()},k=(t,e)=>{if(!c()||!this.sourceBuffer)return;let i,a,n;const o=i=>{window.setTimeout((()=>{c()&&k(t,e)}),i)};if(this.sourceBuffer.updating)r('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=Tc(),d=s.currentTime;!this.paused&&s.buffered.length>1&&g===d&&u-y>500&&(r('Stall suspected; trying to fix'),this._fixupStall()),g!==d&&(g=d,y=u);const l=this._getBufferSizeSec();if(l>30)r(`Buffered ${l} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:l}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;r('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),a=d,a-i>4&&this.sourceBuffer.remove(i,a-3)),o(1e3)}}},$=()=>{u&&o&&(r([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(l)]),k(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{c()&&p(A(t),((e,i)=>{if(c()){if(i/=1e3,u=e,l=t,n=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=>{c()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},_=t=>{c()&&(e.cachedHeader=t,k(t,(()=>{o=!0,$()})))};a=!0,T.seek((e=>{c()&&(E=Tc(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(l=e,w())):P())}),i),e.cachedHeader?_(e.cachedHeader):h(e.headerUrl,_,(()=>this._handleNetworkError()))},stop:S,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),t.isNonNullable(r)&&(r+=.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(r),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,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.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=Tc();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&Ec(a)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Tc();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=wc(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;Qi(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 xc;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xc||(xc={}));const Nc=[xc.PAUSED,xc.PLAYING,xc.READY],_c=[xc.PAUSED,xc.PLAYING,xc.READY];class Dc{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(xc.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Zi,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new fc,this._dashCb=e=>{var i,s,r,a;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}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,a=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),r=null!==(s=os(e.name))&&void 0!==s?s:fs(e.video),n=e.bitrate/1e3,o=Object.assign({},e.video);if(!r)continue;const u={id:t,quality:r,bitrate:n,size:o};a.push({track:u,representation:e})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===xc.MANIFEST_READY&&this.videoState.setState(xc.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(a=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===a?void 0:a.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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekPositionTransition: ${JSON.stringify(n)};`}),r===exports.PlaybackState.STOPPED)return void(i!==xc.STOPPED&&(this.videoState.startTransitionTo(xc.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(xc.STOPPED)));if(s)return;if(_c.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)}const o=null==n?void 0:n.to;if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&Nc.includes(i))this.seek(o+Rc(this.liveOffset.getTotalPausedTime()));else switch(i){case xc.STOPPED:return this.videoState.startTransitionTo(xc.MANIFEST_READY),void this.dash.attachSource(Kl(this.params.source.url));case xc.MANIFEST_READY:this.videoState.startTransitionTo(xc.READY),this.prepare();break;case xc.READY:return void(r===exports.PlaybackState.PAUSED?this.videoState.setState(xc.PAUSED):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(xc.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(xc.PAUSED)}))));case xc.PLAYING:return void(r===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(xc.PAUSED),this.liveOffset.pause(),this.dash.pause()));case xc.PAUSED:return void(r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(xc.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(xc.PAUSED)})),this.params.output.position$.next(Rc(this.liveOffset.getTotalOffset()))):this.seek(Rc(this.liveOffset.getTotalOffset()))));default:return t.assertNever(i)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};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=ts(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(ks(this.params.source.url)),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=as(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===xc.READY&&this.videoState.setState(xc.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(xc.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(xc.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(Rc)).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(Ji(this.video,this.params.desiredState.isLooped,i)).add(Ki(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(rs(this.video).subscribe(this.params.output.firstBytesEvent$)).add(es(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&ds[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case xc.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case xc.MANIFEST_READY:case xc.READY:break;case xc.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case xc.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.seekPosition.stateChangeStarted$,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 Ac({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,r,a,n;const o=this.representations$.getValue(),u=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(),d=null!==(r=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&t.isNonNullable(u)?u:null===(a=Ps(o.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===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===l)))||void 0===n?void 0:n.representation;t.assertNonNullable(c),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}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),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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Rc(i)),this.dash.reinit(Kl(this.params.source.url,i)),this.params.output.seekedEvent$.next()}}const Rc=t=>-t/1e3,Ic=t=>{let e=null;if(t.QUALITY&&(e=os(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=fs({width:i,height:s})}return null!=e?e:null},Lc=(t,e=t)=>p(void 0,void 0,void 0,(function*(){var i;const s=yield To(fetch).fetch(t),r=(yield s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=ao(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=Ic(n);let d;n.BANDWIDTH&&(d=parseInt(n.BANDWIDTH,10)/1e3||void 0),!d&&n['AVERAGE-BANDWIDTH']&&(d=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const l=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const h=new URL(r[++t],e).toString();u&&a.push({id:o,quality:u,url:h,bandwidth:d,size:c,fps:l})}return a}));var Cc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Cc||(Cc={}));class Oc{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(Cc.STOPPED),this.textTracksManager=new Zi,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Cc.STOPPED&&(this.videoState.startTransitionTo(Cc.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(Cc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekPosition.getTransition();if(e===Cc.STOPPED)return this.videoState.startTransitionTo(Cc.READY),void this.prepare();if(r||a){const e=this.videoState.getState();this.videoState.setState(Cc.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const{currentTime:i}=this.video;return this.prepare(),void(n&&!t.isNullable(n.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const o=null==n?void 0:n.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&this.seek(o),e){case Cc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Cc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Cc.PLAYING),this.playIfAllowed()));case Cc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Cc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Cc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Cc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Cc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=ts(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(ks(this.params.source.url)),Lc(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Cc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Cc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Cc.READY&&this.videoState.setState(Cc.READY),this.videoState.getState()===Cc.PLAYING&&this.playIfAllowed()}),s).add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=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(ks(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Cc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.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(){Qi(this.video).then((t=>{t||(this.videoState.setState(Cc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}var Vc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Vc||(Vc={}));class Mc{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new As(Vc.STOPPED),this.textTracksManager=new Zi,this.manifests$=new t.ValueSubject([]),this.liveOffset=new fc,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(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Vc.STOPPED&&(this.videoState.startTransitionTo(Vc.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(Vc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekPosition.getTransition();if(e===Vc.STOPPED)return this.videoState.startTransitionTo(Vc.READY),void this.prepare();if(r||a){const e=this.videoState.getState();this.videoState.setState(Vc.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const i=Bc(this.liveOffset.getTotalOffset());return this.prepare(),void(n&&!t.isNullable(n.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const o=null==n?void 0:n.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o))return this.videoState.startTransitionTo(Vc.READY),this.seek(o+Bc(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(e){case Vc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Vc.PAUSED),this.liveOffset.pause(),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Vc.PLAYING),this.playIfAllowed()));case Vc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Vc.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Vc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Vc.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Bc(this.liveOffset.getTotalOffset()))):this.seek(Bc(this.liveOffset.getTotalOffset()))):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Vc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=ts(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]),Lc(Kl(this.params.source.url)).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ks(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,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Vc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Vc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Vc.READY&&this.videoState.setState(Vc.READY),this.videoState.getState()===Vc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(Bc)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=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(ks(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Vc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:r.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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.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=Kl(e.url,this.liveOffset.getTotalOffset());var s;this.video.setAttribute('src',i),this.video.load(),(s=i,p(void 0,void 0,void 0,(function*(){const t=yield To(fetch).fetch(s,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(Vc.PAUSED),this.liveOffset.pause(),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Bc(i)),this.params.output.seekedEvent$.next()}}const Bc=t=>-t/1e3,Fc={};var Uc;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Uc||(Uc={}));const jc=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Hc{constructor(e){this.subscription=new t.Subscription,this.videoState=new As(Uc.INITIALIZING),this.textTracksManager=new Zi,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(e===Uc.INITIALIZING)return;const a=null==r?void 0:r.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(a)&&this.seek(a),i){case exports.PlaybackState.STOPPED:switch(e){case Uc.STOPPED:break;case Uc.READY:case Uc.PLAYING:case Uc.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Uc.PLAYING:break;case Uc.STOPPED:this.prepare();break;case Uc.READY:case Uc.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Uc.PAUSED:break;case Uc.STOPPED:this.prepare();break;case Uc.READY:this.videoState.setState(Uc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Uc.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=ts(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ks(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 t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);$l(Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(Fc.Hls=e.default,Fc.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(Fc.Hls,'hls.js not loaded'),this.hls=new Fc.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Uc.STOPPED)}subscribe(){t.assertNonNullable(Fc.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,i.position$),a(r.durationChange$,i.duration$),a(r.ended$,i.endedEvent$),a(r.looped$,i.loopedEvent$),a(r.error$,i.error$),a(r.isBuffering$,i.isBuffering$),a(r.currentBuffer$,i.currentBuffer$),a(r.firstBytes$,i.firstBytesEvent$),a(r.firstFrame$,i.firstFrameEvent$),a(r.seeked$,i.seekedEvent$),this.subscription.add(Ji(this.video,e.isLooped,s)),this.subscription.add(Ki(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(jc(this.hls,Fc.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Uc.PLAYING),us(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Uc.PAUSED),us(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Uc.READY&&this.videoState.setState(Uc.READY),this.videoState.getState()===Uc.PLAYING&&this.playIfAllowed()}),s)),a(jc(this.hls,Fc.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=os(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:fs({width:a,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,d={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:u};return this.trackLevels.set(r,{track:d,level:e}),t.push(d),t}),[])))),i.availableVideoTracks$),a(jc(this.hls,Fc.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>ks(t)))),i.hostname$),this.subscription.add(Wi(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 n=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track};a(e.autoVideoTrackLimits.stateChangeEnded$,(({to:t})=>{if(t.max){let e=-1;for(const{track:i,level:s}of this.trackLevels.values())!vs(i.quality)&&ps(i.quality,t.max)&&(e=Math.max(e,this.hls.levels.indexOf(s)));this.hls.autoLevelCapping=e}else this.hls.autoLevelCapping=-1;if(t.min){let e=1/0;for(const{track:i,level:s}of this.trackLevels.values())!vs(i.quality)&&cs(i.quality,t.min)&&(e=Math.min(e,s.bitrate));this.hls.config.minAutoBitrate=isFinite(e)?e:0}else this.hls.config.minAutoBitrate=0}));const o=jc(this.hls,Fc.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>n(this.hls.levels[t]))));o.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(Wi(e.videoTrack,(()=>{var t;return null===(t=n(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 r=this.hls.levels.indexOf(s),a=this.hls.currentLevel,n=this.hls.levels[a];!n||s.bitrate>n.bitrate?this.hls.nextLevel=r:(this.hls.loadLevel=r,this.hls.loadLevel=r)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),a(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Uc.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return p(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(Uc.PLAYING);(yield Qi(this.video))||(this.videoState.setState(Uc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(Uc.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}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(Uc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class qc{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)}}var Gc,Yc,zc,Qc,Wc,Jc,Kc,Xc,Zc,th,eh,ih,sh,rh,ah,nh,oh;const uh=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),dh=(null===(Gc=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Gc?void 0:Gc.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),lh=document.createElement('video'),ch={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(zc=null===(Yc=window.SourceBuffer)||void 0===Yc?void 0:Yc.prototype)||void 0===zc?void 0:zc.appendBuffer)),hls:Boolean((null===(Qc=lh.canPlayType)||void 0===Qc?void 0:Qc.call(lh,'application/x-mpegurl'))||(null===(Wc=lh.canPlayType)||void 0===Wc?void 0:Wc.call(lh,'vnd.apple.mpegURL')))},hh={mp4:Boolean(null===(Jc=lh.canPlayType)||void 0===Jc?void 0:Jc.call(lh,'video/mp4')),webm:Boolean(null===(Kc=lh.canPlayType)||void 0===Kc?void 0:Kc.call(lh,'video/webm'))},ph={h264:Boolean(null===(Zc=null===(Xc=window.MediaSource)||void 0===Xc?void 0:Xc.isTypeSupported)||void 0===Zc?void 0:Zc.call(Xc,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(eh=null===(th=window.MediaSource)||void 0===th?void 0:th.isTypeSupported)||void 0===eh?void 0:eh.call(th,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(sh=null===(ih=window.MediaSource)||void 0===ih?void 0:ih.isTypeSupported)||void 0===sh?void 0:sh.call(ih,'video/webm; codecs="vp9"')),aac:Boolean(null===(ah=null===(rh=window.MediaSource)||void 0===rh?void 0:rh.isTypeSupported)||void 0===ah?void 0:ah.call(rh,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(oh=null===(nh=window.MediaSource)||void 0===nh?void 0:nh.isTypeSupported)||void 0===oh?void 0:oh.call(nh,'audio/webm; codecs="opus"'))},mh=(ph.h264||ph.h265)&&ph.aac,fh=!uh,vh=dh||uh,bh=!ch.hls||!vh,Sh=3e4,gh=18e4,yh=3,Th=100,Eh={cacheDuration:12e4},Ph={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},wh={maxPausedTime:3e4},kh={maxPausedTime:3e4};class $h{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([]),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,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 qc(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return ch.mse&&hh.mp4&&mh&&fh;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return ch.mse&&hh.mp4&&mh;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return ch.mse&&hh.webm&&ph.vp9&&ph.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return ch.mse&&hh.mp4&&mh;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return ch.hls&&hh.mp4&&vh;case exports.VideoFormat.HLS_JS:return ch.mse&&hh.mp4&&mh&&bh;case exports.VideoFormat.MPEG:return hh.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new qc(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(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:'destroyProvider'});const i=this.params.desiredState.seekPosition,s=i.getTransition();s?t.isNonNullable(s.from)&&i.startTransitionTo(s.from):i.startTransitionTo(this.providerOutput.position$.getValue()),e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:r}=this.params,a=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const n=i[e];return t.assertNonNullable(n),new oc({container:s,source:n,desiredState:r,output:a,config:Eh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const n=i[e];return t.assertNonNullable(n),new Wl({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const n=i[e];return t.assertNonNullable(n),new gc({container:s,source:n,desiredState:r,output:a,format:e,config:kh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const n=i[e];return t.assertNonNullable(n),new Oc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const n=i[e];return t.assertNonNullable(n),new Mc({container:s,source:n,desiredState:r,output:a,config:wh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const n=i[e];return t.assertNonNullable(n),new Hc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const n=i[e];return t.assertNonNullable(n),new ec({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const n=i[e];return t.assertNonNullable(n),new Dc({container:s,source:n,desiredState:r,output:a,config:Ph,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new Zl({connection:o,meta:a,container:s,source:i,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var r;return s.add(t.merge(this.providerOutput.error$,(r={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Sh,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=t.timeout(r.maxTransitionInterval),a=new t.ValueSubject(void 0);t.merge(r.desiredPlaybackState$.stateChangeStarted$.pipe(t.mapTo(s)),r.desiredPlaybackState$.stateChangeEnded$.pipe(t.mapTo(void 0)),r.providerChanged$.pipe(t.map((()=>a.getValue())))).subscribe(a);const n=new t.Subscription;return i.add(n),i.add(a.subscribe((t=>{n.unsubscribe(),t&&n.add(t.subscribe(e))}))),i}))).pipe(t.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(Th,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===n.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+gh?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%yh}))),s}}const Ah=(t,e,i)=>i*e+(1-i)*t;class xh{constructor(e){var i;this.prevReported=void 0,this.params=e,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 Ts(`raw_${s}`),this.smoothedSeries$=new Ts(`smoothed_${s}`),this.reportedSeries$=new Ts(`reported_${s}`)}next(e){this.slow=Ah(this.slow,e,this.params.emaAlphaSlow),this.fast=Ah(this.fast,e,this.params.emaAlphaFast);const i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast),this.smoothed$.next(this.smoothed),(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)),this.rawSeries$.next(e),this.smoothedSeries$.next(this.smoothed)}}var Nh;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Nh||(Nh={}));const _h=new Map;let Dh=Nh.RUNTIME;const Rh=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Rh,'test'),localStorage.removeItem(Rh),Dh=Nh.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(Rh),Dh=Nh.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;Dh=Nh.RUNTIME}}})();const Ih=(e,i)=>{switch(Dh){case Nh.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Nh.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Nh.RUNTIME:return void _h.set(e,i);default:t.assertNever(Dh)}},Lh=window.navigator.connection,Ch=()=>{const e=null==Lh?void 0:Lh.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Oh=()=>{const e=null==Lh?void 0:Lh.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Vh=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Mh{constructor(e){var i,s;this.subscription=new t.Subscription,this.tuningConfig=e;const r=Mh.load('one_video_throughput')||(e.useBrowserEstimation?Ch():void 0)||5e3,a=null!==(s=null!==(i=Mh.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Oh():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(r),this.rtt$=new t.ValueSubject(a),this.rttAdjustedThroughput$=new t.ValueSubject(Vh(r,a,e.rttPenaltyRequestSize)),this.throughput=new xh({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new xh({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Ch();e&&this.throughput.next(e);const i=Oh();t.isNonNullable(i)&&this.rtt.next(i)};Lh&&'onchange'in Lh&&this.subscription.add(t.fromEvent(Lh,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ih('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ih('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})=>Vh(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.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const r=new t.Subscription;switch(this.subscription.add(r),e.readyState){case 4:break;case 3:case 2:r.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:r.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}r.add(t.fromEvent(e,'loadend').subscribe((a=>{if(200===e.status){const e=a.loaded,r=t.now(),n=e-i,o=r-s;this.addRawSpeed(n,o)}r.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const r=t.now();let a=0,n=t.now();const o=t=>{i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=({done:e,value:d})=>p(this,void 0,void 0,(function*(){e?this.addRawSpeed(s,t.now()-r):d&&(s+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,t.now()-n),a=0,n=t.now()),yield null==i?void 0:i.read().then(u,o))}));null==i||i.read().then(u,o)}addRawSpeed(t,e){if(Mh.sanityCheck(t,e)){const i=8*t/e;this.throughput.next(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(Dh){case Nh.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case Nh.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case Nh.RUNTIME:return _h.get(e);default:t.assertNever(Dh)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Bh=(e=(t=>t))=>({playbackState:i,seekPosition:s,playbackAbort$:r,looped$:a,position$:n})=>new t.Observable((o=>{let u;const d=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),l=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),c=s.stateChangeEnded$.pipe(t.filter((e=>{var s,r;return t.isNonNullable(e.to)&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),h=s.stateChangeEnded$.pipe(t.filter((e=>{var s,r;return t.isNullable(e.to)&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(d,h).pipe(t.map((()=>e(n.getValue())))),m=t.merge(t.merge(l,c,r).pipe(t.map((()=>e(n.getValue())))),a.pipe(t.map(e)));return(new t.Subscription).add(p.subscribe((t=>{u=e(t)}))).add(m.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const r={start:u,end:s};u=void 0,o.next(r)})))})),Fh=Bh((t=>t)),Uh=Bh((t=>Math.round(1e3*t)+Date.now())),jh={[n.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,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 As(exports.PlaybackState.STOPPED),seekPosition:new As(void 0),volume:new As({volume:1,muted:!1}),videoTrack:new As(void 0),autoVideoTrackSwitching:new As(!0),autoVideoTrackLimits:new As({}),isLooped:new As(!1),externalTextTracks:new As([]),currentTextTrack:new As(void 0),textTrackCuesSettings:new As({})},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),autoQualityLimits$:new t.ValueSubject({}),currentBuffer$:new t.ValueSubject(void 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={started$:new t.Subject,startAttempt$: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,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:gs},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(l)){const s=l[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Mh(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.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(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(e){var i,s;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 $h({screenFormatsPriority:[...jh[n.SCREEN].live,...jh[n.SCREEN].vod],chromecastFormatsPriority:[...jh[n.CHROMECAST].live,...jh[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},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){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekPosition.startTransitionTo(t),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),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}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({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(){var e;t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(i))return this.info.position$.getValue();const s=this.desiredState.seekPosition.getTransition(),r=null!==(e=null==s?void 0:s.to)&&void 0!==e?e:null==s?void 0:s.from;return t.isNonNullable(r)?r:i.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.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$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING)),t.debounce(0)).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition(),i=null==e?void 0:e.to;t.isNonNullable(i)&&(this.desiredState.seekPosition.setState(i),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition();t.isNonNullable(null==e?void 0:e.to)||this.desiredState.seekPosition.setState(void 0),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)=>vs(t)?1:vs(e)?-1:ls(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.currentBuffer$.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((({seekPosition:e,position$:i})=>t.merge(e.stateChangeStarted$.pipe(t.map((t=>t.to)),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>t.isNullable(e.getState())&&t.isNullable(e.getTransition()))))))({seekPosition:this.desiredState.seekPosition,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((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).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 r=0;const a=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),r=i.getValue()||s.getValue();return t&&!r})),t.filterChanged());this.subscription.add(a.subscribe((t=>{t?r=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=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),n.unsubscribe(),e){case!0:n.add(Uh({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:n.add(Fh({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).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=Ps(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),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.seekPosition.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekPosition',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),Ss={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{bs=t})),this.providerContainer.current$.subscribe((({type:t})=>ys('provider',t))),i.duration$.subscribe((t=>ys('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>ys('tracks',t))),this.events.fatalError$.subscribe(new Ts('fatalError')),this.events.managedError$.subscribe(new Ts('managedError')),i.position$.subscribe(new Ts('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new Ts('quality')),i.currentBuffer$.subscribe(new Ts('buffer')),i.isBuffering$.subscribe(new Ts('isBuffering'))].forEach((t=>this.subscription.add(t))),ys('codecs',Object.keys(ph).filter((t=>ph[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.45';
|
|
6
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2015.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'));var r,a,o,n,u,d;exports.PlaybackState=void 0,(r=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',r.PLAYING='playing',r.PAUSED='paused',exports.VideoFormat=void 0,(a=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',a.DASH='DASH',a.DASH_SEP='DASH_SEP',a.DASH_SEP_VK='DASH_SEP_VK',a.DASH_WEBM='DASH_WEBM',a.DASH_WEBM_VK='DASH_WEBM_VK',a.DASH_ONDEMAND='DASH_ONDEMAND',a.DASH_LIVE='DASH_LIVE',a.DASH_LIVE_WEBM='DASH_LIVE_WEBM',a.HLS='HLS',a.HLS_ONDEMAND='HLS_ONDEMAND',a.HLS_JS='HLS_JS',a.HLS_LIVE='HLS_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.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(d=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',d.HTTP2='http2',d.QUIC='quic';const l={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],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};class c{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;var r;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(r='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',r),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',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,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.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,r;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(r=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===r?void 0:r.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((r=>{var a;const o=r===exports.ChromecastState.CONNECTED,n=t.isNonNullable(this.connection$.getValue());if(o&&!n){const r=s.getCurrentSession();t.assertNonNullable(r);const o=r.getCastDevice(),n=null===(a=r.getMediaSession())||void 0===a?void 0:a.media.contentId;(t.isNullable(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:r,castDevice:o}))}else!o&&n&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}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)}};function p(t,e,i,s){return new(i||(i=Promise))((function(r,a){function o(t){try{u(s.next(t))}catch(t){a(t)}}function n(t){try{u(s.throw(t))}catch(t){a(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,n)}u((s=s.apply(t,e||[])).next())}))}var m='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},f=function(t){return t&&t.Math==Math&&t},v=f('object'==typeof globalThis&&globalThis)||f('object'==typeof window&&window)||f('object'==typeof self&&self)||f('object'==typeof m&&m)||function(){return this}()||Function('return this')(),b=function(t){try{return!!t()}catch(t){return!0}},S=!b((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),g=S,y=Function.prototype,T=y.apply,E=y.call,P='object'==typeof Reflect&&Reflect.apply||(g?E.bind(T):function(){return E.apply(T,arguments)}),w=S,k=Function.prototype,$=k.bind,A=k.call,x=w&&$.bind(A,A),N=w?function(t){return t&&x(t)}:function(t){return t&&function(){return A.apply(t,arguments)}},_=function(t){return'function'==typeof t},D={},R=!b((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),I=S,L=Function.prototype.call,C=I?L.bind(L):function(){return L.apply(L,arguments)},O={},V={}.propertyIsEnumerable,M=Object.getOwnPropertyDescriptor,B=M&&!V.call({1:2},1);O.f=B?function(t){var e=M(this,t);return!!e&&e.enumerable}:V;var F,U,j=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},H=N,q=H({}.toString),G=H(''.slice),Y=function(t){return G(q(t),8,-1)},z=N,Q=b,W=Y,J=v.Object,K=z(''.split),X=Q((function(){return!J('z').propertyIsEnumerable(0)}))?function(t){return'String'==W(t)?K(t,''):J(t)}:J,Z=v.TypeError,tt=function(t){if(null==t)throw Z('Can\'t call method on '+t);return t},et=X,it=tt,st=function(t){return et(it(t))},rt=_,at=function(t){return'object'==typeof t?null!==t:rt(t)},ot={},nt=ot,ut=v,dt=_,lt=function(t){return dt(t)?t:void 0},ct=function(t,e){return arguments.length<2?lt(nt[t])||lt(ut[t]):nt[t]&&nt[t][e]||ut[t]&&ut[t][e]},ht=N({}.isPrototypeOf),pt=ct('navigator','userAgent')||'',mt=v,ft=pt,vt=mt.process,bt=mt.Deno,St=vt&&vt.versions||bt&&bt.version,gt=St&&St.v8;gt&&(U=(F=gt.split('.'))[0]>0&&F[0]<4?1:+(F[0]+F[1])),!U&&ft&&(!(F=ft.match(/Edge\/(\d+)/))||F[1]>=74)&&(F=ft.match(/Chrome\/(\d+)/))&&(U=+F[1]);var yt=U,Tt=yt,Et=b,Pt=!!Object.getOwnPropertySymbols&&!Et((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Tt&&Tt<41})),wt=Pt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,kt=ct,$t=_,At=ht,xt=wt,Nt=v.Object,_t=xt?function(t){return'symbol'==typeof t}:function(t){var e=kt('Symbol');return $t(e)&&At(e.prototype,Nt(t))},Dt=v.String,Rt=function(t){try{return Dt(t)}catch(t){return'Object'}},It=_,Lt=Rt,Ct=v.TypeError,Ot=function(t){if(It(t))return t;throw Ct(Lt(t)+' is not a function')},Vt=Ot,Mt=function(t,e){var i=t[e];return null==i?void 0:Vt(i)},Bt=C,Ft=_,Ut=at,jt=v.TypeError,Ht={exports:{}},qt=v,Gt=Object.defineProperty,Yt=function(t,e){try{Gt(qt,t,{value:e,configurable:!0,writable:!0})}catch(i){qt[t]=e}return e},zt=v['__core-js_shared__']||Yt('__core-js_shared__',{}),Qt=zt;(Ht.exports=function(t,e){return Qt[t]||(Qt[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.21.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.21.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Wt=tt,Jt=v.Object,Kt=function(t){return Jt(Wt(t))},Xt=Kt,Zt=N({}.hasOwnProperty),te=Object.hasOwn||function(t,e){return Zt(Xt(t),e)},ee=N,ie=0,se=Math.random(),re=ee(1..toString),ae=function(t){return'Symbol('+(void 0===t?'':t)+')_'+re(++ie+se,36)},oe=v,ne=Ht.exports,ue=te,de=ae,le=Pt,ce=wt,he=ne('wks'),pe=oe.Symbol,me=pe&&pe.for,fe=ce?pe:pe&&pe.withoutSetter||de,ve=function(t){if(!ue(he,t)||!le&&'string'!=typeof he[t]){var e='Symbol.'+t;le&&ue(pe,t)?he[t]=pe[t]:he[t]=ce&&me?me(e):fe(e)}return he[t]},be=C,Se=at,ge=_t,ye=Mt,Te=function(t,e){var i,s;if('string'===e&&Ft(i=t.toString)&&!Ut(s=Bt(i,t)))return s;if(Ft(i=t.valueOf)&&!Ut(s=Bt(i,t)))return s;if('string'!==e&&Ft(i=t.toString)&&!Ut(s=Bt(i,t)))return s;throw jt('Can\'t convert object to primitive value')},Ee=ve,Pe=v.TypeError,we=Ee('toPrimitive'),ke=function(t,e){if(!Se(t)||ge(t))return t;var i,s=ye(t,we);if(s){if(void 0===e&&(e='default'),i=be(s,t,e),!Se(i)||ge(i))return i;throw Pe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Te(t,e)},$e=_t,Ae=function(t){var e=ke(t,'string');return $e(e)?e:e+''},xe=at,Ne=v.document,_e=xe(Ne)&&xe(Ne.createElement),De=function(t){return _e?Ne.createElement(t):{}},Re=De,Ie=!R&&!b((function(){return 7!=Object.defineProperty(Re('div'),'a',{get:function(){return 7}}).a})),Le=R,Ce=C,Oe=O,Ve=j,Me=st,Be=Ae,Fe=te,Ue=Ie,je=Object.getOwnPropertyDescriptor;D.f=Le?je:function(t,e){if(t=Me(t),e=Be(e),Ue)try{return je(t,e)}catch(t){}if(Fe(t,e))return Ve(!Ce(Oe.f,t,e),t[e])};var He=b,qe=_,Ge=/#|\.prototype\./,Ye=function(t,e){var i=Qe[ze(t)];return i==Je||i!=We&&(qe(e)?He(e):!!e)},ze=Ye.normalize=function(t){return String(t).replace(Ge,'.').toLowerCase()},Qe=Ye.data={},We=Ye.NATIVE='N',Je=Ye.POLYFILL='P',Ke=Ye,Xe=Ot,Ze=S,ti=N(N.bind),ei=function(t,e){return Xe(t),void 0===e?t:Ze?ti(t,e):function(){return t.apply(e,arguments)}},ii={},si=R&&b((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ri=v,ai=at,oi=ri.String,ni=ri.TypeError,ui=function(t){if(ai(t))return t;throw ni(oi(t)+' is not an object')},di=R,li=Ie,ci=si,hi=ui,pi=Ae,mi=v.TypeError,fi=Object.defineProperty,vi=Object.getOwnPropertyDescriptor;ii.f=di?ci?function(t,e,i){if(hi(t),e=pi(e),hi(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=vi(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 fi(t,e,i)}:fi:function(t,e,i){if(hi(t),e=pi(e),hi(i),li)try{return fi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw mi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var bi=ii,Si=j,gi=R?function(t,e,i){return bi.f(t,e,Si(1,i))}:function(t,e,i){return t[e]=i,t},yi=v,Ti=P,Ei=N,Pi=_,wi=D.f,ki=Ke,$i=ot,Ai=ei,xi=gi,Ni=te,_i=function(t){var e=function(i,s,r){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,r)}return Ti(t,this,arguments)};return e.prototype=t.prototype,e},Di=function(t,e){var i,s,r,a,o,n,u,d,l=t.target,c=t.global,h=t.stat,p=t.proto,m=c?yi:h?yi[l]:(yi[l]||{}).prototype,f=c?$i:$i[l]||xi($i,l,{})[l],v=f.prototype;for(r in e)i=!ki(c?r:l+(h?'.':'#')+r,t.forced)&&m&&Ni(m,r),o=f[r],i&&(n=t.noTargetGet?(d=wi(m,r))&&d.value:m[r]),a=i&&n?n:e[r],i&&typeof o==typeof a||(u=t.bind&&i?Ai(a,yi):t.wrap&&i?_i(a):p&&Pi(a)?Ei(a):a,(t.sham||a&&a.sham||o&&o.sham)&&xi(u,'sham',!0),xi(f,r,u),p&&(Ni($i,s=l+'Prototype')||xi($i,s,{}),xi($i[s],r,a),t.real&&v&&!v[r]&&xi(v,r,a)))},Ri=Math.ceil,Ii=Math.floor,Li=function(t){var e=+t;return e!=e||0===e?0:(e>0?Ii:Ri)(e)},Ci=Li,Oi=Math.min,Vi=function(t){return t>0?Oi(Ci(t),9007199254740991):0},Mi=function(t){return Vi(t.length)},Bi=Kt,Fi=Mi,Ui=Li;Di({target:'Array',proto:!0},{at:function(t){var e=Bi(this),i=Fi(e),s=Ui(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var ji,Hi,qi,Gi,Yi=ct,zi=Yi('Array','at');!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ji||(ji={})),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'}(Hi||(Hi={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(qi||(qi={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Gi||(Gi={}));var Qi=t=>p(void 0,void 0,void 0,(function*(){const e=t.muted;try{yield 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{yield t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0}));const Wi=(e,i,s,{equal:r=((t,e)=>t===e),changed$:a,onError:o}={})=>{const n=e.getState(),u=i(),d=t.isNullable(a),l=new t.Subscription;return a&&l.add(a.subscribe((t=>{const i=e.getState();r(t,i)&&e.setState(t)}),o)),r(u,n)||(s(n),d&&e.setState(n)),l.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),d&&e.setState(t.to)}),o)),l},Ji=(e,i,s)=>Wi(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Ki=(e,i,s,r)=>Wi(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:r}),Xi=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class Zi{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 r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};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(Wi(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:r})),this.subscription.add(Wi(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:r})),this.subscription.add(Wi(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 r=t=>{var e,i,s,a,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!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(o=t.target)||void 0===o||o.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),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(Zi.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)&&Xi(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 ts=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},es=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class is{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({start:i,end:s,i:e})}return this._buffer.sort((function(t,e){return t.start-e.start})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.start&&t<e.end))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.start-t.end<(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((({start:s,end:r})=>{const a=s>=t&&s<e,o=r>=t&&r<e;a&&o||(a?i(e,r):o?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var ss=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const o=t.start(a),n=t.end(a);if(o<=e&&e<=n){if(s=o,r=n,!i)return{start:s,end:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{start:s,end:r}},rs=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const as=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),r=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>ss(e.buffered,e.currentTime)))),a=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),o=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),n=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let d;return n.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&u.next(d),d=i})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:o,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:n,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:a,firstBytes$:rs(e),firstFrame$:es(e)}};var os;exports.VideoQuality=void 0,(os=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',os.Q_144P='144p',os.Q_240P='240p',os.Q_360P='360p',os.Q_480P='480p',os.Q_720P='720p',os.Q_1080P='1080p',os.Q_1440P='1440p',os.Q_2160P='2160p',os.Q_4320P='4320p';var ns=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}},us=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const ds={[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}},ls=(t,e)=>ds[t].height>ds[e].height,cs=(t,e)=>ds[t].height<ds[e].height,hs=Object.keys(ds).sort(((t,e)=>cs(t,e)?-1:1)),ps=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return hs.find((t=>{const e=ds[t];return e.width>=s&&e.height>=i}))},ms=t=>t===exports.VideoQuality.INVARIANT;let fs=!1,vs={};const bs=t=>{t(vs)},Ss=(t,e)=>{var i;fs&&(vs.meta=null!==(i=vs.meta)&&void 0!==i?i:{},vs.meta[t]=e)};class gs{constructor(t){this.name=t}next(t){var e,i;if(!fs)return;vs.series=null!==(e=vs.series)&&void 0!==e?e:{};const s=null!==(i=vs.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),vs.series[this.name]=s}}const ys=new gs('best_bitrate'),Ts=(e,{container:i,throughput:s,tuning:r,limits:a,forwardBufferHealth:o,currentRepresentation:n})=>{var u,d,l,c;const h=r.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,p=r.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*h*r.containerSizeFactor,height:i.height*h*r.containerSizeFactor},m=p&&ps(p),f=e.filter((t=>!ms(t.quality))).sort(((t,e)=>ls(t.quality,e.quality)?-1:1)),v=null===(d=zi(f,-1))||void 0===d?void 0:d.quality,b=null===(l=zi(f,0))||void 0===l?void 0:l.quality,S=t.isNullable(a)||t.isNonNullable(a.min)&&t.isNonNullable(a.max)&&cs(a.max,a.min)||t.isNonNullable(a.min)&&b&&ls(a.min,b)||t.isNonNullable(a.max)&&v&&cs(a.max,v),g=f.filter((e=>{var i;const u=!m||cs(e.quality,m),d=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s>=e.bitrate*(l=null!=o?o:.5,c=r.bitrateFactorAtEmptyBuffer,h=r.bitrateFactorAtFullBuffer,(c-h)*Math.pow(2,-10*l)+h);var l,c,h;const p=!r.lazyQualitySwitch||!n||(null!=o?o:.5)>=.5||((null===(i=e.size)||void 0===i?void 0:i.height)||0)<=((null==n?void 0:n.height)||0),f=S||(t.isNullable(a.max)||(v=e.quality,b=a.max,ds[v].height<=ds[b].height))&&(t.isNullable(a.min)||((t,e)=>ds[t].height>=ds[e].height)(e.quality,a.min));var v,b;return u&&d&&p&&f}))[0];return g&&g.bitrate&&ys.next(g.bitrate),null!==(c=null!=g?g:f[Math.ceil((f.length-1)/2)])&&void 0!==c?c:e[0]};var Es=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)},Ps=t=>new URL(t).hostname;const ws=(e,i=300)=>new t.Observable((r=>{const{width:a,height:o}=e.getBoundingClientRect();if(r.next({width:a,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,a;i.contentBoxSize&&i.contentBoxSize[0]?(a=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,a=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(a)&&r.next({width:s,height:a})}),i));return n.observe(e),()=>n.disconnect()}));class ks{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 $s={},As=_,xs=zt,Ns=N(Function.toString);As(xs.inspectSource)||(xs.inspectSource=function(t){return Ns(t)});var _s,Ds,Rs,Is=xs.inspectSource,Ls=_,Cs=Is,Os=v.WeakMap,Vs=Ls(Os)&&/native code/.test(Cs(Os)),Ms=Ht.exports,Bs=ae,Fs=Ms('keys'),Us=function(t){return Fs[t]||(Fs[t]=Bs(t))},js={},Hs=Vs,qs=v,Gs=N,Ys=at,zs=gi,Qs=te,Ws=zt,Js=Us,Ks=js,Xs=qs.TypeError,Zs=qs.WeakMap;if(Hs||Ws.state){var tr=Ws.state||(Ws.state=new Zs),er=Gs(tr.get),ir=Gs(tr.has),sr=Gs(tr.set);_s=function(t,e){if(ir(tr,t))throw new Xs('Object already initialized');return e.facade=t,sr(tr,t,e),e},Ds=function(t){return er(tr,t)||{}},Rs=function(t){return ir(tr,t)}}else{var rr=Js('state');Ks[rr]=!0,_s=function(t,e){if(Qs(t,rr))throw new Xs('Object already initialized');return e.facade=t,zs(t,rr,e),e},Ds=function(t){return Qs(t,rr)?t[rr]:{}},Rs=function(t){return Qs(t,rr)}}var ar={set:_s,get:Ds,has:Rs,enforce:function(t){return Rs(t)?Ds(t):_s(t,{})},getterFor:function(t){return function(e){var i;if(!Ys(e)||(i=Ds(e)).type!==t)throw Xs('Incompatible receiver, '+t+' required');return i}}},or=R,nr=te,ur=Function.prototype,dr=or&&Object.getOwnPropertyDescriptor,lr=nr(ur,'name'),cr={EXISTS:lr,PROPER:lr&&'something'===function(){}.name,CONFIGURABLE:lr&&(!or||or&&dr(ur,'name').configurable)},hr={},pr=Li,mr=Math.max,fr=Math.min,vr=st,br=function(t,e){var i=pr(t);return i<0?mr(i+e,0):fr(i,e)},Sr=Mi,gr=function(t){return function(e,i,s){var r,a=vr(e),o=Sr(a),n=br(s,o);if(t&&i!=i){for(;o>n;)if((r=a[n++])!=r)return!0}else for(;o>n;n++)if((t||n in a)&&a[n]===i)return t||n||0;return!t&&-1}},yr={includes:gr(!0),indexOf:gr(!1)},Tr=te,Er=st,Pr=yr.indexOf,wr=js,kr=N([].push),$r=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Ar=function(t,e){var i,s=Er(t),r=0,a=[];for(i in s)!Tr(wr,i)&&Tr(s,i)&&kr(a,i);for(;e.length>r;)Tr(s,i=e[r++])&&(~Pr(a,i)||kr(a,i));return a},xr=$r,Nr=Object.keys||function(t){return Ar(t,xr)},_r=R,Dr=si,Rr=ii,Ir=ui,Lr=st,Cr=Nr;hr.f=_r&&!Dr?Object.defineProperties:function(t,e){Ir(t);for(var i,s=Lr(e),r=Cr(e),a=r.length,o=0;a>o;)Rr.f(t,i=r[o++],s[i]);return t};var Or,Vr=ct('document','documentElement'),Mr=ui,Br=hr,Fr=$r,Ur=js,jr=Vr,Hr=De,qr=Us('IE_PROTO'),Gr=function(){},Yr=function(t){return'<script>'+t+'<\/script>'},zr=function(t){t.write(Yr('')),t.close();var e=t.parentWindow.Object;return t=null,e},Qr=function(){try{Or=new ActiveXObject('htmlfile')}catch(t){}var t,e;Qr='undefined'!=typeof document?document.domain&&Or?zr(Or):((e=Hr('iframe')).style.display='none',jr.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Yr('document.F=Object')),t.close(),t.F):zr(Or);for(var i=Fr.length;i--;)delete Qr.prototype[Fr[i]];return Qr()};Ur[qr]=!0;var Wr,Jr,Kr,Xr=Object.create||function(t,e){var i;return null!==t?(Gr.prototype=Mr(t),i=new Gr,Gr.prototype=null,i[qr]=t):i=Qr(),void 0===e?i:Br.f(i,e)},Zr=!b((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ta=v,ea=te,ia=_,sa=Kt,ra=Zr,aa=Us('IE_PROTO'),oa=ta.Object,na=oa.prototype,ua=ra?oa.getPrototypeOf:function(t){var e=sa(t);if(ea(e,aa))return e[aa];var i=e.constructor;return ia(i)&&e instanceof i?i.prototype:e instanceof oa?na:null},da=gi,la=function(t,e,i,s){s&&s.enumerable?t[e]=i:da(t,e,i)},ca=b,ha=_,pa=Xr,ma=ua,fa=la,va=ve('iterator'),ba=!1;[].keys&&('next'in(Kr=[].keys())?(Jr=ma(ma(Kr)))!==Object.prototype&&(Wr=Jr):ba=!0);var Sa=null==Wr||ca((function(){var t={};return Wr[va].call(t)!==t}));ha((Wr=Sa?{}:pa(Wr))[va])||fa(Wr,va,(function(){return this}));var ga={IteratorPrototype:Wr,BUGGY_SAFARI_ITERATORS:ba},ya={};ya[ve('toStringTag')]='z';var Ta='[object z]'===String(ya),Ea=v,Pa=Ta,wa=_,ka=Y,$a=ve('toStringTag'),Aa=Ea.Object,xa='Arguments'==ka(function(){return arguments}()),Na=Pa?ka: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=Aa(t),$a))?i:xa?ka(e):'Object'==(s=ka(e))&&wa(e.callee)?'Arguments':s},_a=Na,Da=Ta?{}.toString:function(){return'[object '+_a(this)+']'},Ra=Ta,Ia=ii.f,La=gi,Ca=te,Oa=Da,Va=ve('toStringTag'),Ma=function(t,e,i,s){if(t){var r=i?t:t.prototype;Ca(r,Va)||Ia(r,Va,{configurable:!0,value:e}),s&&!Ra&&La(r,'toString',Oa)}},Ba=ga.IteratorPrototype,Fa=Xr,Ua=j,ja=Ma,Ha=$s,qa=function(){return this},Ga=v,Ya=(Ga.String,Ga.TypeError,N);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Ya(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var za=Di,Qa=C,Wa=function(t,e,i,s){var r=e+' Iterator';return t.prototype=Fa(Ba,{next:Ua(+!s,i)}),ja(t,r,!1,!0),Ha[r]=qa,t},Ja=ua,Ka=Ma,Xa=la,Za=$s,to=cr.PROPER,eo=ga.BUGGY_SAFARI_ITERATORS,io=ve('iterator'),so=function(){return this},ro=st,ao=$s,oo=ar;ii.f;var no=function(t,e,i,s,r,a,o){Wa(i,e,s);var n,u,d,l=function(t){if(t===r&&f)return f;if(!eo&&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)}},c=e+' Iterator',h=!1,p=t.prototype,m=p[io]||p['@@iterator']||r&&p[r],f=!eo&&m||l(r),v='Array'==e&&p.entries||m;if(v&&(n=Ja(v.call(new t)))!==Object.prototype&&n.next&&(Ka(n,c,!0,!0),Za[c]=so),to&&'values'==r&&m&&'values'!==m.name&&(h=!0,f=function(){return Qa(m,this)}),r)if(u={values:l('values'),keys:a?f:l('keys'),entries:l('entries')},o)for(d in u)(eo||h||!(d in p))&&Xa(p,d,u[d]);else za({target:e,proto:!0,forced:eo||h},u);return o&&p[io]!==f&&Xa(p,io,f,{name:r}),Za[e]=f,u},uo=oo.set,lo=oo.getterFor('Array Iterator');no(Array,'Array',(function(t,e){uo(this,{type:'Array Iterator',target:ro(t),index:0,kind:e})}),(function(){var t=lo(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'),ao.Arguments=ao.Array;var co=$s,ho=ve('iterator'),po=Array.prototype,mo=Na,fo=Mt,vo=$s,bo=ve('iterator'),So=function(t){if(null!=t)return fo(t,bo)||fo(t,'@@iterator')||vo[mo(t)]},go=C,yo=Ot,To=ui,Eo=Rt,Po=So,wo=v.TypeError,ko=C,$o=ui,Ao=Mt,xo=ei,No=C,_o=ui,Do=Rt,Ro=function(t){return void 0!==t&&(co.Array===t||po[ho]===t)},Io=Mi,Lo=ht,Co=function(t,e){var i=arguments.length<2?Po(t):e;if(yo(i))return To(go(i,t));throw wo(Eo(t)+' is not iterable')},Oo=So,Vo=function(t,e,i){var s,r;$o(t);try{if(!(s=Ao(t,'return'))){if('throw'===e)throw i;return i}s=ko(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return $o(s),i},Mo=v.TypeError,Bo=function(t,e){this.stopped=t,this.result=e},Fo=Bo.prototype,Uo=function(t,e,i){var s,r,a,o,n,u,d,l=i&&i.that,c=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=xo(e,l),f=function(t){return s&&Vo(s,'normal',t),new Bo(!0,t)},v=function(t){return c?(_o(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(h)s=t;else{if(!(r=Oo(t)))throw Mo(Do(t)+' is not iterable');if(Ro(r)){for(a=0,o=Io(t);o>a;a++)if((n=v(t[a]))&&Lo(Fo,n))return n;return new Bo(!1)}s=Co(t,r)}for(u=s.next;!(d=No(u,s)).done;){try{n=v(d.value)}catch(t){Vo(s,'throw',t)}if('object'==typeof n&&n&&Lo(Fo,n))return n}return new Bo(!1)},jo=Ae,Ho=ii,qo=j,Go=Uo,Yo=function(t,e,i){var s=jo(e);s in t?Ho.f(t,s,qo(0,i)):t[s]=i};Di({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Go(t,(function(t,i){Yo(e,t,i)}),{AS_ENTRIES:!0}),e}});var zo=ot.Object.fromEntries,Qo={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},Wo=v,Jo=Na,Ko=gi,Xo=$s,Zo=ve('toStringTag');for(var tn in Qo){var en=Wo[tn],sn=en&&en.prototype;sn&&Jo(sn)!==Zo&&Ko(sn,Zo,tn),Xo[tn]=Xo.Array}var rn=zo,an={};function on(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function nn(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,'value'in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}function un(t,e,i){return e&&nn(t.prototype,e),i&&nn(t,i),t}function dn(t){return(dn=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function ln(t,e){return(ln=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function cn(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function hn(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?cn(t):e}function pn(t){var e=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,s=dn(t);if(e){var r=dn(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return hn(this,i)}}function mn(t,e,i){return(mn='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var s=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=dn(t)););return t}(t,e);if(s){var r=Object.getOwnPropertyDescriptor(s,e);return r.get?r.get.call(i):r.value}})(t,e,i||t)}Object.defineProperty(an,'__esModule',{value:!0});var fn=function(){function t(){on(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return un(t,[{key:'addEventListener',value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:'removeEventListener',value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],s=0,r=i.length;s<r;s++)if(i[s].callback===e)return void i.splice(s,1)}},{key:'dispatchEvent',value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,s=e.length;i<s;i++){var r=e[i];try{r.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}r.options&&r.options.once&&this.removeEventListener(t.type,r.callback)}return!t.defaultPrevented}}}]),t}(),vn=function(t){!function(t,e){if('function'!=typeof e&&null!==e)throw new TypeError('Super expression must either be null or a function');t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&ln(t,e)}(i,fn);var e=pn(i);function i(){var t;return on(this,i),(t=e.call(this)).listeners||fn.call(cn(t)),Object.defineProperty(cn(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(cn(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return un(i,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),mn(dn(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),bn=function(){function t(){on(this,t),Object.defineProperty(this,'signal',{value:new vn,writable:!0,configurable:!0})}return un(t,[{key:'abort',value:function(){var t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event')).initEvent('abort',!1,!1):(t=document.createEventObject()).type='abort':t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}},{key:'toString',value:function(){return'[object AbortController]'}}]),t}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(bn.prototype[Symbol.toStringTag]='AbortController',vn.prototype[Symbol.toStringTag]='AbortSignal');var Sn=an.AbortController=bn;an.AbortSignal=vn;var gn=an.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e=t,i=e.fetch,s=e.Request,r=void 0===s?i.Request:s,a=e.AbortController,o=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,n=void 0!==o&&o;if(!function(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}({fetch:i,Request:r,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:n}))return{fetch:i,Request:u};var u=r;(u&&!u.prototype.hasOwnProperty('signal')||n)&&((u=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var s=new r(t,e);return i&&Object.defineProperty(s,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),s}).prototype=r.prototype);var d=i;return{fetch:function(t,e){var i=u&&u.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var s;try{s=new DOMException('Aborted','AbortError')}catch(t){(s=new Error('Aborted')).name='AbortError'}if(i.aborted)return Promise.reject(s);var r=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,d(t,e)])}return d(t,e)},Request:u}},yn=v.Promise,Tn=la,En=ct,Pn=ii,wn=R,kn=ve('species'),$n=ht,An=v.TypeError,xn=ve('iterator'),Nn=!1;try{var _n=0,Dn={next:function(){return{done:!!_n++}},return:function(){Nn=!0}};Dn[xn]=function(){return this},Array.from(Dn,(function(){throw 2}))}catch(t){}var Rn=N,In=b,Ln=_,Cn=Na,On=Is,Vn=function(){},Mn=[],Bn=ct('Reflect','construct'),Fn=/^\s*(?:class|function)\b/,Un=Rn(Fn.exec),jn=!Fn.exec(Vn),Hn=function(t){if(!Ln(t))return!1;try{return Bn(Vn,Mn,t),!0}catch(t){return!1}},qn=function(t){if(!Ln(t))return!1;switch(Cn(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return jn||!!Un(Fn,On(t))}catch(t){return!0}};qn.sham=!0;var Gn,Yn,zn,Qn,Wn=!Bn||In((function(){var t;return Hn(Hn.call)||!Hn(Object)||!Hn((function(){t=!0}))||t}))?qn:Hn,Jn=Rt,Kn=v.TypeError,Xn=ui,Zn=function(t){if(Wn(t))return t;throw Kn(Jn(t)+' is not a constructor')},tu=ve('species'),eu=function(t,e){var i,s=Xn(t).constructor;return void 0===s||null==(i=Xn(s)[tu])?e:Zn(i)},iu=N([].slice),su=v.TypeError,ru=/(?:ipad|iphone|ipod).*applewebkit/i.test(pt),au='process'==Y(v.process),ou=v,nu=P,uu=ei,du=_,lu=te,cu=b,hu=Vr,pu=iu,mu=De,fu=function(t,e){if(t<e)throw su('Not enough arguments');return t},vu=ru,bu=au,Su=ou.setImmediate,gu=ou.clearImmediate,yu=ou.process,Tu=ou.Dispatch,Eu=ou.Function,Pu=ou.MessageChannel,wu=ou.String,ku=0,$u={};try{Gn=ou.location}catch(t){}var Au=function(t){if(lu($u,t)){var e=$u[t];delete $u[t],e()}},xu=function(t){return function(){Au(t)}},Nu=function(t){Au(t.data)},_u=function(t){ou.postMessage(wu(t),Gn.protocol+'//'+Gn.host)};Su&&gu||(Su=function(t){fu(arguments.length,1);var e=du(t)?t:Eu(t),i=pu(arguments,1);return $u[++ku]=function(){nu(e,void 0,i)},Yn(ku),ku},gu=function(t){delete $u[t]},bu?Yn=function(t){yu.nextTick(xu(t))}:Tu&&Tu.now?Yn=function(t){Tu.now(xu(t))}:Pu&&!vu?(Qn=(zn=new Pu).port2,zn.port1.onmessage=Nu,Yn=uu(Qn.postMessage,Qn)):ou.addEventListener&&du(ou.postMessage)&&!ou.importScripts&&Gn&&'file:'!==Gn.protocol&&!cu(_u)?(Yn=_u,ou.addEventListener('message',Nu,!1)):Yn='onreadystatechange'in mu('script')?function(t){hu.appendChild(mu('script')).onreadystatechange=function(){hu.removeChild(this),Au(t)}}:function(t){setTimeout(xu(t),0)});var Du,Ru,Iu,Lu,Cu,Ou,Vu,Mu,Bu={set:Su,clear:gu},Fu=v,Uu=/ipad|iphone|ipod/i.test(pt)&&void 0!==Fu.Pebble,ju=/web0s(?!.*chrome)/i.test(pt),Hu=v,qu=ei,Gu=D.f,Yu=Bu.set,zu=ru,Qu=Uu,Wu=ju,Ju=au,Ku=Hu.MutationObserver||Hu.WebKitMutationObserver,Xu=Hu.document,Zu=Hu.process,td=Hu.Promise,ed=Gu(Hu,'queueMicrotask'),id=ed&&ed.value;id||(Du=function(){var t,e;for(Ju&&(t=Zu.domain)&&t.exit();Ru;){e=Ru.fn,Ru=Ru.next;try{e()}catch(t){throw Ru?Lu():Iu=void 0,t}}Iu=void 0,t&&t.enter()},zu||Ju||Wu||!Ku||!Xu?!Qu&&td&&td.resolve?((Vu=td.resolve(void 0)).constructor=td,Mu=qu(Vu.then,Vu),Lu=function(){Mu(Du)}):Ju?Lu=function(){Zu.nextTick(Du)}:(Yu=qu(Yu,Hu),Lu=function(){Yu(Du)}):(Cu=!0,Ou=Xu.createTextNode(''),new Ku(Du).observe(Ou,{characterData:!0}),Lu=function(){Ou.data=Cu=!Cu}));var sd=id||function(t){var e={fn:t,next:void 0};Iu&&(Iu.next=e),Ru||(Ru=e,Lu()),Iu=e},rd={},ad=Ot,od=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw TypeError('Bad Promise constructor');e=t,i=s})),this.resolve=ad(e),this.reject=ad(i)};rd.f=function(t){return new od(t)};var nd=ui,ud=at,dd=rd,ld=function(t,e){if(nd(t),ud(e)&&e.constructor===t)return e;var i=dd.f(t);return(0,i.resolve)(e),i.promise},cd=v,hd=function(){this.head=null,this.tail=null};hd.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}};var pd,md,fd,vd='object'==typeof window,bd=Di,Sd=v,gd=ct,yd=C,Td=yn,Ed=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Tn(t,s,e[s],i);return t},Pd=Ma,wd=function(t){var e=En(t),i=Pn.f;wn&&e&&!e[kn]&&i(e,kn,{configurable:!0,get:function(){return this}})},kd=Ot,$d=_,Ad=at,xd=function(t,e){if($n(e,t))return t;throw An('Incorrect invocation')},Nd=Is,_d=Uo,Dd=function(t,e){if(!e&&!Nn)return!1;var i=!1;try{var s={};s[xn]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},Rd=eu,Id=Bu.set,Ld=sd,Cd=ld,Od=function(t,e){var i=cd.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},Vd=rd,Md=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Bd=hd,Fd=ar,Ud=Ke,jd=vd,Hd=au,qd=yt,Gd=ve('species'),Yd='Promise',zd=Fd.getterFor(Yd),Qd=Fd.set,Wd=Fd.getterFor(Yd),Jd=Td&&Td.prototype,Kd=Td,Xd=Jd,Zd=Sd.TypeError,tl=Sd.document,el=Sd.process,il=Vd.f,sl=il,rl=!!(tl&&tl.createEvent&&Sd.dispatchEvent),al=$d(Sd.PromiseRejectionEvent),ol=Ud(Yd,(function(){var t=Nd(Kd),e=t!==String(Kd);if(!e&&66===qd)return!0;if(!Xd.finally)return!0;if(qd>=51&&/native code/.test(t))return!1;var i=new Kd((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[Gd]=s,!(i.then((function(){}))instanceof s)||!e&&jd&&!al})),nl=ol||!Dd((function(t){Kd.all(t).catch((function(){}))})),ul=function(t){var e;return!(!Ad(t)||!$d(e=t.then))&&e},dl=function(t,e){var i,s,r,a=e.value,o=1==e.state,n=o?t.ok:t.fail,u=t.resolve,d=t.reject,l=t.domain;try{n?(o||(2===e.rejection&&ml(e),e.rejection=1),!0===n?i=a:(l&&l.enter(),i=n(a),l&&(l.exit(),r=!0)),i===t.promise?d(Zd('Promise-chain cycle')):(s=ul(i))?yd(s,i,u,d):u(i)):d(a)}catch(t){l&&!r&&l.exit(),d(t)}},ll=function(t,e){t.notified||(t.notified=!0,Ld((function(){for(var i,s=t.reactions;i=s.get();)dl(i,t);t.notified=!1,e&&!t.rejection&&hl(t)})))},cl=function(t,e,i){var s,r;rl?((s=tl.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),Sd.dispatchEvent(s)):s={promise:e,reason:i},!al&&(r=Sd['on'+t])?r(s):'unhandledrejection'===t&&Od('Unhandled promise rejection',i)},hl=function(t){yd(Id,Sd,(function(){var e,i=t.facade,s=t.value;if(pl(t)&&(e=Md((function(){Hd?el.emit('unhandledRejection',s,i):cl('unhandledrejection',i,s)})),t.rejection=Hd||pl(t)?2:1,e.error))throw e.value}))},pl=function(t){return 1!==t.rejection&&!t.parent},ml=function(t){yd(Id,Sd,(function(){var e=t.facade;Hd?el.emit('rejectionHandled',e):cl('rejectionhandled',e,t.value)}))},fl=function(t,e,i){return function(s){t(e,s,i)}},vl=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,ll(t,!0))},bl=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw Zd('Promise can\'t be resolved itself');var s=ul(e);s?Ld((function(){var i={done:!1};try{yd(s,e,fl(bl,i,t),fl(vl,i,t))}catch(e){vl(i,e,t)}})):(t.value=e,t.state=1,ll(t,!1))}catch(e){vl({done:!1},e,t)}}};ol&&(Xd=(Kd=function(t){xd(this,Xd),kd(t),yd(pd,this);var e=zd(this);try{t(fl(bl,e),fl(vl,e))}catch(t){vl(e,t)}}).prototype,(pd=function(t){Qd(this,{type:Yd,done:!1,notified:!1,parent:!1,reactions:new Bd,rejection:!1,state:0,value:void 0})}).prototype=Ed(Xd,{then:function(t,e){var i=Wd(this),s=il(Rd(this,Kd));return i.parent=!0,s.ok=!$d(t)||t,s.fail=$d(e)&&e,s.domain=Hd?el.domain:void 0,0==i.state?i.reactions.add(s):Ld((function(){dl(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),md=function(){var t=new pd,e=zd(t);this.promise=t,this.resolve=fl(bl,e),this.reject=fl(vl,e)},Vd.f=il=function(t){return t===Kd||t===fd?new md(t):sl(t)}),bd({global:!0,wrap:!0,forced:ol},{Promise:Kd}),Pd(Kd,Yd,!1,!0),wd(Yd),fd=gd(Yd),bd({target:Yd,stat:!0,forced:ol},{reject:function(t){var e=il(this);return yd(e.reject,void 0,t),e.promise}}),bd({target:Yd,stat:!0,forced:true},{resolve:function(t){return Cd(this===fd?Kd:this,t)}}),bd({target:Yd,stat:!0,forced:nl},{all:function(t){var e=this,i=il(e),s=i.resolve,r=i.reject,a=Md((function(){var i=kd(e.resolve),a=[],o=0,n=1;_d(t,(function(t){var u=o++,d=!1;n++,yd(i,e,t).then((function(t){d||(d=!0,a[u]=t,--n||s(a))}),r)})),--n||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=il(e),s=i.reject,r=Md((function(){var r=kd(e.resolve);_d(t,(function(t){yd(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Sl=yn,gl=ct,yl=_,Tl=eu,El=ld;Di({target:'Promise',proto:!0,real:!0,forced:!!Sl&&b((function(){Sl.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=Tl(this,gl('Promise')),i=yl(t);return this.then(i?function(i){return El(e,t()).then((function(){return i}))}:t,i?function(i){return El(e,t()).then((function(){throw i}))}:t)}});var Pl,wl=Yi('Promise','finally'),kl=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Pl||(Pl={}));class $l{constructor({throughputEstimator:e}={}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Sn,this.subscription=new t.Subscription,this.fetchRepresentation=(t,e,i=0)=>p(this,void 0,void 0,(function*(){const{from:s,to:r}=t.initRange;let a,o,n=s,u=r,d=!1;t.indexRange&&(a=t.indexRange.from,o=t.indexRange.to,d=r+1===a,d&&(n=Math.min(a,s),u=Math.max(o,r))),n=Math.min(n,0),u+=i;const l=yield this.fetchRange(t.url,n,u,{method:Pl.PARAM});if(!l)return null;const c=new DataView(l,s-n,r-n);if(!e.validateData(c))throw new Error('Invalid media file');const h=e.parseInit(c);let p;if(d&&void 0!==a&&void 0!==o)p=new DataView(l,a-n,o-a);else{const i=e.getIndexRange(h);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:Pl.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,h);return{dataView:new DataView(l),segments:m}})),this.throughputEstimator=e}onHeadersReceived(t){const{type:e,reused:i}=kl(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest(t){return p(this,void 0,void 0,(function*(){const e=yield gn(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Al);return e?(this.onHeadersReceived(e.headers),e.text()):null}))}fetchRange(e,i,s,{method:r=Pl.HEADER,onProgress:a,signal:o}={}){var n,u,d;return p(this,void 0,void 0,(function*(){let l=e;const c=new Headers;switch(r){case Pl.HEADER:c.append('Range',`${i}-${s}`);break;case Pl.PARAM:{const t=new URL(l,location.href);t.searchParams.append('bytes',`${i}-${s}`),l=t.toString();break}default:t.assertNever(r)}let h=this.abortAllController.signal;if(o){const e=new Sn;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&e.abort(),h=e.signal}const m=t.now(),f=yield gn(fetch).fetch(l,{headers:c,signal:h}).catch(Al);if(null===(n=this.throughputEstimator)||void 0===n||n.addRawRtt(t.now()-m),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const[v,b]=f.body.tee(),S=v.getReader();null===(u=this.throughputEstimator)||void 0===u||u.trackStream(b);const g=parseInt(null!==(d=f.headers.get('Content-Length'))&&void 0!==d?d:'',10);let y=0;const T=new ArrayBuffer(g),E=new Uint8Array(T),P=new DataView(T);let w=!1;const k=t=>{w=!0,Al(t)},$=({done:e,value:i})=>p(this,void 0,void 0,(function*(){0===y&&this.lastRequestFirstBytes$.next(t.now()-m),e?null==a||a(P,y):i&&(E.set(i,y),y+=i.byteLength,null==a||a(P,y),yield null==S?void 0:S.read().then($,k))}));return yield null==S?void 0:S.read().then($,k),w?null:T}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Al=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var xl,Nl;!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.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'}(xl||(xl={})),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'}(Nl||(Nl={}));const _l={[xl.EBML]:{type:Nl.Master},[xl.EBMLVersion]:{type:Nl.UnsignedInteger},[xl.EBMLReadVersion]:{type:Nl.UnsignedInteger},[xl.EBMLMaxIDLength]:{type:Nl.UnsignedInteger},[xl.EBMLMaxSizeLength]:{type:Nl.UnsignedInteger},[xl.DocType]:{type:Nl.String},[xl.DocTypeVersion]:{type:Nl.UnsignedInteger},[xl.DocTypeReadVersion]:{type:Nl.UnsignedInteger},[xl.Void]:{type:Nl.Binary},[xl.Segment]:{type:Nl.Master},[xl.SeekHead]:{type:Nl.Master},[xl.Seek]:{type:Nl.Master},[xl.SeekID]:{type:Nl.Binary},[xl.SeekPosition]:{type:Nl.UnsignedInteger},[xl.Info]:{type:Nl.Master},[xl.TimestampScale]:{type:Nl.UnsignedInteger},[xl.Duration]:{type:Nl.Float},[xl.Tracks]:{type:Nl.Master},[xl.Chapters]:{type:Nl.Master},[xl.Cluster]:{type:Nl.Master},[xl.Attachments]:{type:Nl.Master},[xl.Tags]:{type:Nl.Master},[xl.Cues]:{type:Nl.Master},[xl.CuePoint]:{type:Nl.Master},[xl.CueTime]:{type:Nl.UnsignedInteger},[xl.CueTrackPositions]:{type:Nl.Master},[xl.CueTrack]:{type:Nl.UnsignedInteger},[xl.CueClusterPosition]:{type:Nl.UnsignedInteger},[xl.CueRelativePosition]:{type:Nl.UnsignedInteger},[xl.CueDuration]:{type:Nl.UnsignedInteger},[xl.CueBlockNumber]:{type:Nl.UnsignedInteger},[xl.CueCodecState]:{type:Nl.UnsignedInteger},[xl.CueReference]:{type:Nl.Master},[xl.CueRefTime]:{type:Nl.UnsignedInteger}},Dl=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=Rl(t,i),r=s in _l,a=r?_l[s].type:Nl.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 u=new DataView(t.buffer,t.byteOffset+i+1,n-1),d=((o&255>>n)<<8*(n-1))+Rl(u),l=i+n;let c;return c=l+d>t.byteLength?new DataView(t.buffer,t.byteOffset+l):new DataView(t.buffer,t.byteOffset+l,d),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,value:c,valueSize:d}},Rl=(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 Nl.SignedInteger:return e.getInt8(0);case Nl.UnsignedInteger:return Rl(e);case Nl.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Nl.String:return new TextDecoder('ascii').decode(e);case Nl.UTF8:return new TextDecoder('utf-8').decode(e);case Nl.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Nl.Master:case Nl.Binary:return e;default:t.assertNever(i)}},Ll=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Dl(s);if(!e(r))return;r.type===Nl.Master&&Ll(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Cl=[xl.Info,xl.SeekHead,xl.Tracks,xl.Chapters,xl.Cluster,xl.Cues,xl.Attachments,xl.Tags],Ol={validateData:t=>{if(t.getUint32(0)!==xl.EBML)return!1;let e,i,s;const r=Dl(t);return Ll(r.value,(({tag:t,type:r,value:a})=>(t===xl.EBMLReadVersion?e=Il(a,r):t===xl.DocType?i=Il(a,r):t===xl.DocTypeReadVersion&&(s=Il(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,r,a,o,n,u=!1,d=!1,l=!1;return Ll(e,(({tag:t,type:e,value:c,valueSize:h})=>{if(t===xl.SeekID){const t=Il(c,e);n=Rl(t)}else t!==xl.SeekPosition&&(n=void 0);return t===xl.Segment?(i=c.byteOffset,s=c.byteOffset+h):t===xl.Info?u=!0:t===xl.SeekHead?d=!0:t===xl.TimestampScale?r=Il(c,e):t===xl.Duration?a=Il(c,e):t===xl.SeekPosition&&n===xl.Cues?o=Il(c,e):u&&d&&Cl.includes(t)&&(l=!0),!l})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(a,'Failed to parse webm Segment duration'),r=null!=r?r:1e6,{segmentStart:Math.round(i/1e9*r*1e3),segmentEnd:Math.round(s/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*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,r=!1;const a=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),o=[];let n;return Ll(e,(({tag:t,type:e,value:i})=>{switch(t){case xl.Cues:s=!0;break;case xl.CuePoint:n&&a(n)&&o.push(n),n={};break;case xl.CueTime:n&&(n.time=Il(i,e));break;case xl.CueTrackPositions:break;case xl.CueClusterPosition:n&&(n.position=Il(i,e));break;default:s&&Cl.includes(t)&&(r=!0)}return!(s&&r)})),n&&a(n)&&o.push(n),o.map(((t,e)=>{const{time:s,position:r}=t,a=o[e+1];return{status:qi.NONE,time:{from:s,to:a?a.time:i.segmentDuration},byte:{from:i.segmentStart+r,to:a?i.segmentStart+a.position-1:i.segmentEnd-1}}}))}},Vl=new TextDecoder('ascii'),Ml={validateData:t=>'ftyp'===Vl.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=(t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=Vl.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e+1;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}})(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),o=r(),n=r(),u=255&r();let d=o/a*1e3,l=t.byteOffset+t.byteLength+n+1;for(let t=0;t<u;t++){const t=r(),e=t>>>31,s=t<<1>>>1,o=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const n=o/a*1e3;i.push({status:qi.NONE,time:{from:d,to:d+n},byte:{from:l,to:l+s-1}}),d+=n,l+=s}return i}};class Bl{constructor(e,i,s,r,{fetcher:a,tuning:o}){switch(this.ended$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.abortController=new Sn,this.allInitsLoaded=!1,this.fetcher=a,this.tuning=o,this.container=s,s){case Gi.MP4:this.containerParser=Ml;break;case Gi.WEBM:this.containerParser=Ol;break;default:t.assertNever(s)}this.initData=new Map,this.segments=new Map,this.representations=new Map(r.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith(e){return p(this,void 0,void 0,(function*(){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`);const s=Math.ceil(1e3*i.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateEnd').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejecte by browser',thrown:t})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const r=yield this.fetcher.fetchRepresentation(i,this.containerParser,s).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!r)return!1;const{dataView:a,segments:o}=r,n=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength-s);this.initData.set(e,n);const u=o.filter((t=>t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength)),d=zi(u,-1),l=new DataView(a.buffer,a.byteOffset,u.length&&d?Math.min(d.byte.to-a.byteOffset+1,a.byteLength):a.byteLength-s);return yield this.appendDataToBuffer(l),this.segments.set(e,o.map((t=>Object.assign(Object.assign({},t),{status:t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength?qi.FED:qi.NONE})))),this.maintain(0),!0}))}switchTo(e){var i;return p(this,void 0,void 0,(function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=e,!this.initData.has(e))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const i=this.representations.get(e);t.assertNonNullable(i);const s=yield this.fetcher.fetchRepresentation(i,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:r,segments:a}=s,o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);this.initData.set(e,o),this.segments.set(e,a)}const s=this.initData.get(e);t.assertNonNullable(s,`No init buffer for ${e}`),t.assertNonNullable(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abortController.abort(),this.abortController=new Sn,this.abortBuffer(),yield this.appendDataToBuffer(s,this.abortController.signal),t.isNonNullable(this.playingRepresentationId)&&(null===(i=this.segments.get(this.playingRepresentationId))||void 0===i||i.forEach((t=>{t.status===qi.FED&&(t.status=qi.NONE)})))}))}maintain(e){return p(this,void 0,void 0,(function*(){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer)||this.ended$.getValue())return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);t.assertNonNullable(i),t.assertNonNullable(s);const r=s.find((t=>e>=t.time.from&&e<t.time.to));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=Es(this.sourceBuffer.buffered,e);a=e+Math.min(t,this.tuning.representationSwitchForwardBufferGap)}const o=this.selectForwardBufferSegments(s,a);o.length&&(yield this.loadSegments(o,i)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&r&&r.status===qi.FED&&!o.length&&Es(this.sourceBuffer.buffered,e)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const n=zi(s,-1);n&&r===n&&n.status===qi.FED&&this.ended$.next(!0)}))}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.abortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===qi.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.forwardBufferTarget));if(-1===i)return[];let s=0;const r=[];for(let e=i;e<t.length&&s<=this.tuning.segmentRequestSize;e++){const i=t[e];if(s+=i.byte.to+1-i.byte.from,i.status===qi.NONE)r.push(i);else if([qi.DOWNLOADING,qi.DOWNLOADED,qi.FED].includes(i.status))break}return r}loadSegments(t,e){return p(this,void 0,void 0,(function*(){if(!t.length)return;const i=zi(t,0).byte.from,s=zi(t,-1).byte.to;for(const e of t)e.status=qi.DOWNLOADING;const{signal:r}=this.abortController,a=(t,i)=>{t.status=qi.DOWNLOADED,this.appendDataToBuffer(i,r).then((i=>{!i||r.aborted?t.status=qi.NONE:(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=qi.FED)}))},o=(e,s)=>{for(const r of t)r.status===qi.DOWNLOADING&&r.byte.from-i>=0&&r.byte.to+1-i<=s&&a(r,new DataView(e.buffer,e.byteOffset+r.byte.from-i,r.byte.to+1-r.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((()=>p(this,void 0,void 0,(function*(){if(r.aborted){for(const e of t)e.status===qi.DOWNLOADING&&(e.status=qi.NONE);return}const n=yield this.fetcher.fetchRange(e.url,i,s,{method:Pl.PARAM,onProgress:o,signal:r}),u=zi(t,-1),d=zi(this.segments.get(e.id),-1);if(!n)for(const e of t)e.status===qi.DOWNLOADING&&(e.status=qi.NONE);n&&!r.aborted&&u&&d&&u.status===qi.DOWNLOADING&&u===d&&a(u,new DataView(n,u.byte.from-i))})))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}))}loadAllInits(){return p(this,void 0,void 0,(function*(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=wl(Promise.all(Array.from(this.representations.entries()).map((([t,e])=>this.initData.has(t)?Promise.resolve():this.fetcher.fetchRepresentation(e,this.containerParser).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,r),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})),(()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}))}appendDataToBuffer(e,i){return p(this,void 0,void 0,(function*(){if(t.assertNonNullable(this.sourceBuffer),i&&i.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return yield Bl.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(e,i);try{this.sourceBuffer.appendBuffer(e)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),!1}return yield Bl.waitForBufferUpdate(this.sourceBuffer),!0}))}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(t){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:t})}}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=this.segments.get(this.playingRepresentationId);t.assertNonNullable(e);const i=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),r=1e3*(s%1>.9?Math.round(s):s);i.push({from:e,to:r})}for(const t of e){const e=i.some((e=>e.from<=t.time.from&&e.to>=t.time.to));t.status!==qi.FED||e||(t.status=qi.NONE)}}static waitForBufferUpdate(t){return p(this,void 0,void 0,(function*(){return new Promise((e=>t?t.addEventListener('update',(()=>e())):e()))}))}}const Fl=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},Ul=['timeupdate','progress','play','seeked','stalled'];var jl,Hl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(jl||(jl={}));class ql{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new ks(jl.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.tick=()=>{var t,e;if(!this.element)return;const i=1e3*this.element.currentTime;null===(t=this.videoBufferManager)||void 0===t||t.maintain(i),null===(e=this.audioBufferManager)||void 0===e||e.maintain(i)},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new $l({throughputEstimator:this.throughputEstimator})}initManifest(e,i){return p(this,void 0,void 0,(function*(){this.element=e,this.subscription.add(t.fromEvent(e,'waiting').subscribe((()=>{e.duration-e.currentTime<this.tuning.endGapTolerance/1e3&&this.forceEnded$.next()}),(t=>this.error$.next({id:'ForceEnd',message:'Error when forcing stream end',thrown:t})))),this.state$.startTransitionTo(jl.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i);let r;try{r=((t,e)=>{var i,s,r,a,o,n,u,d,l,c,h,p,m,f,v,b,S,g,y,T,E,P,w,k;const $={video:[],audio:[],text:[]},A=(new DOMParser).parseFromString(t,'application/xml').children[0],x=A.getElementsByTagName('Period')[0].children;let N=0;const _=null!==(s=null===(i=A.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==s?s:[],D=_.includes(Hi.WEBM_AS_IN_FFMPEG)||_.includes(Hi.WEBM_AS_IN_SPEC)?Gi.WEBM:Gi.MP4;for(const t of x){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),A=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==i?void 0:i.split('/')[0],x=null!==(o=null===(a=t.getAttribute('profiles'))||void 0===a?void 0:a.split(','))&&void 0!==o?o:[],D=t.querySelectorAll('Representation');for(const r of D){const a=null!==(n=r.getAttribute('mimeType'))&&void 0!==n?n:i,o=null!==(d=null!==(u=r.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==d?d:'',D=null!==(c=null!==(l=r.getAttribute('contentType'))&&void 0!==l?l:null==a?void 0:a.split('/')[0])&&void 0!==c?c:A,R=null!==(p=null===(h=t.getAttribute('profiles'))||void 0===h?void 0:h.split(','))&&void 0!==p?p:[],I=parseInt(null!==(m=r.getAttribute('width'))&&void 0!==m?m:'',10),L=parseInt(null!==(f=r.getAttribute('height'))&&void 0!==f?f:'',10),C=parseInt(null!==(v=r.getAttribute('bandwidth'))&&void 0!==v?v:'',10)/1e3,O=null!==(b=r.getAttribute('frameRate'))&&void 0!==b?b:'',V=null!==(S=r.getAttribute('quality'))&&void 0!==S?S:void 0,M=O?Fl(O):void 0,B=`${null!==(g=r.getAttribute('id'))&&void 0!==g?g:(N++).toString(10)}@${'video'===D?`${L}p`:'audio'===D?`${C}Kbps`:o}`,F=null!==(E=null===(T=null===(y=r.querySelector('BaseURL'))||void 0===y?void 0:y.textContent)||void 0===T?void 0:T.trim())&&void 0!==E?E:'',U=new URL(F,e).toString(),j=[..._,...x,...R],H=null!==(w=null===(P=r.querySelector('SegmentBase Initialization'))||void 0===P?void 0:P.getAttribute('range'))&&void 0!==w?w:'',[q,G]=H.split('-').map((t=>parseInt(t,10))),Y={from:q,to:G},z=null===(k=r.querySelector('SegmentBase'))||void 0===k?void 0:k.getAttribute('indexRange'),[Q,W]=z?z.split('-').map((t=>parseInt(t,10))):[],J=z?{from:Q,to:W}:void 0;if(!D||!a)continue;const K={video:ji.VIDEO,audio:ji.AUDIO,text:ji.TEXT}[D];K&&$[K].push({id:B,kind:K,profiles:j,initRange:Y,indexRange:J,bitrate:C,mime:a,codecs:o,width:I,height:L,fps:M,quality:V,url:U})}}return{container:D,representations:$}})(null!=s?s:'',i)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}t.assertNonNullable(r);const a=({mime:t,codecs:i})=>{var s,r,a;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${t}; codecs="${i}"`)))};return this.manifest=Object.assign(Object.assign({},r),{representations:rn(Object.entries(r.representations).map((([t,e])=>[t,e.filter(a)])))}),this.manifest.representations.video.length?this.state$.setState(jl.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}))}initRepresentations(e,i){return p(this,void 0,void 0,(function*(){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(jl.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash};this.videoBufferManager=new Bl(ji.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.audioBufferManager=new Bl(ji.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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$)),this.subscription.add(t.merge(this.forceEnded$,t.combine({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(t.filter((t=>Object.values(t).every((t=>!0===t)))))).subscribe((()=>{var t,e;if('open'===(null===(t=this.source)||void 0===t?void 0:t.readyState))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(t.merge(this.videoBufferManager.error$,this.audioBufferManager.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)})));(yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)])).some((t=>!t))||(this.state$.setState(jl.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...Ul.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),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.tick())}))}switchRepresentation(e,i){return p(this,void 0,void 0,(function*(){const s={[ji.VIDEO]:this.videoBufferManager,[ji.AUDIO]:this.audioBufferManager,[ji.TEXT]:null}[e];return t.assertNonNullable(s),s.switchTo(i)}))}seek(e){t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),t.assertNonNullable(this.audioBufferManager),this.videoBufferManager.maintain(e),this.audioBufferManager.maintain(e),this.element.currentTime=e/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.state$.setState(jl.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Hl||(Hl={}));const Gl=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var o;const n=null!==(o=a?ns(a):void 0)&&void 0!==o?o:ps({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:r}},Yl=(t,e,i)=>{var s;const r=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=zi(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:zi(t,-1)};class zl{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks(Hl.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Zi,this.videoTracks=[],this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const a=null==r?void 0:r.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(a)&&e!==Hl.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a),i!==exports.PlaybackState.STOPPED){if(e===Hl.STOPPED)return this.videoState.startTransitionTo(Hl.READY),void this.prepare();switch(e){case Hl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Hl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Hl.PLAYING),this.playIfAllowed()));case Hl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Hl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Hl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Hl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Hl.STOPPED&&(this.videoState.startTransitionTo(Hl.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(Hl.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=ts(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Ps(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ql({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=as(this.video),r=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.firstFrame$,e.firstFrameEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ji(this.video,i.isLooped,r)),this.subscription.add(Ki(this.video,i.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),a(ws(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(Hl.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),r)).add(s.pause$.subscribe((()=>{this.videoState.setState(Hl.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),r)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===Hl.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===jl.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Hl.READY)}))),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 e,s,r;const a=this.player.state$.getState(),o=this.player.state$.getTransition();if(a===jl.NONE||!this.videoTracks.length)return;const n=a===jl.MANIFEST_LOADED&&!o,u=i.autoVideoTrackSwitching.getState(),d=i.videoTrack.getState(),l=null===(e=this.videoTracks.find((({track:{id:t}})=>t===d)))||void 0===e?void 0:e.track;i.autoVideoTrackSwitching.getTransition()&&i.autoVideoTrackSwitching.setState(u);const c=Es(this.video.buffered,1e3*this.video.currentTime),h=Math.min(c/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),p=Ts(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(),forwardBufferHealth:h}),m=u?null!=p?p:l:null!=l?l:p;if(n){const e=m&&(null===(s=this.videoTracks.find((({track:t})=>t===m)))||void 0===s?void 0:s.representation);t.assertNonNullable(e);const i=Yl(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),e);t.assertNonNullable(i),this.player.initRepresentations(e.id,i.id)}else{const t=m&&(null===(r=this.videoTracks.find((({track:t})=>t===m)))||void 0===r?void 0:r.representation);if(t){const e=Yl(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(ji.VIDEO,t.id),e&&this.player.switchRepresentation(ji.AUDIO,e.id)}}}),r)),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$,r)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}prepare(){return p(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=Gl(e);t&&this.videoTracks.push({track:t,representation:e})}this.audioRepresentations=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t){this.params.output.willSeekEvent$.next(),this.player.seek(1e3*t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(Hl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Ql;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Ql||(Ql={}));var Wl=(e,i=0,s=Ql.OFFSET_P)=>{switch(s){case Ql.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case Ql.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};var Jl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Jl||(Jl={}));class Kl{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new ks(Jl.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(a)};`}),s===exports.PlaybackState.STOPPED)return void(e!==Jl.STOPPED&&(this.videoState.startTransitionTo(Jl.STOPPED),this.stop()));if(i)return;const o=null==a?void 0:a.to;if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&e!==Jl.STOPPED)this.seek(o);else switch(s){case exports.PlaybackState.PLAYING:switch(e){case Jl.PLAYING:break;case Jl.PAUSED:case Jl.READY:this.videoState.startTransitionTo(Jl.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Jl.STOPPED:this.videoState.startTransitionTo(Jl.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Jl.PLAYING:this.videoState.startTransitionTo(Jl.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Jl.PAUSED:break;case Jl.READY:this.videoState.startTransitionTo(Jl.PAUSED),this.videoState.setState(Jl.PAUSED);break;case Jl.STOPPED:this.videoState.startTransitionTo(Jl.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}},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_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM: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((e=>{this.logRemoteEvent(e);const r=e.value;this.params.output.position$.next(r);const a=this.params.desiredState.seekPosition.getTransition();(t.isNonNullable(a)&&t.isNullable(a.to)||Math.abs(r-s)>5)&&i.next(r),s=r}))),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,r=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(r!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),us(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.seekPosition.stateChangeStarted$,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(Jl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Jl.PLAYING),us(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.seekPosition.setState(void 0)}}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)!==Jl.PAUSED&&t!==Jl.PLAYING||(this.videoState.setState(Jl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Jl.PLAYING&&t!==Jl.PAUSED||(this.videoState.setState(Jl.PLAYING),us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Jl.READY&&this.videoState.setState(Jl.READY)}handleRemoteStop(){this.videoState.getState()!==Jl.STOPPED&&this.videoState.setState(Jl.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}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 r,a,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:cs(t,e)?1:-1))[0];t.assertNonNullable(n);const u=i[n];t.assertNonNullable(u),r=u,a='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),r=i.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),r=Wl(i.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return t.assertNever(e)}const n=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:r,a);n.contentUrl=r,n.streamType=o,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return t.isNonNullable(u)&&(n.metadata.title=u),t.isNonNullable(d)&&(n.metadata.subtitle=d),n}createLoadRequest(t){var e;const i=new chrome.cast.media.LoadRequest(t);i.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return i.currentTime=s?this.params.output.isLive$.getValue()?0:null!==(e=s.to)&&void 0!==e?e:0:0,i}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)'))))}));wl(Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});const t=this.params.desiredState.seekPosition;t.getTransition()&&t.setState(void 0),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})),(()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}var Xl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Xl||(Xl={}));class Zl{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks(Xl.STOPPED),this.trackUrls={},this.textTracksManager=new Zi,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!==Xl.STOPPED&&(this.videoState.startTransitionTo(Xl.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(Xl.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(e===Xl.STOPPED)return this.videoState.startTransitionTo(Xl.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=null==a?void 0:a.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&this.seek(o),e){case Xl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Xl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Xl.PLAYING),this.playIfAllowed()));case Xl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Xl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Xl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Xl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=ts(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.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Xl.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Xl.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===Xl.READY&&this.videoState.setState(Xl.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()===Xl.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.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.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');const{url:r}=this.trackUrls[s];t.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.video.setAttribute('src',r),this.video.load(),this.params.output.hostname$.next(Ps(r))}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(Xl.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}class tc{constructor(t,e=[],i,s,r,a){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=r,this._errorCb=a,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,r,a,o,n,u,d;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===(r=this._xhr)||void 0===r?void 0:r.status}`,`XHR response code ${null===(a=this._xhr)||void 0===a?void 0:a.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=rn(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===(u=this._progressCb)||void 0===u||u.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.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 ec{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,r,a,o){this.abort((()=>{let n=0;const u=Date.now();let d=0,l=0,c=0;const h=t=>{s(ec._str2ua(t.substr(n))),n=t.length};this._lastXhr=new tc(t.baseURL+'&bytes='+e+'-'+i,t.failoverHosts,(t=>{this._lastXhr=void 0,h(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-n>o&&h(t),0===l)return void(l=Date.now());c=t.length-d;const e=Date.now()-l;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,d=t.length,l=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((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=ec._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 ic{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){new tc(t,e,(i=>{this.attachManifest(i,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(t))}),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,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],o=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,n,u,d,l,c,h,p,m,f,v,b,S,g,y,T,E,P,w;const k=t.getElementsByTagName('SegmentBase')[0],$=k&&r(k,'indexRange').split('-'),A=k&&k.getElementsByTagName('Initialization')[0],x=A&&r(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(l=null===(d=null===(u=null===(n=t.getElementsByTagName('BaseURL'))||void 0===n?void 0:n[0])||void 0===u?void 0:u.childNodes)||void 0===d?void 0:d[0])||void 0===l?void 0:l.data),h=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&o.push({id:r,url:a,language:h})}return}const N=Number(null===(h=t.attributes.getNamedItem('bandwidth'))||void 0===h?void 0:h.value),_=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=R?Fl(R):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:N,baseURL:_,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(S=null===(b=t.attributes.getNamedItem('codecs'))||void 0===b?void 0:b.value)&&void 0!==S?S: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===(P=t.attributes.getNamedItem('id'))||void 0===P?void 0:P.value)&&void 0!==w?w:void 0})})),a.length?(this._representations=a,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 r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let o=r.getUint32(s,!1),n=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const u=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;e+=1){const e=n+(2147483647&r.getUint32(s,!1)),i=o+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:o/a,toTime:i/a,fromOffset:n,toOffset:e-1}),n=e,o=i}const d=t.refs[t.refs.length-1];d.toTime-d.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,r;const a=()=>{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 a;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');a=e.end-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.end&&(r=e.end,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.start)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*a)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}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 ec({mediaSource:i,sourceBuffer:e,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){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const s=this._findRef(e);if(s){if(i){this._isLastRef(s)&&e>=s.toTime&&(e=s.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:s.fromTime}this._appendVector[String(s.fromTime)]=t,this._stream.load(t,s.fromOffset,s.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=s.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 r=.1;if(s.toTime<i.end+r){const e=this._findRef(s.toTime);e&&e.toTime<i.end+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((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=!1){this._stream&&this._buffer.getByTime(t)&&!e?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0)}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 r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}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 sc;!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'}(sc||(sc={}));const rc=[sc.PAUSED,sc.PLAYING];class ac{constructor(e){this.videoState=new ks(sc.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Zi,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 r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),o=null!==(s=a.name&&ns(a.name))&&void 0!==s?s:ps(a),n=a.bandwidth/1e3,u={width:a.width,height:a.height},d=a.fps;if(!o)continue;const l={id:t,quality:o,bitrate:n,size:u,fps:d};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(sc.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(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekPositionTransition: ${JSON.stringify(a)};`}),s===exports.PlaybackState.STOPPED)return void(e!==sc.STOPPED&&(this.videoState.startTransitionTo(sc.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(sc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(i)return;const o=null==a?void 0:a.to;switch((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&rc.includes(e)&&this.seek(o),e){case sc.STOPPED:return this.videoState.startTransitionTo(sc.MANIFEST_LOADED),void this.prepare();case sc.MANIFEST_LOADED:return void this.videoState.startTransitionTo(sc.INITIAL_REPRESENTATION_SELECTED);case sc.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(sc.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case sc.METADATA_LOADED:return this.videoState.startTransitionTo(sc.READY),void this.dash.seek(null!=o?o:0);case sc.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(sc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(sc.PLAYING),this.playIfAllowed()));case sc.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(sc.PAUSED),this.video.pause()):(null==r?void 0:r.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case sc.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(sc.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},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=ts(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(Ps(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new is(this.video),this.dash=new ic({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,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},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}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},r=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},a=as(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,s));o(a.timeUpdate$,e.position$),o(a.durationChange$,e.duration$),o(a.ended$,e.endedEvent$),o(a.looped$,e.loopedEvent$),o(a.error$,e.error$),o(a.isBuffering$,e.isBuffering$),o(a.firstFrame$,e.firstFrameEvent$),this.subscription.add(a.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===sc.PLAYING||this.videoState.getState()===sc.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),o(ws(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===sc.READY&&this.videoState.setState(sc.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(sc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(a.playing$.subscribe((()=>{this.videoState.setState(sc.PLAYING),us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.loadedMetadata$.subscribe((()=>{this.videoState.setState(sc.METADATA_LOADED)}),s)).add(a.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).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;const s=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),l=r();let c;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!l&&t.isNonNullable(n))c=n;else{const t=Es(this.video.buffered,1e3*this.video.currentTime),i=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);c=null===(e=Ts(a.map((({track:t})=>t)),{container:d,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:s}))||void 0===e?void 0:e.id}return t.isNonNullable(c)?null===(i=a.find((({track:t})=>t.id===c)))||void 0===i?void 0:i.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===sc.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(sc.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?t.height<=e.height:t===e))).subscribe((t=>{const e=Es(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!r())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Ps(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=kl(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).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.seekPosition.stateChangeStarted$,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){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(sc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var oc=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,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},nc=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 uc=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class dc{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)}executeNextRequests(){return p(this,void 0,void 0,(function*(){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[r,a]=uc(s.request);if(r>=i.from&&a<=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),r=this.activeRequests.get(i.url);s&&r&&r.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(t,e){const i=e.map(uc),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const o=a.toString(),n=new Sn,u=n.signal,d={url:t,from:s,to:r,loaded:0,data:null,abortController:n};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const l=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return gn(fetch).fetch(o,{signal:u}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(d);const[r,a]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,a);const o=r.getReader(),n=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);d.data=new ArrayBuffer(n);const u=new Uint8Array(d.data),c=({done:t,value:e})=>p(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(d):e&&(u.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),yield null==o?void 0:o.read().then(c,dc.suppressStreamErrors).catch(l))}));null==o||o.read().then(c,dc.suppressStreamErrors).catch(l)}),dc.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r}){var a,o,n,u,d,l,c;if(!this.activeRequests.has(t)||!r)return;const h=null!==(a=this.dashJsRequestQueue.get(t))&&void 0!==a?a:[];for(const a of h){const{request:h}=a,[p,m]=uc(h),f=p>=e&&m<=e+s,v=e>=p&&e+s<m,b=r.slice(p-e,Math.min(m-e+1,s));(f||v)&&(h.requestStartDate=null!==(o=h.requestStartDate)&&void 0!==o?o:new Date,h.firstByteDate=null!==(n=h.firstByteDate)&&void 0!==n?n:new Date,h.bytesLoaded=b.byteLength,h.bytesTotal=i-e),f?(h.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==a))),null===(d=a.success)||void 0===d||d.call(a,b,'',t),null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(h,t,200,{},[])):v&&(null===(c=a.progress)||void 0===c||c.call(a,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,o,n;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const u=null!==(o=this.dashJsRequestQueue.get(t))&&void 0!==o?o:[];for(const t of u){const[r,a]=uc(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(n=null==t?void 0:t.error)||void 0===n||n.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=uc(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.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 lc{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(lc.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;lc.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const cc=(t,e)=>{const i=new dc(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new lc(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var hc=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject;let r=NaN,a=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,o=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const o=e.onload,n=e.progress;e.onload=function(...e){return(e=>{var s,r,a;if(!e.getAllResponseHeaders().includes('x-playback-duration'))return;const o=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),n=parseInt(null!==(r=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==r?r:'',10),u=null!==(a=null!=n?n:1e3*o)&&void 0!==a?a:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)})(this),o(...e)},e.progress=function(...t){return this.readyState>=2&&!a&&(a=!0,s.next(Date.now()-r)),n(...t)},r=Date.now(),a=!1}return o(e)}}}),!0),{playbackDuration$:i,ping$:s}};class pc{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}}const mc={};var fc;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(fc||(fc={}));const vc=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class bc{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks(fc.DOWNLOADING_LIB),this.textTracksManager=new Zi,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 pc,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition(),a=this.isLive$.getValue();if(this.videoState.getTransition())return;if(e===fc.DOWNLOADING_LIB||e===fc.STREAM_INITIALIZED)return;const o=null==r?void 0:r.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&e!==fc.STOPPED&&i!==exports.PlaybackState.STOPPED&&(a?this.seek(o+Sc(this.liveOffset.getTotalPausedTime())):this.seek(o)),i){case exports.PlaybackState.STOPPED:switch(e){case fc.STOPPED:break;case fc.PLAYING:case fc.PAUSED:case fc.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case fc.PLAYING:break;case fc.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(Sc(this.liveOffset.getTotalOffset()))):this.seek(Sc(this.liveOffset.getTotalOffset()))),this.play();break;case fc.READY:this.play();break;case fc.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case fc.PLAYING:this.pause(),this.liveOffset.pause();break;case fc.PAUSED:break;case fc.READY:this.videoState.setState(fc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case fc.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=ts(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Ps(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);wl(Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(mc.MediaPlayer=e.MediaPlayer,mc.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(mc.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(mc.Debug,'dashjs not loaded'),this.player=mc.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?Fl(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=cc(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&&nc(this.player),oc(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(fc.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(ws(this.video),this.elementSize$),r(vc(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$),r(vc(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const a=vc(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})));a.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===fc.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Wi(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$:a.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Wi(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})),r(vc(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),r(vc(this.player,'fragmentLoadingStarted').pipe(t.map((t=>Ps(t.request.url)))),e.hostname$),r(vc(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 r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=ps(t),s=t.bitrate/1e3,o={width:t.width,height:t.height},n=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:o,fps:n};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===r&&(a=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&e.currentVideoTrack$.next(a),this.videoState.setState(fc.STREAM_INITIALIZED),this.videoState.startTransitionTo(fc.READY)})),r(vc(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)})),r(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=Ts(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)})),r(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>Sc(t)))),this.params.output.duration$);const o=vc(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));r(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:o}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(o.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),r(vc(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),r(vc(this.player,'playbackEnded'),e.endedEvent$),r(vc(this.player,'playbackProgress').pipe(t.map((()=>ss(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),r(vc(this.player,'playbackPlaying'),(()=>{this.videoState.setState(fc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)})),r(vc(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(fc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(vc(this.player,'playbackPaused'),(()=>{this.videoState.setState(fc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)})),r(vc(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===fc.READY&&this.videoState.setState(fc.READY)})),r(this.isLive$,e.isLive$),r(ws(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:u}=hc(this.player);r(n,this.maxSeekBackTime$),r(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(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}}})})),r(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(vc(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(vc(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(Ji(this.video,i.isLooped,s));const{volumeState$:d,looped$:l}=as(this.video);this.subscription.add(Ki(this.video,i.volume,d,s)),this.subscription.add(d.subscribe(e.volume$,s)),this.subscription.add(l.subscribe(e.loopedEvent$))}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(fc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(fc.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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Sc(i));const s=Wl(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ql.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(fc.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(fc.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)}}const Sc=t=>-t/1e3;function gc(){return t.now()}function yc(t){return gc()-t}function Tc(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Ec(e,i,s,r){const a=window.XMLHttpRequest;let o,n,u,d,l,c=!1,h=0,p=!1,m='arraybuffer',f=7e3,v=2e3,b=()=>{if(c)return;t.assertNonNullable(d);const e=yc(d);let i;if(e<v)return i=v-e,void setTimeout(b,i);v*=2,v>f&&(v=f),n&&n.abort(),n=new a,g()};const S=()=>{if(!c){if(--h>=0)return b(),void(r&&r());c=!0,l&&l(),s&&s()}},g=()=>{d=gc(),n=new a,n.open('get',e);let s,r=0,h=0;const f=()=>(t.assertNonNullable(d),Math.max(d,Math.max(s||0,h||0)));if(o&&n.addEventListener('progress',(t=>{const e=gc();o.updateChunk&&t.loaded>r&&(o.updateChunk(f(),t.loaded-r),r=t.loaded,s=e)})),u&&(n.timeout=u,n.addEventListener('timeout',(()=>S()))),n.addEventListener('load',(()=>{if(c)return;t.assertNonNullable(n);const e=n.status;if(e>=200&&e<300){if(n.response.byteLength&&o){const t=n.response.byteLength-r;t&&o.updateChunk&&o.updateChunk(f(),t)}l&&l(),n&&i(n.response)}else S()})),n.addEventListener('error',(()=>{S()})),p){const e=()=>{t.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(h=gc(),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=>(h=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(v=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(l=t,y),send:g,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return y}class Pc{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 r=e-t.start,a=t.end-t.start;i+=r;const o=t.bytes*r/a;s+=o,t.start=e,t.bytes-=o}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/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 wc{constructor(t,e,i,s,r){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=r}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=gc(),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=Ec(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=gc()-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=gc()}_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=gc();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 r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._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(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}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 kc{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 Pc(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Tc(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=Tc(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',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.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,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));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(e,i){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s('setting video src'),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{t.assertNonNullable(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],i()})),this.videoPlayStarted=!1,r.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const o=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(r,'progress',(()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:'playing'})):o()}))};o()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new wc(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:r}=this.params;let a=!1,o=null,n=null,u=null,d=null,l=!1;const c=()=>{const t=a&&(!l||l===this.rep);return t||i('Not running!'),t},h=(t,e,i)=>{u&&u.abort(),u=Ec(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=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}`),v()},v=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=gc()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const r=this.bufferStates[i];t=Math.min(t,r.buf),r.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,m(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else m(1)},b=e=>{let s;const a=()=>s&&s.start?s.start.length:0,o=t=>s.start[t]/1e3,n=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,l=(t,e)=>({chunkIdx:u(t),startTS:o(t),dur:n(t),discontinuity:e}),h=()=>{let t=0;if(s&&s.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=s.dur.length-1;t>=0&&(e-=s.dur[t]/1e3,!(e<=0));--t);}return l(t,!0)},p=(t,e,i)=>{d&&d.abort(),d=Ec(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{d=null})).withJSONResponse().send()};return{seek:(i,n)=>{p(e,(e=>{if(!c())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let d=0;for(let t=0;t<s.dur.length;++t)d+=s.dur[t];d>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(d/s.dur.length)),r({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=a();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(o(t)>e)return l(t);return h()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=a(),r=t?t.chunkIdx+1:0,o=r-s.fragIndex;if(!(e<=0)){if(!t||o<0||o-e>10)return i(`Resync: offset=${o} bChunks=${e} chunk=`+JSON.stringify(t)),h();if(!(o>=e))return l(r-s.fragIndex,!1)}}}},S=()=>{a=!1,n&&n.abort(),u&&u.abort(),d&&d.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:i=>{const{videoElement:s,logger:r}=this.params;let n,u,l,m,f,g,y,T=b(e.jidxUrl),E=0;const P=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=gc(),s=Math.min(1e4,e-i);E=i;const r=()=>{d||c()&&T.seek((()=>{c()&&(E=gc(),w(),P())}))};s>0?f=window.setTimeout((()=>{this.paused?P():r()}),s):r()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(l);if(i){if(l&&i.discontinuity)return r('Detected discontinuity; restarting playback'),void(this.paused?P():(S(),this._initPlayerWith(e)));x(i)}else P()},k=(t,e)=>{if(!c()||!this.sourceBuffer)return;let i,a,o;const n=i=>{window.setTimeout((()=>{c()&&k(t,e)}),i)};if(this.sourceBuffer.updating)r('Source buffer is updating; delaying appendBuffer'),n(100);else{const u=gc(),d=s.currentTime;!this.paused&&s.buffered.length>1&&g===d&&u-y>500&&(r('Stall suspected; trying to fix'),this._fixupStall()),g!==d&&(g=d,y=u);const l=this._getBufferSizeSec();if(l>30)r(`Buffered ${l} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:l}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;r('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(i=this.sourceBuffer.buffered.start(0),a=d,a-i>4&&this.sourceBuffer.remove(i,a-3)),n(1e3)}}},$=()=>{u&&n&&(r([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(l)]),k(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{c()&&p(A(t),((e,i)=>{if(c()){if(i/=1e3,u=e,l=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=>{c()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},_=t=>{c()&&(e.cachedHeader=t,k(t,(()=>{n=!0,$()})))};a=!0,T.seek((e=>{c()&&(E=gc(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(l=e,w())):P())}),i),e.cachedHeader?_(e.cachedHeader):h(e.headerUrl,_,(()=>this._handleNetworkError()))},stop:S,getTimestampSec:()=>o},l}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),t.isNonNullable(r)&&(r+=.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(r),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,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.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=gc();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,o=!0;const n=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(o&&t>r&&yc(a)<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=gc();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Ec(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;Qi(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 $c;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}($c||($c={}));const Ac=[$c.PAUSED,$c.PLAYING,$c.READY],xc=[$c.PAUSED,$c.PLAYING,$c.READY];class Nc{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks($c.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Zi,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new pc,this._dashCb=e=>{var i,s,r,a;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}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,a=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),r=null!==(s=ns(e.name))&&void 0!==s?s:ps(e.video),o=e.bitrate/1e3,n=Object.assign({},e.video);if(!r)continue;const u={id:t,quality:r,bitrate:o,size:n};a.push({track:u,representation:e})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===$c.MANIFEST_READY&&this.videoState.setState($c.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(a=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===a?void 0:a.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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekPositionTransition: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED)return void(i!==$c.STOPPED&&(this.videoState.startTransitionTo($c.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState($c.STOPPED)));if(s)return;if(xc.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)}const n=null==o?void 0:o.to;if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&Ac.includes(i))this.seek(n+_c(this.liveOffset.getTotalPausedTime()));else switch(i){case $c.STOPPED:return this.videoState.startTransitionTo($c.MANIFEST_READY),void this.dash.attachSource(Wl(this.params.source.url));case $c.MANIFEST_READY:this.videoState.startTransitionTo($c.READY),this.prepare();break;case $c.READY:return void(r===exports.PlaybackState.PAUSED?this.videoState.setState($c.PAUSED):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($c.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState($c.PAUSED)}))));case $c.PLAYING:return void(r===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo($c.PAUSED),this.liveOffset.pause(),this.dash.pause()));case $c.PAUSED:return void(r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($c.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($c.PAUSED)})),this.params.output.position$.next(_c(this.liveOffset.getTotalOffset()))):this.seek(_c(this.liveOffset.getTotalOffset()))));default:return t.assertNever(i)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};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=ts(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(Ps(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=as(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===$c.READY&&this.videoState.setState($c.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState($c.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState($c.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(_c)).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(Ji(this.video,this.params.desiredState.isLooped,i)).add(Ki(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(rs(this.video).subscribe(this.params.output.firstBytesEvent$)).add(es(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&ds[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case $c.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case $c.MANIFEST_READY:case $c.READY:break;case $c.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case $c.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.seekPosition.stateChangeStarted$,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 kc({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,r,a,o;const n=this.representations$.getValue(),u=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(),d=null!==(r=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&t.isNonNullable(u)?u:null===(a=Ts(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===a?void 0:a.id,c=null===(o=n.find((({track:t})=>t.id===l)))||void 0===o?void 0:o.representation;t.assertNonNullable(c),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}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),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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(_c(i)),this.dash.reinit(Wl(this.params.source.url,i)),this.params.output.seekedEvent$.next()}}const _c=t=>-t/1e3,Dc=t=>{let e=null;if(t.QUALITY&&(e=ns(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=ps({width:i,height:s})}return null!=e?e:null},Rc=(t,e=t)=>p(void 0,void 0,void 0,(function*(){var i;const s=yield gn(fetch).fetch(t),r=(yield s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const o=rn(s[1].split(',').map((t=>t.split('=')))),n=null!==(i=o.QUALITY)&&void 0!==i?i:`stream-${o.BANDWIDTH}`,u=Dc(o);let d;o.BANDWIDTH&&(d=parseInt(o.BANDWIDTH,10)/1e3||void 0),!d&&o['AVERAGE-BANDWIDTH']&&(d=parseInt(o['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const l=o['FRAME-RATE']?parseFloat(o['FRAME-RATE']):void 0;let c;if(o.RESOLUTION){const[t,e]=o.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const h=new URL(r[++t],e).toString();u&&a.push({id:n,quality:u,url:h,bandwidth:d,size:c,fps:l})}return a}));var Ic;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ic||(Ic={}));class Lc{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks(Ic.STOPPED),this.textTracksManager=new Zi,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Ic.STOPPED&&(this.videoState.startTransitionTo(Ic.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(Ic.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(e===Ic.STOPPED)return this.videoState.startTransitionTo(Ic.READY),void this.prepare();if(r||a){const e=this.videoState.getState();this.videoState.setState(Ic.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const{currentTime:i}=this.video;return this.prepare(),void(o&&!t.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const n=null==o?void 0:o.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&this.seek(n),e){case Ic.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Ic.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ic.PLAYING),this.playIfAllowed()));case Ic.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ic.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ic.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ic.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Ic.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=ts(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(Ps(this.params.source.url)),Rc(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),o=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const u=r?'master':o;return r&&!a&&s.startTransitionTo('master'),n.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ji(this.video,i.isLooped,s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Ic.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ic.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ic.READY&&this.videoState.setState(Ic.READY),this.videoState.getState()===Ic.PLAYING&&this.playIfAllowed()}),s).add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=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(Ps(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Ic.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,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(){Qi(this.video).then((t=>{t||(this.videoState.setState(Ic.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}var Cc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Cc||(Cc={}));class Oc{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new ks(Cc.STOPPED),this.textTracksManager=new Zi,this.manifests$=new t.ValueSubject([]),this.liveOffset=new pc,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(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Cc.STOPPED&&(this.videoState.startTransitionTo(Cc.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(Cc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(e===Cc.STOPPED)return this.videoState.startTransitionTo(Cc.READY),void this.prepare();if(r||a){const e=this.videoState.getState();this.videoState.setState(Cc.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const i=Vc(this.liveOffset.getTotalOffset());return this.prepare(),void(o&&!t.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const n=null==o?void 0:o.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n))return this.videoState.startTransitionTo(Cc.READY),this.seek(n+Vc(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(e){case Cc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Cc.PAUSED),this.liveOffset.pause(),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Cc.PLAYING),this.playIfAllowed()));case Cc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Cc.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&us(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Cc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Cc.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Vc(this.liveOffset.getTotalOffset()))):this.seek(Vc(this.liveOffset.getTotalOffset()))):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Cc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=ts(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]),Rc(Wl(this.params.source.url)).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ps(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,r=i.getState(),a=s.getTransition(),o=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const u=r?'master':o;return r&&!a&&s.startTransitionTo('master'),n.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Ki(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Cc.PLAYING),us(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Cc.PAUSED),us(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Cc.READY&&this.videoState.setState(Cc.READY),this.videoState.getState()===Cc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(Vc)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=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(Ps(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Cc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:r.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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,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=Wl(e.url,this.liveOffset.getTotalOffset());var s;this.video.setAttribute('src',i),this.video.load(),(s=i,p(void 0,void 0,void 0,(function*(){const t=yield gn(fetch).fetch(s,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Qi(this.video).then((t=>{t||(this.videoState.setState(Cc.PAUSED),this.liveOffset.pause(),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Vc(i)),this.params.output.seekedEvent$.next()}}const Vc=t=>-t/1e3,Mc={};var Bc;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Bc||(Bc={}));const Fc=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Uc{constructor(e){this.subscription=new t.Subscription,this.videoState=new ks(Bc.INITIALIZING),this.textTracksManager=new Zi,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(e===Bc.INITIALIZING)return;const a=null==r?void 0:r.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(a)&&this.seek(a),i){case exports.PlaybackState.STOPPED:switch(e){case Bc.STOPPED:break;case Bc.READY:case Bc.PLAYING:case Bc.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Bc.PLAYING:break;case Bc.STOPPED:this.prepare();break;case Bc.READY:case Bc.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Bc.PAUSED:break;case Bc.STOPPED:this.prepare();break;case Bc.READY:this.videoState.setState(Bc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Bc.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=ts(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Ps(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 t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);wl(Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(Mc.Hls=e.default,Mc.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(Mc.Hls,'hls.js not loaded'),this.hls=new Mc.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Bc.STOPPED)}subscribe(){t.assertNonNullable(Mc.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=as(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,i.position$),a(r.durationChange$,i.duration$),a(r.ended$,i.endedEvent$),a(r.looped$,i.loopedEvent$),a(r.error$,i.error$),a(r.isBuffering$,i.isBuffering$),a(r.currentBuffer$,i.currentBuffer$),a(r.firstBytes$,i.firstBytesEvent$),a(r.firstFrame$,i.firstFrameEvent$),a(r.seeked$,i.seekedEvent$),this.subscription.add(Ji(this.video,e.isLooped,s)),this.subscription.add(Ki(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fc(this.hls,Mc.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Bc.PLAYING),us(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Bc.PAUSED),us(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Bc.READY&&this.videoState.setState(Bc.READY),this.videoState.getState()===Bc.PLAYING&&this.playIfAllowed()}),s)),a(Fc(this.hls,Mc.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:o}=e,n=null!==(s=ns(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:ps({width:a,height:o});if(!n)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,d={id:r.toString(),quality:n,bitrate:e.bitrate/1e3,size:{width:a,height:o},fps:u};return this.trackLevels.set(r,{track:d,level:e}),t.push(d),t}),[])))),i.availableVideoTracks$),a(Fc(this.hls,Mc.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>Ps(t)))),i.hostname$),this.subscription.add(Wi(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=Fc(this.hls,Mc.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(Wi(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 r=this.hls.levels.indexOf(s),a=this.hls.currentLevel,o=this.hls.levels[a];!o||s.bitrate>o.bitrate?this.hls.nextLevel=r:(this.hls.loadLevel=r,this.hls.loadLevel=r)}),{changed$:n.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),a(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Bc.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return p(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(Bc.PLAYING);(yield Qi(this.video))||(this.videoState.setState(Bc.PAUSED),us(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(Bc.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}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(Bc.STOPPED),us(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class jc{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)}}var Hc,qc,Gc,Yc,zc,Qc,Wc,Jc,Kc,Xc,Zc,th,eh,ih,sh,rh,ah;const oh=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),nh=(null===(Hc=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Hc?void 0:Hc.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),uh=document.createElement('video'),dh={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Gc=null===(qc=window.SourceBuffer)||void 0===qc?void 0:qc.prototype)||void 0===Gc?void 0:Gc.appendBuffer)),hls:Boolean((null===(Yc=uh.canPlayType)||void 0===Yc?void 0:Yc.call(uh,'application/x-mpegurl'))||(null===(zc=uh.canPlayType)||void 0===zc?void 0:zc.call(uh,'vnd.apple.mpegURL')))},lh={mp4:Boolean(null===(Qc=uh.canPlayType)||void 0===Qc?void 0:Qc.call(uh,'video/mp4')),webm:Boolean(null===(Wc=uh.canPlayType)||void 0===Wc?void 0:Wc.call(uh,'video/webm'))},ch={h264:Boolean(null===(Kc=null===(Jc=window.MediaSource)||void 0===Jc?void 0:Jc.isTypeSupported)||void 0===Kc?void 0:Kc.call(Jc,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Zc=null===(Xc=window.MediaSource)||void 0===Xc?void 0:Xc.isTypeSupported)||void 0===Zc?void 0:Zc.call(Xc,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(eh=null===(th=window.MediaSource)||void 0===th?void 0:th.isTypeSupported)||void 0===eh?void 0:eh.call(th,'video/webm; codecs="vp9"')),aac:Boolean(null===(sh=null===(ih=window.MediaSource)||void 0===ih?void 0:ih.isTypeSupported)||void 0===sh?void 0:sh.call(ih,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(ah=null===(rh=window.MediaSource)||void 0===rh?void 0:rh.isTypeSupported)||void 0===ah?void 0:ah.call(rh,'audio/webm; codecs="opus"'))},hh=(ch.h264||ch.h265)&&ch.aac,ph=!oh,mh=nh||oh,fh=!dh.hls||!mh,vh=3e4,bh=18e4,Sh=3,gh=100,yh={cacheDuration:12e4},Th={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Eh={maxPausedTime:3e4},Ph={maxPausedTime:3e4};class wh{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,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 jc(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return dh.mse&&lh.mp4&&hh&&ph;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return dh.mse&&lh.mp4&&hh;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return dh.mse&&lh.webm&&ch.vp9&&ch.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return dh.mse&&lh.mp4&&hh;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return dh.hls&&lh.mp4&&mh;case exports.VideoFormat.HLS_JS:return dh.mse&&lh.mp4&&hh&&fh;case exports.VideoFormat.MPEG:return lh.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new jc(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(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:'destroyProvider'});const i=this.params.desiredState.seekPosition,s=i.getTransition();s?t.isNonNullable(s.from)&&i.startTransitionTo(s.from):i.startTransitionTo(this.providerOutput.position$.getValue()),e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.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:r}=this.params,a=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const o=i[e];return t.assertNonNullable(o),new ac({container:s,source:o,desiredState:r,output:a,config:yh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const o=i[e];return t.assertNonNullable(o),new zl({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const o=i[e];return t.assertNonNullable(o),new bc({container:s,source:o,desiredState:r,output:a,format:e,config:Ph,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=i[e];return t.assertNonNullable(o),new Lc({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const o=i[e];return t.assertNonNullable(o),new Oc({container:s,source:o,desiredState:r,output:a,config:Eh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=i[e];return t.assertNonNullable(o),new Uc({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const o=i[e];return t.assertNonNullable(o),new Zl({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const o=i[e];return t.assertNonNullable(o),new Nc({container:s,source:o,desiredState:r,output:a,config:Th,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:r,meta:a}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(n),new Kl({connection:n,meta:a,container:s,source:i,format:e,desiredState:r,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)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var r;return s.add(t.merge(this.providerOutput.error$,(r={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:vh,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=t.timeout(r.maxTransitionInterval),a=new t.ValueSubject(void 0);t.merge(r.desiredPlaybackState$.stateChangeStarted$.pipe(t.mapTo(s)),r.desiredPlaybackState$.stateChangeEnded$.pipe(t.mapTo(void 0)),r.providerChanged$.pipe(t.map((()=>a.getValue())))).subscribe(a);const o=new t.Subscription;return i.add(o),i.add(a.subscribe((t=>{o.unsubscribe(),t&&o.add(t.subscribe(e))}))),i}))).pipe(t.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(gh,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===o.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+bh?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%Sh}))),s}}const kh=(t,e,i)=>i*e+(1-i)*t;class $h{constructor(e){var i;this.prevReported=void 0,this.params=e,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 gs(`raw_${s}`),this.smoothedSeries$=new gs(`smoothed_${s}`),this.reportedSeries$=new gs(`reported_${s}`)}next(e){this.slow=kh(this.slow,e,this.params.emaAlphaSlow),this.fast=kh(this.fast,e,this.params.emaAlphaFast);const i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast),this.smoothed$.next(this.smoothed),(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)),this.rawSeries$.next(e),this.smoothedSeries$.next(this.smoothed)}}var Ah;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Ah||(Ah={}));const xh=new Map;let Nh=Ah.RUNTIME;const _h=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(_h,'test'),localStorage.removeItem(_h),Nh=Ah.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(_h),Nh=Ah.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;Nh=Ah.RUNTIME}}})();const Dh=(e,i)=>{switch(Nh){case Ah.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ah.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ah.RUNTIME:return void xh.set(e,i);default:t.assertNever(Nh)}},Rh=window.navigator.connection,Ih=()=>{const e=null==Rh?void 0:Rh.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Lh=()=>{const e=null==Rh?void 0:Rh.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Ch=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Oh{constructor(e){var i,s;this.subscription=new t.Subscription,this.tuningConfig=e;const r=Oh.load('one_video_throughput')||(e.useBrowserEstimation?Ih():void 0)||5e3,a=null!==(s=null!==(i=Oh.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Lh():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(r),this.rtt$=new t.ValueSubject(a),this.rttAdjustedThroughput$=new t.ValueSubject(Ch(r,a,e.rttPenaltyRequestSize)),this.throughput=new $h({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new $h({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Ih();e&&this.throughput.next(e);const i=Lh();t.isNonNullable(i)&&this.rtt.next(i)};Rh&&'onchange'in Rh&&this.subscription.add(t.fromEvent(Rh,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Dh('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Dh('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})=>Ch(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.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const r=new t.Subscription;switch(this.subscription.add(r),e.readyState){case 4:break;case 3:case 2:r.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:r.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}r.add(t.fromEvent(e,'loadend').subscribe((a=>{if(200===e.status){const e=a.loaded,r=t.now(),o=e-i,n=r-s;this.addRawSpeed(o,n)}r.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const r=t.now();let a=0,o=t.now();const n=t=>{i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=({done:e,value:d})=>p(this,void 0,void 0,(function*(){e?this.addRawSpeed(s,t.now()-r):d&&(s+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&t.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,t.now()-o),a=0,o=t.now()),yield null==i?void 0:i.read().then(u,n))}));null==i||i.read().then(u,n)}addRawSpeed(t,e){if(Oh.sanityCheck(t,e)){const i=8*t/e;this.throughput.next(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(Nh){case Ah.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case Ah.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case Ah.RUNTIME:return xh.get(e);default:t.assertNever(Nh)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Vh=(e=(t=>t))=>({playbackState:i,seekPosition:s,playbackAbort$:r,looped$:a,position$:o})=>new t.Observable((n=>{let u;const d=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),l=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),c=s.stateChangeEnded$.pipe(t.filter((e=>{var s,r;return t.isNonNullable(e.to)&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),h=s.stateChangeEnded$.pipe(t.filter((e=>{var s,r;return t.isNullable(e.to)&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(d,h).pipe(t.map((()=>e(o.getValue())))),m=t.merge(t.merge(l,c,r).pipe(t.map((()=>e(o.getValue())))),a.pipe(t.map(e)));return(new t.Subscription).add(p.subscribe((t=>{u=e(t)}))).add(m.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const r={start:u,end:s};u=void 0,n.next(r)})))})),Mh=Vh((t=>t)),Bh=Vh((t=>Math.round(1e3*t)+Date.now())),Fh={[o.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,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 ks(exports.PlaybackState.STOPPED),seekPosition:new ks(void 0),volume:new ks({volume:1,muted:!1}),videoTrack:new ks(void 0),autoVideoTrackSwitching:new ks(!0),autoVideoTrackLimits:new ks({}),isLooped:new ks(!1),externalTextTracks:new ks([]),currentTextTrack:new ks(void 0),textTrackCuesSettings:new ks({})},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({}),currentBuffer$:new t.ValueSubject(void 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={started$:new t.Subject,startAttempt$: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,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:bs},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(l)){const s=l[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Oh(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.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(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(e){var i,s;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 wh({screenFormatsPriority:[...Fh[o.SCREEN].live,...Fh[o.SCREEN].vod],chromecastFormatsPriority:[...Fh[o.CHROMECAST].live,...Fh[o.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},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){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekPosition.startTransitionTo(t),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),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}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({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(){var e;t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(i))return this.info.position$.getValue();const s=this.desiredState.seekPosition.getTransition(),r=null!==(e=null==s?void 0:s.to)&&void 0!==e?e:null==s?void 0:s.from;return t.isNonNullable(r)?r:i.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.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$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING)),t.debounce(0)).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition(),i=null==e?void 0:e.to;t.isNonNullable(i)&&(this.desiredState.seekPosition.setState(i),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition();t.isNonNullable(null==e?void 0:e.to)||this.desiredState.seekPosition.setState(void 0),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)=>ms(t)?1:ms(e)?-1:ls(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$.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((({seekPosition:e,position$:i})=>t.merge(e.stateChangeStarted$.pipe(t.map((t=>t.to)),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>t.isNullable(e.getState())&&t.isNullable(e.getTransition()))))))({seekPosition:this.desiredState.seekPosition,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((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).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 r=0;const a=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),r=i.getValue()||s.getValue();return t&&!r})),t.filterChanged());this.subscription.add(a.subscribe((t=>{t?r=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),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:o.add(Bh({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(Mh({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).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=Ts(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),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.seekPosition.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekPosition',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),vs={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{fs=t})),this.providerContainer.current$.subscribe((({type:t})=>Ss('provider',t))),i.duration$.subscribe((t=>Ss('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>Ss('tracks',t))),this.events.fatalError$.subscribe(new gs('fatalError')),this.events.managedError$.subscribe(new gs('managedError')),i.position$.subscribe(new gs('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new gs('quality')),i.currentBuffer$.subscribe(new gs('buffer')),i.isBuffering$.subscribe(new gs('isBuffering'))].forEach((t=>this.subscription.add(t))),Ss('codecs',Object.keys(ch).filter((t=>ch[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.46';
|