@vkontakte/videoplayer-core 2.0.42 → 2.0.45

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/esnext.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.42
3
- * Tue, 15 Mar 2022 22:20:55 GMT
4
- * https://st.mycdn.me/static/playersdk/2-0-42/doc/
2
+ * @vkontakte/videoplayer-core v2.0.45
3
+ * Tue, 22 Mar 2022 14:34:17 GMT
4
+ * https://st.mycdn.me/static/playersdk/2-0-45/doc/
5
5
  */
6
- import{ValueSubject as t,Subject as e,Subscription as s,isNonNullable as i,isNullable as a,fromEvent as r,assertNever as n,merge as o,tap as d,map as h,observableFrom as u,filterChanged as c,assertNonNullable as l,Observable as p,once as m,debounce as f,now as S,combine as g,filter as b,timeout as v,mapTo as T,throttle as y,Logger as E}from'@vkontakte/videoplayer-shared';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared';import $ from'lodash/debounce';var w,P,A,k,_,D;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(w||(w={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(P||(P={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(A||(A={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(k||(k={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(D||(D={}));const R={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:[P.DASH_WEBM,P.DASH_SEP,P.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 I{connection$=new t(void 0);castState$=new t(k.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(k.NOT_AVAILABLE);subscription=new s;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;var s;i(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(s='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',s),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){i(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();a(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();a(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),s=cast.framework.CastContext.getInstance();this.subscription.add(r(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(r(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),h((t=>t.castState))),u([s.getCastState()])).pipe(c(),h(L),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{const n=r===k.CONNECTED,o=i(this.connection$.getValue());if(n&&!o){const i=s.getCurrentSession();l(i);const r=i.getCastDevice(),n=i.getMediaSession()?.media.contentId;(a(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:i,castDevice:r}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===k.CONNECTED?i(this.connection$.getValue())?k.CONNECTED:k.AVAILABLE:r)})))}initializeCastApi(){let t,e,s;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const L=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return k.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return k.AVAILABLE;case cast.framework.CastState.CONNECTING:return k.CONNECTING;case cast.framework.CastState.CONNECTED:return k.CONNECTED;default:return n(t)}};var C,x,O,N;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(C||(C={})),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'}(x||(x={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(O||(O={})),function(t){t.MP4='mp4',t.WEBM='webm'}(N||(N={}));var B=async t=>{const e=t.muted;try{await t.play()}catch(s){if(s instanceof DOMException&&(20===s.code||'AbortError'===s.name))return!1;if(e)return console.warn(s),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};const M=(t,e,i,{equal:r=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=a(n),c=new s;return n&&c.add(n.subscribe((e=>{const s=t.getState();r(e,s)&&t.setState(e)}),o)),r(h,d)||(i(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{i(e.to),u&&t.setState(e.to)}),o)),c},U=(t,e,s)=>M(e,(()=>t.loop),(e=>{i(e)&&(t.loop=e)}),{onError:s}),V=(t,e,s,a)=>M(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{i(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:s,onError:a}),F=(t,e)=>{if(t.id===e)return!0;const[s,i,a]=e.split('|');return t.language===i&&t.label===a};class H{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new s;externalTracks=new Map;connect(t,e,s){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const a=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(M(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{i(t)&&this.setExternal(t)}),{equal:(t,e)=>i(t)&&i(e)&&t.length===e.length&&t.every((({id:t},s)=>t===e[s].id)),changed$:this.available$.pipe(h((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(M(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(M(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(r(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(r(t,'addtrack'),r(t,'removetrack'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},s)=>t===e[s].id))))).subscribe(this.available$)),this.subscription.add(o(r(t,'change'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),h((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(r(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const s=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',s))};t.track?.addEventListener('cuechange',s)}))),this.subscription.add(r(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const s of Array.from(t)){const t=s;i(e.align)&&(t.align=e.align),i(e.position)&&(t.position=e.position),i(e.size)&&(t.size=e.size),i(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(H.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:s}=t,i=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(i)?{id:i,type:'external',language:e,label:s,url:this.externalTracks.get(i).url}:{id:i,type:'internal',language:e,label:s}}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(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))i(t)&&F(e,t)?e.mode='showing':e.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(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var q=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},G=t=>new p((e=>{let i=0;return(new s).add(r(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(r(t,'loadeddata').subscribe((()=>{e.next(Date.now()-i)})))})).pipe(m());class Y{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,s=this._source.buffered.length;e<s;e++){let s=this._source.buffered.start(e);const i=this._source.buffered.end(e);s>t&&s-t<3&&(s=t),this._buffer.push({start:s,end:i,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 s=this.getNext(t);if(s&&s.start-t.end<(e||3))return s}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,s){this._buffer.forEach((({start:i,end:a})=>{const r=i>=t&&i<e,n=a>=t&&a<e;r&&n||(r?s(e,a):n?s(i,t):i<t&&a>e?(s(e,a),s(i,t)):s(i,a))}))}destroy(){this._buffer=[]}}var z=(t,e,s=3)=>{let i=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(i=n,a=o,!s)return{start:i,end:a};for(let e=r-1;e>=0;e--)t.end(e)+s>=i&&(i=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-s<=a&&(a=t.end(e))}}return{start:i,end:a}},Q=t=>new p((e=>{let i=0;return(new s).add(r(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(r(t,'loadedmetadata').subscribe((()=>{e.next(Date.now()-i)})))})).pipe(m());const W=t=>{const e=(e,s=(()=>{}))=>r(t,e).pipe(h(s)),s=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>r(t,e)))).pipe(h((()=>t.readyState<3)),c()),i=o(r(t,'progress'),r(t,'timeupdate')).pipe(h((()=>z(t.buffered,t.currentTime)))),a=r(t,'volumechange').pipe(f(0),h((()=>({muted:t.muted,volume:t.volume})))),n=r(t,'error').pipe(h((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}})));return{playing$:e('playing'),pause$:e('pause'),canplay$:e('canplay'),ended$:e('ended'),error$:n,seeked$:e('seeked'),seeking$:e('seeking'),progress$:e('progress'),loadedMetadata$:e('loadedmetadata'),loadedData$:e('loadeddata'),timeUpdate$:e('timeupdate',(()=>t.currentTime)),durationChange$:e('durationchange',(()=>t.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:a,firstBytes$:Q(t),firstFrame$:G(t)}};var j,J=(t,e,s=!1)=>{const i=t.getTransition();!s&&i&&i.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(j||(j={}));const K={[j.Q_144P]:144,[j.Q_240P]:240,[j.Q_360P]:360,[j.Q_480P]:480,[j.Q_720P]:720,[j.Q_1080P]:1080,[j.Q_1440P]:1440,[j.Q_2160P]:2160,[j.Q_4320P]:4320},X=(t,e)=>K[t]>K[e],Z=(t,e)=>K[t]<K[e],tt=Object.keys(K).sort(((t,e)=>Z(t,e)?-1:1)),et=({width:t,height:e},s)=>((t,e=.02)=>[...tt].find((s=>K[s]*(1+e)>=t)))(Math.min(t,e),s),st=t=>t===j.INVARIANT;let it=!1,at={};const rt=t=>{t(at)},nt=(t,e)=>{it&&(at.meta=at.meta??{},at.meta[t]=e)};class ot{name;constructor(t){this.name=t}next(t){if(!it)return;at.series=at.series??{};const e=at.series[this.name]??[];e.push([Date.now(),t]),at.series[this.name]=e}}const dt=new ot('best_bitrate'),ht=(t,{container:e,throughput:s,tuning:a,forwardBufferHealth:r,currentRepresentation:n})=>{const o=a.usePixelRatio?window.devicePixelRatio??1:1,d=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*o*a.containerSizeFactor,height:e.height*o*a.containerSizeFactor},h=d&&et(d,0),u=t.filter((t=>!st(t.quality))).sort(((t,e)=>X(t.quality,e.quality)?-1:1)),c=u.filter((t=>{const e=!h||Z(t.quality,h),o=!(i(s)&&isFinite(s)&&i(t.bitrate))||s>=t.bitrate*(d=r??.5,u=a.bitrateFactorAtEmptyBuffer,c=a.bitrateFactorAtFullBuffer,(u-c)*Math.pow(2,-10*d)+c);var d,u,c;const l=!a.lazyQualitySwitch||!n||(r??.5)>=.5||(t.size?.height||0)<=(n?.height||0);return e&&o&&l}))[0];return c&&c.bitrate&&dt.next(c.bitrate),c??u[u.length-1]??t[0]};var ut=(t,e)=>{let s=0;for(let i=0;i<t.length;i++){const a=1e3*t.start(i),r=1e3*t.end(i);a<=e&&e<=r&&(s=r)}return Math.max(s-e,0)},ct=t=>new URL(t).hostname;const lt=(t,e=300)=>new p((s=>{const{width:a,height:r}=t.getBoundingClientRect();if(s.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver($((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),i(a)&&i(r)&&s.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()}));class pt{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}setState(t){const e=this.transition,s=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:s,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,s=this.state;s===t||i(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var mt={};function ft(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function St(t,e){for(var s=0;s<e.length;s++){var i=e[s];i.enumerable=i.enumerable||!1,i.configurable=!0,'value'in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function gt(t,e,s){return e&&St(t.prototype,e),s&&St(t,s),t}function bt(t){return(bt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function vt(t,e){return(vt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Tt(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function yt(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?Tt(t):e}function Et(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 s,i=bt(t);if(e){var a=bt(this).constructor;s=Reflect.construct(i,arguments,a)}else s=i.apply(this,arguments);return yt(this,s)}}function $t(t,e,s){return($t='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,s){var i=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=bt(t)););return t}(t,e);if(i){var a=Object.getOwnPropertyDescriptor(i,e);return a.get?a.get.call(s):a.value}})(t,e,s||t)}Object.defineProperty(mt,'__esModule',{value:!0});var wt=function(){function t(){ft(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return gt(t,[{key:'addEventListener',value:function(t,e,s){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:s})}},{key:'removeEventListener',value:function(t,e){if(t in this.listeners)for(var s=this.listeners[t],i=0,a=s.length;i<a;i++)if(s[i].callback===e)return void s.splice(i,1)}},{key:'dispatchEvent',value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),s=0,i=e.length;s<i;s++){var a=e[s];try{a.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}}]),t}(),Pt=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&&vt(t,e)}(s,wt);var e=Et(s);function s(){var t;return ft(this,s),(t=e.call(this)).listeners||wt.call(Tt(t)),Object.defineProperty(Tt(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(Tt(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return gt(s,[{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)),$t(bt(s.prototype),'dispatchEvent',this).call(this,t)}}]),s}(),At=function(){function t(){ft(this,t),Object.defineProperty(this,'signal',{value:new Pt,writable:!0,configurable:!0})}return gt(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&&(At.prototype[Symbol.toStringTag]='AbortController',Pt.prototype[Symbol.toStringTag]='AbortSignal');var kt=mt.AbortController=At;mt.AbortSignal=Pt;var _t,Dt=mt.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e,s=t,i=s.fetch,a=s.Request,r=void 0===a?i.Request:a,n=s.AbortController,o=s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,d=void 0!==o&&o;if(!((e={fetch:i,Request:r,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:d}).__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),1):'function'==typeof e.Request&&!e.Request.prototype.hasOwnProperty('signal')||!e.AbortController))return{fetch:i,Request:h};var h=r;(h&&!h.prototype.hasOwnProperty('signal')||d)&&((h=function(t,e){var s;e&&e.signal&&(s=e.signal,delete e.signal);var i=new r(t,e);return s&&Object.defineProperty(i,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),i}).prototype=r.prototype);var u=i;return{fetch:function(t,e){var s=h&&h.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(s){var i;try{i=new DOMException('Aborted','AbortError')}catch(t){(i=new Error('Aborted')).name='AbortError'}if(s.aborted)return Promise.reject(i);var a=new Promise((function(t,e){s.addEventListener('abort',(function(){return e(i)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,u(t,e)])}return u(t,e)},Request:h}},Rt=t=>{const e=t.get('X-Delivery-Type'),s=t.get('X-Reused');return{type:null===e?D.HTTP1:e??void 0,reused:null===s?void 0:{1:!0,0:!1}[s]??void 0}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(_t||(_t={}));class It{throughputEstimator;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new kt;subscription=new s;constructor({throughputEstimator:t}={}){this.throughputEstimator=t}onHeadersReceived(t){const{type:e,reused:s}=Rt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(s)}async fetchManifest(t){const e=await Dt(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Lt);return e?(this.onHeadersReceived(e.headers),e.text()):null}async fetchRange(t,e,s,{method:i=_t.HEADER,onProgress:a,signal:d}={}){let h=t;const u=new Headers;switch(i){case _t.HEADER:u.append('Range',`${e}-${s}`);break;case _t.PARAM:{const t=new URL(h,location.href);t.searchParams.append('bytes',`${e}-${s}`),h=t.toString();break}default:n(i)}let c=this.abortAllController.signal;if(d){const t=new kt;this.subscription.add(o(r(this.abortAllController.signal,'abort'),r(d,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||d.aborted)&&t.abort(),c=t.signal}const l=S(),p=await Dt(fetch).fetch(h,{headers:u,signal:c}).catch(Lt);if(this.throughputEstimator?.addRawRtt(S()-l),!p)return null;if(!p.ok||!p.body)return Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const[m,f]=p.body.tee(),g=m.getReader();this.throughputEstimator?.trackStream(f);const b=parseInt(p.headers.get('Content-Length')??'',10);let v=0;const T=new ArrayBuffer(b),y=new Uint8Array(T),E=new DataView(T);let $=!1;const w=t=>{$=!0,Lt(t)},P=async({done:t,value:e})=>{0===v&&this.lastRequestFirstBytes$.next(S()-l),t?a?.(E,v):e&&(y.set(e,v),v+=e.byteLength,a?.(E,v),await(g?.read().then(P,w)))};return await(g?.read().then(P,w)),$?null:T}fetchRepresentation=async(t,e,s=0)=>{const{from:i,to:a}=t.initRange;let r,n,o=i,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,i),d=Math.max(n,a))),o=Math.min(o,0),d+=s;const u=await this.fetchRange(t.url,o,d,{method:_t.PARAM});if(!u)return null;const c=new DataView(u,i-o,a-o);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r);else{const s=e.getIndexRange(l);if(s){const e=await this.fetchRange(t.url,s.from,s.to,{method:_t.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,l);return{dataView:new DataView(u),segments:m}};destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Lt=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Ct,xt;!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'}(Ct||(Ct={})),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'}(xt||(xt={}));const Ot={[Ct.EBML]:{type:xt.Master},[Ct.EBMLVersion]:{type:xt.UnsignedInteger},[Ct.EBMLReadVersion]:{type:xt.UnsignedInteger},[Ct.EBMLMaxIDLength]:{type:xt.UnsignedInteger},[Ct.EBMLMaxSizeLength]:{type:xt.UnsignedInteger},[Ct.DocType]:{type:xt.String},[Ct.DocTypeVersion]:{type:xt.UnsignedInteger},[Ct.DocTypeReadVersion]:{type:xt.UnsignedInteger},[Ct.Void]:{type:xt.Binary},[Ct.Segment]:{type:xt.Master},[Ct.SeekHead]:{type:xt.Master},[Ct.Seek]:{type:xt.Master},[Ct.SeekID]:{type:xt.Binary},[Ct.SeekPosition]:{type:xt.UnsignedInteger},[Ct.Info]:{type:xt.Master},[Ct.TimestampScale]:{type:xt.UnsignedInteger},[Ct.Duration]:{type:xt.Float},[Ct.Tracks]:{type:xt.Master},[Ct.Chapters]:{type:xt.Master},[Ct.Cluster]:{type:xt.Master},[Ct.Attachments]:{type:xt.Master},[Ct.Tags]:{type:xt.Master},[Ct.Cues]:{type:xt.Master},[Ct.CuePoint]:{type:xt.Master},[Ct.CueTime]:{type:xt.UnsignedInteger},[Ct.CueTrackPositions]:{type:xt.Master},[Ct.CueTrack]:{type:xt.UnsignedInteger},[Ct.CueClusterPosition]:{type:xt.UnsignedInteger},[Ct.CueRelativePosition]:{type:xt.UnsignedInteger},[Ct.CueDuration]:{type:xt.UnsignedInteger},[Ct.CueBlockNumber]:{type:xt.UnsignedInteger},[Ct.CueCodecState]:{type:xt.UnsignedInteger},[Ct.CueReference]:{type:xt.Master},[Ct.CueRefTime]:{type:xt.UnsignedInteger}},Nt=t=>{const e=t.getUint8(0);let s=0;128&e?s=1:64&e?s=2:32&e?s=3:16&e&&(s=4);const i=Bt(t,s),a=i in Ot,r=a?Ot[i].type:xt.Binary,n=t.getUint8(s);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 d=new DataView(t.buffer,t.byteOffset+s+1,o-1),h=((n&255>>o)<<8*(o-1))+Bt(d),u=s+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?i:'0x'+i.toString(16).toUpperCase(),type:r,value:c,valueSize:h}},Bt=(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},Mt=(t,e)=>{switch(e){case xt.SignedInteger:return t.getInt8(0);case xt.UnsignedInteger:return Bt(t);case xt.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case xt.String:return new TextDecoder('ascii').decode(t);case xt.UTF8:return new TextDecoder('utf-8').decode(t);case xt.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case xt.Master:case xt.Binary:return t;default:n(e)}},Ut=(t,e)=>{let s=0;for(;s<t.byteLength;){const i=new DataView(t.buffer,t.byteOffset+s),a=Nt(i);if(!e(a))return;a.type===xt.Master&&Ut(a.value,e),s=a.value.byteOffset-t.byteOffset+a.valueSize}},Vt=[Ct.Info,Ct.SeekHead,Ct.Tracks,Ct.Chapters,Ct.Cluster,Ct.Cues,Ct.Attachments,Ct.Tags],Ft={validateData:t=>{if(t.getUint32(0)!==Ct.EBML)return!1;let e,s,i;const a=Nt(t);return Ut(a.value,(({tag:t,type:a,value:r})=>(t===Ct.EBMLReadVersion?e=Mt(r,a):t===Ct.DocType?s=Mt(r,a):t===Ct.DocTypeReadVersion&&(i=Mt(r,a)),!0))),(void 0===e||e<=1)&&void 0!==s&&'webm'===s&&(void 0===i||i<=2)},parseInit:t=>{let e,s,i,a,r,n,o=!1,d=!1,h=!1;return Ut(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===Ct.SeekID){const t=Mt(c,u);n=Bt(t)}else t!==Ct.SeekPosition&&(n=void 0);return t===Ct.Segment?(e=c.byteOffset,s=c.byteOffset+l):t===Ct.Info?o=!0:t===Ct.SeekHead?d=!0:t===Ct.TimestampScale?i=Mt(c,u):t===Ct.Duration?a=Mt(c,u):t===Ct.SeekPosition&&n===Ct.Cues?r=Mt(c,u):o&&d&&Vt.includes(t)&&(h=!0),!h})),l(e,'Failed to parse webm Segment start'),l(s,'Failed to parse webm Segment end'),l(a,'Failed to parse webm Segment duration'),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(s/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(a(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let s=!1,a=!1;const r=t=>i(t.time)&&i(t.position),n=[];let o;return Ut(t,(({tag:t,type:e,value:i})=>{switch(t){case Ct.Cues:s=!0;break;case Ct.CuePoint:o&&r(o)&&n.push(o),o={};break;case Ct.CueTime:o&&(o.time=Mt(i,e));break;case Ct.CueTrackPositions:break;case Ct.CueClusterPosition:o&&(o.position=Mt(i,e));break;default:s&&Vt.includes(t)&&(a=!0)}return!(s&&a)})),o&&r(o)&&n.push(o),n.map(((t,s)=>{const{time:i,position:a}=t,r=n[s+1];return{status:O.NONE,time:{from:i,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))}},Ht=new TextDecoder('ascii'),qt={validateData:t=>'ftyp'===Ht.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=(t=>{let e=0,s=t.getUint32(e);e+=4;const i=new DataView(t.buffer,t.byteOffset+e,4),a=Ht.decode(i);e+=4,0===s?s=1/0:1===s&&(e+=8,s=1/0);const r=Math.min(s,t.byteLength)-e+1;return{id:a,size:s,contents:new DataView(t.buffer,t.byteOffset+e,r)}})(t),s=[];let i=0;const a=()=>{const t=e.contents.getUint32(i);return i+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=255&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o+1;for(let t=0;t<d;t++){const t=a(),e=t>>>31,i=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;s.push({status:O.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+i-1}}),h+=o,u+=i}return s}};class Gt{ended$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;subscription=new s;kind;container;containerParser;initData;representations;segments;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;abortController=new kt;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;constructor(t,e,s,i,{fetcher:a,tuning:r}){switch(this.fetcher=a,this.tuning=r,this.container=s,s){case N.MP4:this.containerParser=qt;break;case N.WEBM:this.containerParser=Ft;break;default:n(s)}this.initData=new Map,this.segments=new Map,this.representations=new Map(i.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}async startWith(t){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`);const s=Math.ceil(1e3*e.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.subscription.add(r(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(r(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const i=await this.fetcher.fetchRepresentation(e,this.containerParser,s).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!i)return!1;const{dataView:a,segments:n}=i,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength-s);this.initData.set(t,o);const d=n.filter((t=>t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength)),h=d.at(-1),u=new DataView(a.buffer,a.byteOffset,d.length&&h?Math.min(h.byte.to-a.byteOffset+1,a.byteLength):a.byteLength-s);return await this.appendDataToBuffer(u),this.segments.set(t,n.map((t=>({...t,status:t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength?O.FED:O.NONE})))),this.maintain(0),!0}async switchTo(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)await this.loadAllInitsPromise;else{const e=this.representations.get(t);l(e);const s=await this.fetcher.fetchRepresentation(e,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:i,segments:a}=s,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,r),this.segments.set(t,a)}const e=this.initData.get(t);l(e,`No init buffer for ${t}`),l(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abortController.abort(),this.abortController=new kt,this.abortBuffer(),await this.appendDataToBuffer(e,this.abortController.signal),i(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((t=>{t.status===O.FED&&(t.status=O.NONE)}))}async maintain(t){if(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer)||this.ended$.getValue())return;const e=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);l(e),l(s);const i=s.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=ut(this.sourceBuffer.buffered,t);r=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}const n=this.selectForwardBufferSegments(s,r);n.length&&await this.loadSegments(n,e),!this.allInitsLoaded&&!this.loadAllInitsPromise&&i&&i.status===O.FED&&!n.length&&ut(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=s.at(-1);o&&i===o&&o.status===O.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 s=t.findIndex((({status:t,time:{from:s,to:i}})=>t===O.NONE&&(s>e||s<=e&&i>=e)&&i<=e+this.tuning.forwardBufferTarget));if(-1===s)return[];let i=0;const a=[];for(let e=s;e<t.length&&i<=this.tuning.segmentRequestSize;e++){const s=t[e];if(i+=s.byte.to+1-s.byte.from,s.status===O.NONE)a.push(s);else if([O.DOWNLOADING,O.DOWNLOADED,O.FED].includes(s.status))break}return a}async loadSegments(t,e){if(!t.length)return;const s=t.at(0).byte.from,i=t.at(-1).byte.to;for(const e of t)e.status=O.DOWNLOADING;const{signal:a}=this.abortController,r=(t,s)=>{t.status=O.DOWNLOADED,this.appendDataToBuffer(s,a).then((s=>{!s||a.aborted?t.status=O.NONE:(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=O.FED)}))},n=(e,i)=>{for(const a of t)a.status===O.DOWNLOADING&&a.byte.from-s>=0&&a.byte.to+1-s<=i&&r(a,new DataView(e.buffer,e.byteOffset+a.byte.from-s,a.byte.to+1-a.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((async()=>{if(a.aborted){for(const e of t)e.status===O.DOWNLOADING&&(e.status=O.NONE);return}const o=await this.fetcher.fetchRange(e.url,s,i,{method:_t.PARAM,onProgress:n,signal:a}),d=t.at(-1),h=this.segments.get(e.id)?.at(-1);if(!o)for(const e of t)e.status===O.DOWNLOADING&&(e.status=O.NONE);o&&!a.aborted&&d&&h&&d.status===O.DOWNLOADING&&d===h&&r(d,new DataView(o,d.byte.from-s))})).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=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:s,segments:i}=e,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t,a),this.segments.set(t,i)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async appendDataToBuffer(t,e){if(l(this.sourceBuffer),e&&e.aborted)return!1;if(this.sourceBuffer.updating)return await Gt.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(t,e);try{this.sourceBuffer.appendBuffer(t)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),!1}return await Gt.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(a(this.sourceBuffer)||a(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);l(t);const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),i=this.sourceBuffer.buffered.end(t),a=1e3*(i%1>.9?Math.round(i):i);e.push({from:s,to:a})}for(const s of t){const t=e.some((t=>t.from<=s.time.from&&t.to>=s.time.to));s.status!==O.FED||t||(s.status=O.NONE)}}static async waitForBufferUpdate(t){return new Promise((e=>t?t.addEventListener('update',(()=>e())):e()))}}const Yt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},zt=['timeupdate','progress','play','seeked','stalled'];var Qt,Wt;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Qt||(Qt={}));class jt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new s;fetcher;state$=new pt(Qt.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new It({throughputEstimator:this.throughputEstimator})}async initManifest(t,e){this.element=t,this.subscription.add(r(t,'waiting').subscribe((()=>{t.duration-t.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(Qt.MANIFEST_LOADED);const s=await this.fetcher.fetchManifest(e);let i;try{i=((t,e)=>{const s={video:[],audio:[],text:[]},i=(new DOMParser).parseFromString(t,'application/xml').children[0],a=i.getElementsByTagName('Period')[0].children;let r=0;const n=i.getAttribute('profiles')?.split(',')??[],o=n.includes(x.WEBM_AS_IN_FFMPEG)||n.includes(x.WEBM_AS_IN_SPEC)?N.WEBM:N.MP4;for(const t of a){const i=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),o=t.getAttribute('contentType')??i?.split('/')[0],d=t.getAttribute('profiles')?.split(',')??[],h=t.querySelectorAll('Representation');for(const u of h){const h=u.getAttribute('mimeType')??i,c=u.getAttribute('codecs')??a??'',l=u.getAttribute('contentType')??h?.split('/')[0]??o,p=t.getAttribute('profiles')?.split(',')??[],m=parseInt(u.getAttribute('width')??'',10),f=parseInt(u.getAttribute('height')??'',10),S=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,g=u.getAttribute('frameRate')??'',b=g?Yt(g):void 0,v=`${u.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${f}p`:'audio'===l?`${S}Kbps`:c}`,T=u.querySelector('BaseURL')?.textContent?.trim()??'',y=new URL(T,e).toString(),E=[...n,...d,...p],$=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[w,P]=$.split('-').map((t=>parseInt(t,10))),A={from:w,to:P},k=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[_,D]=k?k.split('-').map((t=>parseInt(t,10))):[],R=k?{from:_,to:D}:void 0;if(!l||!h)continue;const I={video:C.VIDEO,audio:C.AUDIO,text:C.TEXT}[l];I&&s[I].push({id:v,kind:I,profiles:E,initRange:A,indexRange:R,bitrate:S,mime:h,codecs:c,width:m,height:f,fps:b,url:y})}}return{container:o,representations:s}})(s??'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}l(i);const a=({mime:e,codecs:s})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${s}"`));return this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map((([t,e])=>[t,e.filter(a)])))},this.manifest.representations.video.length?this.state$.setState(Qt.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}async initRepresentations(t,e){l(this.manifest),l(this.element),this.state$.startTransitionTo(Qt.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 Gt(C.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.audioBufferManager=new Gt(C.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(o(this.forceEnded$,g({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(b((t=>Object.values(t).every((t=>!0===t)))))).subscribe((()=>{if('open'===this.source?.readyState)try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&await new Promise((t=>this.source?.addEventListener('sourceopen',t)));(await Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])).some((t=>!t))||(this.state$.setState(Qt.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...zt.map((t=>r(this.element,t))),r(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(r(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.tick())}async switchRepresentation(t,e){const s={[C.VIDEO]:this.videoBufferManager,[C.AUDIO]:this.audioBufferManager,[C.TEXT]:null}[t];return l(s),s.switchTo(e)}seek(t){l(this.element),l(this.videoBufferManager),l(this.audioBufferManager),this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),this.element.currentTime=t/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.state$.setState(Qt.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element)return;const t=1e3*this.element.currentTime;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Wt||(Wt={}));const Jt=({id:t,width:e,height:s,bitrate:i,fps:a})=>{const r=et({width:e,height:s});return r&&{id:t,quality:r,bitrate:i,size:{width:e,height:s},fps:a}},Kt=(t,e,s)=>{const i=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(s);return t.at(Math.round(t.length*i/e.length))??t.at(-1)};class Xt{subscription=new s;videoState=new pt(Wt.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new H;videoTracks=[];audioRepresentations;constructor(t){this.params=t,this.video=q(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ct(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new jt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,s=W(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,a));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.firstFrame$,t.firstFrameEvent$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(b(i),m()),t.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(U(this.video,e.isLooped,a)),this.subscription.add(V(this.video,e.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),n(lt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(Wt.PLAYING),J(e.playbackState,w.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(Wt.PAUSED),J(e.playbackState,w.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===Wt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(b((({to:t})=>t===Qt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Wt.READY)}))),this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.elementSize$,r(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),s=this.player.state$.getTransition();if(t===Qt.NONE||!this.videoTracks.length)return;const i=t===Qt.MANIFEST_LOADED&&!s,a=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState(),n=this.videoTracks.find((({track:{id:t}})=>t===r))?.track;e.autoVideoTrackSwitching.getTransition()&&e.autoVideoTrackSwitching.setState(a);const o=ut(this.video.buffered,1e3*this.video.currentTime),d=Math.min(o/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),h=ht(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:d}),u=a?h??n:n??h;if(i){const t=u&&this.videoTracks.find((({track:t})=>t===u))?.representation;l(t);const e=Kt(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);l(e),this.player.initRepresentations(t.id,e.id)}else{const t=u&&this.videoTracks.find((({track:t})=>t===u))?.representation;if(t){const e=Kt(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(C.VIDEO,t.id),e&&this.player.switchRepresentation(C.AUDIO,e.id)}}}))),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),h((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$)),this.textTracksManager.connect(this.video,e,t);const d=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=Jt(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)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const r=a?.to;if(s?.to!==w.PAUSED&&i(r)&&t!==Wt.STOPPED&&e!==w.STOPPED&&this.seek(r),e!==w.STOPPED){if(t===Wt.STOPPED)return this.videoState.startTransitionTo(Wt.READY),void this.prepare();switch(t){case Wt.READY:return void(e===w.PAUSED?(this.videoState.setState(Wt.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(Wt.PLAYING),this.playIfAllowed()));case Wt.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(Wt.PAUSED),this.video.pause()):s?.to===w.PLAYING&&J(this.params.desiredState.playbackState,w.PLAYING));case Wt.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Wt.PLAYING),this.playIfAllowed()):s?.to===w.PAUSED&&J(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}else t!==Wt.STOPPED&&(this.videoState.startTransitionTo(Wt.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(Wt.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(Wt.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0))}))}}var Zt;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Zt||(Zt={}));var te=(t,e=0,s=Zt.OFFSET_P)=>{switch(s){case Zt.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case Zt.PLAYBACK_SHIFT:{if(0===e)return t;const s=new URL(t);return s.searchParams.append('playback_shift',e.toFixed(0)),s.toString()}default:n(s)}return t};var ee;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ee||(ee={}));class se{subscription=new s;loadMediaTimeoutSubscription=new s;videoState=new pt(ee.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case P.MPEG:case P.DASH:case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.HLS:case P.HLS_JS:case P.HLS_ONDEMAND:return!1;case P.HLS_LIVE:case P.DASH_LIVE:case P.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new s;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(h((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(h((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const d=(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 s=new e;t.add(s.pipe(f(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let n=NaN;t.add(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);const r=this.params.desiredState.seekPosition.getTransition();(i(r)&&a(r.to)||Math.abs(e-n)>5)&&s.next(e),n=e}))),t.add(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,s=t.value,i=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(i!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),J(this.params.desiredState.playbackState,w.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:n(s)}})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));d(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(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(ee.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)):(this.videoState.setState(ee.PLAYING),J(this.params.desiredState.playbackState,w.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),s=this.createLoadRequest(e);this.loadMedia(s)}handleRemotePause(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==ee.PAUSED&&t!==ee.PLAYING||(this.videoState.setState(ee.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==ee.PLAYING&&t!==ee.PAUSED||(this.videoState.setState(ee.PLAYING),J(this.params.desiredState.playbackState,w.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)}handleRemoteStop(){this.videoState.getState()!==ee.STOPPED&&this.videoState.setState(ee.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),s={volume:t.volume??e.volume,muted:t.muted??e.muted};s.volume===e.volume&&s.muted==s.muted||this.params.output.volume$.next(s)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:s}=this.params.connection;e.currentTime=t,s.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let s,a,r;switch(t){case P.MPEG:{const i=e[t];l(i);const n=Object.keys(i).sort(((t,e)=>t===e?0:t===j.INVARIANT?1:e===j.INVARIANT?-1:Z(t,e)?1:-1))[0];l(n);const o=i[n];l(o),s=o,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS:case P.HLS_ONDEMAND:{const i=e[t];l(i),s=i.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM_VK:case P.DASH_WEBM:{const i=e[t];l(i),s=i.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS_LIVE:{const i=e[t];l(i),s=te(i.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case P.DASH_LIVE_WEBM:{const i=e[t];l(i),s=i.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case P.HLS_JS:case P.DASH:case P.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 n(t)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,a);o.contentUrl=s,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:h}=this.params.meta;return i(d)&&(o.metadata.title=d),i(h)&&(o.metadata.subtitle=h),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return e.currentTime=s?this.params.output.isLive$.getValue()?0:s.to??0:0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),s=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(v(7e3).subscribe((()=>e('timeout(7000)'))))}));Promise.race([e,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})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(r)};`}),s===w.STOPPED)return void(t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.stop()));if(e)return;const o=r?.to;if(a?.to!==w.PAUSED&&i(o)&&t!==ee.STOPPED)this.seek(o);else switch(s){case w.PLAYING:switch(t){case ee.PLAYING:break;case ee.PAUSED:case ee.READY:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case ee.PLAYING:this.videoState.startTransitionTo(ee.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ee.PAUSED:break;case ee.READY:this.videoState.startTransitionTo(ee.PAUSED),this.videoState.setState(ee.PAUSED);break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:n(t)}break;default:n(s)}}}var ie;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ie||(ie={}));class ae{subscription=new s;videoState=new pt(ie.STOPPED);video;trackUrls={};params;textTracksManager=new H;constructor(t){this.params=t,this.video=q(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],s)=>{const i=s.toString(10);this.trackUrls[i]={track:{quality:t,id:i},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:t,desiredState:e}=this.params,s=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(U(this.video,e.isLooped,s)),this.subscription.add(V(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ie.PLAYING),J(e.playbackState,w.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(ie.PAUSED),J(e.playbackState,w.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&i(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(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(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();l(t,'MpegProvider: track is not selected');const{url:e}=this.trackUrls[t];l(e,`MpegProvider: No url for ${t}`),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(ct(e))}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(ie.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(e===w.STOPPED)return void(t!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.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(ie.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===ie.STOPPED)return this.videoState.startTransitionTo(ie.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=r?.to;switch(s?.to!==w.PAUSED&&i(o)&&this.seek(o),t){case ie.READY:return void(e===w.PAUSED?(this.videoState.setState(ie.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed()));case ie.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.video.pause()):s?.to===w.PLAYING&&J(this.params.desiredState.playbackState,w.PLAYING));case ie.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed()):s?.to===w.PAUSED&&J(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}class re{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],s,i,a,r){this._url=t,this._failoverHosts=e,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(l(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('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 ne{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){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),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 s=0,i=t.length;s<i;s++)e+=t.end(s)-t.start(s);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,s,i,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{i(ne._str2ua(t.substr(o))),o=t.length};this._lastXhr=new re(t.baseURL+'&bytes='+e+'-'+s,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,s)=>this._params.onError(t,e,s)))}))}abort(t){this._lastXhr?.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(),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=ne._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 s=new Uint8Array(t.byteLength+e.byteLength);return s.set(t,0),s.set(e,t.byteLength),s}static _str2ua(t){const e=new Uint8Array(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class oe{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const s=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(s)?0:s)*e},s=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),i='-'===s?.[1]?-1:1;e(s?.[2],i),e(s?.[3],i),e(s?.[4],i),e(s?.[5],i);return 3600*e(s?.[6],i)+60*e(s?.[7],i)+e(s?.[8],i)}getRepresentations(){return this._representations}attachSource(t,e){new re(t,e,(s=>{this.attachManifest(s,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(t))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,s)=>this._params.onError(t,e,s)))}attachManifest(t,e,s){const i=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const s=t.attributes.getNamedItem(e);return s?s.value:null};this._duration=this._parseDurationFromISO8601(String(a(i,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(i.getElementsByTagName('Representation'),(t=>{const i=t.getElementsByTagName('SegmentBase')[0],o=i&&a(i,'indexRange').split('-'),d=i&&i.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const i=t.getAttribute('id')??void 0,a=(s?s+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:i,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(s?s+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Yt(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:s})=>{const i=document.createElement('track');i.setAttribute('src',s),t&&i.setAttribute('id',t),e&&i.setAttribute('srclang',e),this._video.appendChild(i)})),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 s=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(s=>{let i=t.initTo-t.initFrom+1;if(!s.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(s.buffer,0,i);const a=new DataView(s.buffer);i+=12;const r=a.getUint32(i+4,!1);i+=8;let n=a.getUint32(i,!1),o=a.getUint32(i+4,!1)+(t.indexTo+1);i+=8;const d=a.getUint16(i+2,!1);i+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(i,!1)),s=n+a.getUint32(i+4,!1);i+=12,t.refs.push({fromTime:n/r,toTime:s/r,fromOffset:o,toOffset:e-1}),o=e,n=s}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-s)}),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 s=new e;let i,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const s=this._appendVector[String(e.fromTime)];let r;s!==i&&(i=s,this._params.onRepresentationPlay(s));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.end-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.end&&(a=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*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=s.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new ne({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||n(),s.removeEventListener('sourceopen',o),s.removeEventListener('webkitsourceopen',o)};s.addEventListener('sourceopen',o,!1),s.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const i=this._findRef(e);if(i){if(s){this._isLastRef(i)&&e>=i.toTime&&(e=i.fromTime);const t=this._findRef(this._video.currentTime),s=Math.abs(this._video.currentTime-e),a=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||i===t||s<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:i.fromTime}this._appendVector[String(i.fromTime)]=t,this._stream.load(t,i.fromOffset,i.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=i.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 s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(i.toTime<s.end+a){const e=this._findRef(i.toTime);e&&e.toTime<s.end+a?(this._buffer.smartRemove(i.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,i.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 t=this._video.currentTime;this._stream&&!a(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let i=0;i<e.length;i++){const a=e[i];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const s=e[e.length-1];if(t>s.toTime)return s}return s}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const s=e[e.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const s=this._video.buffered.start(e),i=this._video.buffered.end(e);if(t>s&&t<i)return Math.round(10*i)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var de;!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'}(de||(de={}));const he=[de.PAUSED,de.PLAYING];class ue{videoState=new pt(de.STOPPED);subscription=new s;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new H;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=q(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(ct(this.params.source.url)),this.buffer=new Y(this.video),this.dash=new oe({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,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:s})},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:t,desiredState:e}=this.params,s=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=W(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,s));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.firstFrame$,t.firstFrameEvent$),this.subscription.add(d.seeking$.subscribe((()=>{a(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===de.PLAYING||this.videoState.getState()===de.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,s)),this.subscription.add(U(this.video,e.isLooped,s)),this.subscription.add(V(this.video,e.volume,d.volumeState$,s)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(lt(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===de.READY&&this.videoState.setState(de.READY)}),s)).add(d.pause$.subscribe((()=>{this.videoState.setState(de.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(de.PLAYING),J(this.params.desiredState.playbackState,w.PLAYING)}),s)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(de.METADATA_LOADED)}),s)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),s)).add(this.dashLiteEvents.error$.pipe(h((({id:t,message:e,thrown:s})=>({id:`DashLite_${t}`,message:e,thrown:s})))).subscribe(this.params.output.error$)).add(o(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.output.element$,this.elementSize$,r(this.video,'progress')).pipe(h((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),o=this.elementSize$.getValue(),d=n();let h;if(s&&this.params.desiredState.autoVideoTrackSwitching.setState(s.to),!d&&i(a))h=a;else{const s=ut(this.video.buffered,1e3*this.video.currentTime),i=Math.min(s/this.params.tuning.dash.forwardBufferTarget,1);h=ht(e.map((({track:t})=>t)),{container:o,throughput:r,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:i,currentRepresentation:t})?.id}return i(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),c()).subscribe(this.currentRepresentation$,s)).add(g({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(b((t=>t.to===de.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(b(i))}).pipe(m()).subscribe((()=>this.videoState.setState(de.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(b(i),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=ut(this.video.buffered,1e3*this.video.currentTime),s=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||s<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(ct(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:s}=Rt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(s)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(m()).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(b(i)).subscribe(this.handleRepresentationPlay,s)).add(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(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 t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}handleManifestReady=t=>{const e=[];for(const s of t){const t=s.name??s.id??s.height.toString(10),i=et(s),a=s.bandwidth/1e3,r={width:s.width,height:s.height},n=s.fps;if(!i)continue;const o={id:t,quality:i,bitrate:a,size:r,fps:n};e.push({track:o,representation:s})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(de.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t};seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(de.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${s}; seekPositionTransition: ${JSON.stringify(r)};`}),s===w.STOPPED)return void(t!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)));if(e)return;const o=r?.to;switch(a?.to!==w.PAUSED&&i(o)&&he.includes(t)&&this.seek(o),t){case de.STOPPED:return this.videoState.startTransitionTo(de.MANIFEST_LOADED),void this.prepare();case de.MANIFEST_LOADED:return void this.videoState.startTransitionTo(de.INITIAL_REPRESENTATION_SELECTED);case de.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(de.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case de.METADATA_LOADED:return this.videoState.startTransitionTo(de.READY),void this.dash.seek(o??0);case de.READY:return void(s===w.PAUSED?(this.videoState.setState(de.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)):s===w.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()));case de.PLAYING:return void(s===w.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):a?.to===w.PLAYING&&J(this.params.desiredState.playbackState,w.PLAYING));case de.PAUSED:return void(s===w.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):a?.to===w.PAUSED&&J(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}var ce=t=>{let e,s=!1,i=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{i=t<=3,s&&i&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{s=!0,e=()=>a(t),s&&i&&e?.()}}}),!0)},le=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,s]=t.request.range.split('-').map((t=>parseInt(t,10))),i=new URL(t.request.url,location.href);i.searchParams.append('bytes',`${e}-${s}`),t.request.url=i.toString(),t.request.range=void 0}e(t)}}}),!0)};const pe=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class me{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,s=this.dashJsRequestQueue.get(e)??[];s.push(t),this.dashJsRequestQueue.set(e,s)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(t);if(s){e.length&&this.onBigRequestProgress(s);const i=e[0];if(!i||!i.request.range)continue;const[a,r]=pe(i.request);if(a>=s.from&&r<=s.to)continue;this.activeRequests.delete(t)}if(e.length){const s=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,s)}}}abort(t){if(t){const{request:e}=t,s=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),i=this.activeRequests.get(e.url);s&&i&&i.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 s=e.map(pe),i=s[0][0];let a=s[0][1];for(let t=1;t<s.length&&a<this.params.minDataSize;t++){const e=s[t][1];e-i<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===i?Math.max(a,i+this.params.minInitSize):Math.max(a,i+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${i}-${a}`);const n=r.toString(),o=new kt,d=o.signal,h={url:t,from:i,to:a,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(h)));const u=t=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Dt(fetch).fetch(n,{signal:d}).then((t=>{if(!t.ok||!t.body)return void this.onBigRequestError(h);const[e,s]=t.body.tee();this.params.onDownloadStream?.(s);const i=e.getReader(),a=parseInt(t.headers.get('Content-Length')??'',10);h.data=new ArrayBuffer(a);const r=new Uint8Array(h.data),n=async({done:t,value:e})=>{t?this.onBigRequestProgress(h):e&&(r.set(e,h.loaded),h.loaded+=e.byteLength,this.onBigRequestProgress(h),await(i?.read().then(n,me.suppressStreamErrors).catch(u)))};i?.read().then(n,me.suppressStreamErrors).catch(u)}),me.suppressAbort).catch((t=>this.onBigRequestError(h,t))),h}onBigRequestProgress({url:t,from:e,to:s,loaded:i,data:a}){if(!this.activeRequests.has(t)||!a)return;const r=this.dashJsRequestQueue.get(t)??[];for(const n of r){const{request:r}=n,[o,d]=pe(r),h=o>=e&&d<=e+i,u=e>=o&&e+i<d,c=a.slice(o-e,Math.min(d-e+1,i));(h||u)&&(r.requestStartDate=r.requestStartDate??new Date,r.firstByteDate=r.firstByteDate??new Date,r.bytesLoaded=c.byteLength,r.bytesTotal=s-e),h?(r.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==n))),n.success?.(c,'',t),this.dashMetrics?.addHttpRequest(r,t,200,{},[])):u&&n.progress?.({loaded:i,total:s-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:s},i){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:i}),!this.activeRequests.has(t))return;const a=this.dashJsRequestQueue.get(t)??[];for(const t of a){const[a,r]=pe(t.request);(a>=e&&a<s||r>e&&r<=s)&&t?.error?.(t.request,String(i))}if(this.activeRequests.delete(t),i)throw i}onBigRequestAbort({url:t,from:e,to:s}){if(!this.activeRequests.has(t))return;const i=this.dashJsRequestQueue.get(t)??[];for(const t of i){const[i,a]=pe(t.request);(i>=e&&i<s||a>e&&a<=s)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class fe{baseLoader;config;bigRequest;constructor(t,e,s){this.baseLoader=t,this.config=s,this.bigRequest=e,e.setMetrics(s.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(fe.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;fe.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const Se=(t,e)=>{const s=new me(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>s=>({create:i=>{const a=t(s).create(i);return new fe(a,e,i)}}))(e(t),s)}}),!0),()=>s.destroy()};var ge=s=>{const a=new t(1/0),r=new e;let n=NaN,o=!1;return s.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,s=t.progress;t.onload=function(...t){return(t=>{if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),s=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;i(s)&&!isNaN(s)&&a.next(s)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,r.next(Date.now()-n)),s(...t)},n=Date.now(),o=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r}};class be{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){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 ve={};var Te;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Te||(Te={}));const ye=(t,e)=>new p((s=>{const i=t=>s.next(t);return t.on(e,i),()=>t.off(e,i)}));class Ee{subscription=new s;videoState=new pt(Te.DOWNLOADING_LIB);video;player;params;textTracksManager=new H;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new be;destroyBigRequest;constructor(t){this.video=q(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ct(this.params.source.url)),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(ve.MediaPlayer=e.MediaPlayer,ve.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){l(ve.MediaPlayer,'dashjs not loaded'),l(ve.Debug,'dashjs not loaded'),this.player=ve.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?Yt(t.frameRate+''):void 0),!0)));(this.params.format===P.DASH_WEBM||this.params.format===P.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Se(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&&le(this.player),ce(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Te.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,s=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(lt(this.video),this.elementSize$),r(ye(this.player,'error').pipe(h((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),r(ye(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=ye(this.player,'qualityChangeRendered').pipe(b((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(b(i)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(b((({to:t})=>t===Te.STREAM_INITIALIZED)),m()).subscribe((()=>{this.subscription.add(M(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(a(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:n.pipe(h((t=>t?.id))),onError:s}))}),s)),this.subscription.add(M(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),r(ye(this.player,'bufferStateChanged').pipe(b((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(ye(this.player,'fragmentLoadingStarted').pipe(h((t=>ct(t.request.url)))),t.hostname$),r(ye(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:s,availableFrom:i}}})=>{this.isLive$.next(s),this.availableFrom$.next(i.getTime()),s||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),s=et(t),i=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(s){const d={id:e,quality:s,bitrate:i,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(Te.STREAM_INITIALIZED),this.videoState.startTransitionTo(Te.READY)})),r(ye(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),s=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(s,e)})),r(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=ht(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection}),s=this.videoTracks.find((({track:t})=>t===e));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),r(g({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(b(i))}).pipe(b((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>$e(t)))),this.params.output.duration$);const d=ye(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(g({availableFrom:this.availableFrom$.pipe(b(i)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(b((()=>!1===this.isLive$.getValue()))),t.position$),r(ye(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(ye(this.player,'playbackEnded'),t.endedEvent$),r(ye(this.player,'playbackProgress').pipe(h((()=>z(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(ye(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Te.PLAYING),J(e.playbackState,w.PLAYING)})),r(ye(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Te.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(ye(this.player,'playbackPaused'),(()=>{this.videoState.setState(Te.PAUSED),J(e.playbackState,w.PAUSED)})),r(ye(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===Te.READY&&this.videoState.setState(Te.READY)})),r(this.isLive$,t.isLive$),r(lt(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l}=ge(this.player);r(c,this.maxSeekBackTime$),r(l.pipe(m()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(g({isLive:this.isLive$,isShort:t.duration$.pipe(h((t=>t<60)))}),(({isLive:t,isShort:e})=>{const s=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:s}}})})),r(d.pipe(b((t=>t>this.params.tuning.insufficientBufferRuleMargin)),m()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(ye(this.player,'manifestLoaded').pipe(m()).subscribe((()=>{const e=Date.now();this.subscription.add(ye(this.player,'playbackPlaying').pipe(m()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-e)),s))}),s)),this.subscription.add(U(this.video,e.isLooped,s));const{volumeState$:p}=W(this.video);this.subscription.add(V(this.video,e.volume,p,s)),this.subscription.add(p.subscribe(t.volume$,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Te.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Te.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),s=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(s),this.params.output.position$.next($e(s));const i=te(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Zt.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(Te.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Te.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition(),r=this.isLive$.getValue();if(this.videoState.getTransition())return;if(t===Te.DOWNLOADING_LIB||t===Te.STREAM_INITIALIZED)return;const o=a?.to;switch(s?.to!==w.PAUSED&&i(o)&&t!==Te.STOPPED&&e!==w.STOPPED&&(r?this.seek(o+$e(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case w.STOPPED:switch(t){case Te.STOPPED:break;case Te.PLAYING:case Te.PAUSED:case Te.READY:this.stop();break;default:n(t)}break;case w.PLAYING:switch(t){case Te.PLAYING:break;case Te.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next($e(this.liveOffset.getTotalOffset()))):this.seek($e(this.liveOffset.getTotalOffset()))),this.play();break;case Te.READY:this.play();break;case Te.STOPPED:this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case Te.PLAYING:this.pause(),this.liveOffset.pause();break;case Te.PAUSED:break;case Te.READY:this.videoState.setState(Te.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED);break;case Te.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}const $e=t=>-t/1e3;function we(){return S()}function Pe(t){return we()-t}function Ae(t){const e=t.split('/'),s=e.slice(0,e.length-1).join('/'),i=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>i.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=s+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function ke(t,e,s,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,p=0,m=!1,f='arraybuffer',S=7e3,g=2e3,b=()=>{if(c)return;l(h);const t=Pe(h);let e;if(t<g)return e=g-t,void setTimeout(b,e);g*=2,g>S&&(g=S),o&&o.abort(),o=new r,T()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),s&&s()}},T=()=>{h=we(),o=new r,o.open('get',t);let s,i=0,a=0;const p=()=>(l(h),Math.max(h,Math.max(s||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=we();n.updateChunk&&t.loaded>i&&(n.updateChunk(p(),t.loaded-i),i=t.loaded,s=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-i;t&&n.updateChunk&&n.updateChunk(p(),t)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=we(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(m=t,y),withJSONResponse:()=>(f='json',y),withRetryCount:t=>(p=t,y),withRetryInterval:(t,e)=>(i(t)&&(g=t),i(e)&&(S=e),y),withTimeout:t=>(d=t,y),withFinally:t=>(u=t,y),send:T,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return y}class _e{intervals=[];currentRate=0;logger;constructor(t){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,s){return{start:t,end:e,bytes:s}}_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 s=0,i=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)s+=t.end-t.start,i+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;s+=a;const n=t.bytes*a/r;i+=n,t.start=e,t.bytes-=n}}}if(i>0&&s>0){const a=8*i/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(s)} 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,s){return this.intervals.push(this._createInterval(t,e,s)),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 De{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,s,i,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const s=we(),i=s=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=s,t._errorCB?t._errorCB(s):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=ke(e,(i=>{t._complete=1,t._responseData=i,t._downloadTime=we()-s,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(i,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>i('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=we()}_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=we();if(Object.keys(this.activeRequests).length>=t)return!1;const s=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(s>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),s),!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,s,i){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=s,r._retryCB=i,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),s(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Re{paused=!1;autoQuality=!0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new _e(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Ae(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}switchByName(t){let e;for(let s=0;s<this.manifest.length;++s)if(e=this.manifest[s],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=Ae(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 s=t.buffered.length;return 0!==s&&(e=t.buffered.end(s-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',(s=>{this.destroyed||(e(`Video element error: ${t.error?.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,s=e.buffered.length;let i;0!==s&&(i=e.buffered.start(s-1),e.currentTime<i&&(t('Fixup stall'),e.currentTime=i))}_selectQuality(t){const{videoElement:e}=this.params;let s,i,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a);return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||i(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:s,videoElement:i,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s('setting video src'),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{l(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e()})),this.videoPlayStarted=!1,i.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,s){const i=(...a)=>{s.apply(null,a),t.removeEventListener(e,i)};t.addEventListener(e,i)}(i,'progress',(()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new De(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,s)=>{h&&h.abort(),h=ke(this.urlResolver.resolve(t,!1),e,s,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,s)=>{l(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,s,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},S=t=>{const i=s.playbackRate;s.playbackRate!==t&&(e(`Playback rate switch: ${i}=>${t}`),s.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void S(1);const s=we()-6e4;let i=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<s&&i++}this.bufferStates.splice(0,i),e(`update playback rate; minBuffer=${t} drop=${i} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,S(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else S(1)},v=t=>{let s;const a=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,d=t=>s.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{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 h(t,!0)},m=(t,e,s)=>{u&&u.abort(),u=ke(this.urlResolver.resolve(t,!0,this.lowLatency),e,s,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;s=t;const d=Boolean(s.lowLatency);d!==this.lowLatency&&g(d);let u=0;for(let t=0;t<s.dur.length;++t)u+=s.dur[t];u>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/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,e((t=>{const e=a();if(!(e<=0)){if(i(t))for(let s=0;s<e;s++)if(n(s)>t)return h(s);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const i=a(),r=t?t.chunkIdx+1:0,n=r-s.fragIndex;if(!(i<=0)){if(!t||n<0||n-i>10)return e(`Resync: offset=${n} bChunks=${i} chunk=`+JSON.stringify(t)),c();if(!(n>=i))return h(r-s.fragIndex,!1)}}}},T=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:s,logger:i}=this.params;let r,d,h,c,S,g,y,E=v(t.jidxUrl),$=0;const w=()=>{S&&(clearTimeout(S),S=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=$+t,s=we(),i=Math.min(1e4,e-s);$=s;const a=()=>{u||p()&&E.seek((()=>{p()&&($=we(),P(),w())}))};i>0?S=window.setTimeout((()=>{this.paused?w():a()}),i):a()},P=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const s=E.nextChunk(h);if(s){if(h&&s.discontinuity)return i('Detected discontinuity; restarting playback'),void(this.paused?w():(T(),this._initPlayerWith(t)));D(s)}else w()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let a,r,n;const o=s=>{window.setTimeout((()=>{p()&&A(t,e)}),s)};if(this.sourceBuffer.updating)i('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=we(),h=s.currentTime;!this.paused&&s.buffered.length>1&&g===h&&d-y>500&&(i('Stall suspected; trying to fix'),this._fixupStall()),g!==h&&(g=h,y=d);const u=this._getBufferSizeSec();if(u>30)i(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;i('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},k=()=>{d&&r&&(i([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,P()})))},_=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{p()&&f(_(t),((e,s)=>{if(p()){if(s/=1e3,d=e,h=t,o=t.startTS,s){const e=Math.min(10,t.dur/s);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}k()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{r=!0,k()})))};n=!0,E.seek((t=>{p()&&($=we(),t?(c=t,!a(e)||t.startTS>e?D(t):(h=t,P())):w())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:T,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:s}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),i(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return i(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,s=e=>{if(!this.autoQuality)return;let s,i,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(i=this._getBufferSizeSec(),a=e/this.bitrate,i>10&&a>.8||i>15&&a>.5||i>20&&a>.3)?t(`Not switching: buffer=${Math.floor(i)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(s=this._selectQuality(e),s?this._switchToQuality(s):t(`Could not find quality by bitrate ${e}`))},i=(()=>({updateChunk:(t,s)=>{const i=we();if(this.chunkRateEstimator.addInterval(t,i,s)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:s,duration:i-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=i.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Pe(r)<3e4)return;s(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const s=i.updateChunk(t,e);return s&&o(),s},notifySwitch:t=>{const e=we();t<a&&(r=e),a=t}}}_fetchManifest(t,e,s){this.manifestRequest=ke(this.urlResolver.resolve(t,!0),e,s,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;B(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:s,videoElement:i}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,s)=>{t.video&&i.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=s,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}`),s({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 Ie;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ie||(Ie={}));const Le=[Ie.PAUSED,Ie.PLAYING,Ie.READY],Ce=[Ie.PAUSED,Ie.PLAYING,Ie.READY];class xe{subscription=new s;video;videoState=new pt(Ie.STOPPED);dash;representations$=new t([]);textTracksManager=new H;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new be;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=q(t.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(ct(this.params.source.url)),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=W(this.video);this.subscription.add(s.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ie.READY&&this.videoState.setState(Ie.READY)}),e)).add(s.pause$.subscribe((()=>{this.videoState.setState(Ie.PAUSED)}),e)).add(s.playing$.subscribe((()=>{this.videoState.setState(Ie.PLAYING)}),e)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h(Oe)).subscribe(this.params.output.duration$)).add(g({zeroTime:this.zeroTime$.pipe(b(i)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(U(this.video,this.params.desiredState.isLooped,e)).add(V(this.video,this.params.desiredState.volume,s.volumeState$,e)).add(s.volumeState$.subscribe(this.params.output.volume$,e)).add(Q(this.video).subscribe(this.params.output.firstBytesEvent$)).add(G(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Ie.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(w.STOPPED);break;case Ie.MANIFEST_READY:case Ie.READY:break;case Ie.PAUSED:this.params.desiredState.playbackState.setState(w.PAUSED);break;case Ie.PLAYING:this.params.desiredState.playbackState.setState(w.PLAYING);break;default:return n(t.to)}}),e)).add(o(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekPosition.stateChangeStarted$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Re({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(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!s&&i(e)?e:ht(t.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})?.id,r=t.find((({track:t})=>t.id===a))?.representation;l(r),this.dash.startPlay(r,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;l(e),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}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),s=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(s),this.params.output.position$.next(Oe(s)),this.dash.reinit(te(this.params.source.url,s)),this.params.output.seekedEvent$.next()}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,s=[];for(const t of e){const e=t.name??t.index.toString(10),i=et(t.video),a=t.bitrate/1e3,r={...t.video};if(!i)continue;const n={id:e,quality:i,bitrate:a,size:r};s.push({track:n,representation:t})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map((({track:t})=>t))),this.videoState.getTransition()?.to===Ie.MANIFEST_READY&&this.videoState.setState(Ie.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,s=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),i(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:e,duration:s}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,s);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${s}; seekPositionTransition: ${JSON.stringify(r)};`}),s===w.STOPPED)return void(t!==Ie.STOPPED&&(this.videoState.startTransitionTo(Ie.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Ie.STOPPED)));if(e)return;if(Ce.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;i(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}const o=r?.to;if(a?.to!==w.PAUSED&&i(o)&&Le.includes(t))this.seek(o+Oe(this.liveOffset.getTotalPausedTime()));else switch(t){case Ie.STOPPED:return this.videoState.startTransitionTo(Ie.MANIFEST_READY),void this.dash.attachSource(te(this.params.source.url));case Ie.MANIFEST_READY:this.videoState.startTransitionTo(Ie.READY),this.prepare();break;case Ie.READY:return void(s===w.PAUSED?this.videoState.setState(Ie.PAUSED):s===w.PLAYING&&(this.videoState.startTransitionTo(Ie.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Ie.PAUSED)}))));case Ie.PLAYING:return void(s===w.PAUSED&&(this.videoState.startTransitionTo(Ie.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Ie.PAUSED:return void(s===w.PLAYING&&(this.videoState.startTransitionTo(Ie.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(Ie.PAUSED)})),this.params.output.position$.next(Oe(this.liveOffset.getTotalOffset()))):this.seek(Oe(this.liveOffset.getTotalOffset()))));default:return n(t)}}}const Oe=t=>-t/1e3;var Ne=t=>{switch(t){case'mobile':return j.Q_144P;case'lowest':return j.Q_240P;case'low':return j.Q_360P;case'sd':case'medium':return j.Q_480P;case'hd':case'high':return j.Q_720P;case'fullhd':case'full':return j.Q_1080P;case'quadhd':case'quad':return j.Q_1440P;case'ultrahd':case'ultra':return j.Q_2160P}};const Be=t=>{let e=null;if(t.QUALITY&&(e=Ne(t.QUALITY)),!e&&t.RESOLUTION){const[s,i]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=et({width:s,height:i})}return e??null},Me=async(t,e=t)=>{const s=await Dt(fetch).fetch(t),i=(await s.text()).split('\n'),a=[];for(let t=0;t<i.length;t++){const s=i[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const r=Object.fromEntries(s[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=Be(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(i[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Ue;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ue||(Ue={}));class Ve{subscription=new s;videoState=new pt(Ue.STOPPED);video;params;textTracksManager=new H;manifests$=new t([]);constructor(t){this.params=t,this.video=q(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:j.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ct(this.params.source.url)),Me(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,s=t.getState(),i=e.getTransition(),a=i?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=s?'master':a;return s&&!i&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,s=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(U(this.video,e.isLooped,s)),this.subscription.add(V(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Ue.PLAYING),J(e.playbackState,w.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ue.PAUSED),J(e.playbackState,w.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ue.READY&&this.videoState.setState(Ue.READY),this.videoState.getState()===Ue.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&i(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(ct(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Ue.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&i(t.to)&&this.seek(t.to)}),s))),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:s,bandwidth:i,fps:a})=>({id:t,quality:e,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(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 t=this.selectManifest();a(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(Ue.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===w.STOPPED)return void(t!==Ue.STOPPED&&(this.videoState.startTransitionTo(Ue.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(Ue.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===Ue.STOPPED)return this.videoState.startTransitionTo(Ue.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(Ue.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(d&&!a(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const h=d?.to;switch(s?.to!==w.PAUSED&&i(h)&&this.seek(h),t){case Ue.READY:return void(e===w.PAUSED?(this.videoState.setState(Ue.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(Ue.PLAYING),this.playIfAllowed()));case Ue.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(Ue.PAUSED),this.video.pause()):s?.to===w.PLAYING&&J(this.params.desiredState.playbackState,w.PLAYING));case Ue.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Ue.PLAYING),this.playIfAllowed()):s?.to===w.PAUSED&&J(this.params.desiredState.playbackState,w.PAUSED));case Ue.CHANGING_MANIFEST:break;default:return n(t)}}}var Fe;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Fe||(Fe={}));class He{subscription=new s;videoState=new pt(Fe.STOPPED);video;params;textTracksManager=new H;manifests$=new t([]);maxSeekBackTime$;liveOffset=new be;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:j.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Me(te(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(ct(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,s=t.getState(),i=e.getTransition(),a=i?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=s?'master':a;return s&&!i&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,s=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),s)),this.subscription.add(V(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Fe.PLAYING),J(e.playbackState,w.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Fe.PAUSED),J(e.playbackState,w.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Fe.READY&&this.videoState.setState(Fe.READY),this.videoState.getState()===Fe.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h(qe)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&i(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(ct(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Fe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&i(t.to)&&this.seek(t.to)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{const t=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(t||void 0)}),s)),this.subscription.add(g({startTime:this.manifestStartTime$.pipe(b(i)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:s,bandwidth:i,fps:a})=>({id:t,quality:e,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,u(['init'])).pipe(f(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 t=this.selectManifest();if(a(t))return;const e=te(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await Dt(fetch).fetch(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(e).then((t=>{a(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(Fe.PAUSED),this.liveOffset.pause(),J(this.params.desiredState.playbackState,w.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),s=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(s),this.params.output.position$.next(qe(s)),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===w.STOPPED)return void(t!==Fe.STOPPED&&(this.videoState.startTransitionTo(Fe.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(Fe.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===Fe.STOPPED)return this.videoState.startTransitionTo(Fe.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(Fe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const e=qe(this.liveOffset.getTotalOffset());return this.prepare(),void(d&&!a(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const h=d?.to;if(s?.to!==w.PAUSED&&i(h))return this.videoState.startTransitionTo(Fe.READY),this.seek(h+qe(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case Fe.READY:return void(e===w.PAUSED?(this.videoState.setState(Fe.PAUSED),this.liveOffset.pause(),J(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(Fe.PLAYING),this.playIfAllowed()));case Fe.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(Fe.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===w.PLAYING&&J(this.params.desiredState.playbackState,w.PLAYING));case Fe.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Fe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(qe(this.liveOffset.getTotalOffset()))):this.seek(qe(this.liveOffset.getTotalOffset()))):s?.to===w.PAUSED&&(J(this.params.desiredState.playbackState,w.PAUSED),this.liveOffset.pause()));case Fe.CHANGING_MANIFEST:break;default:return n(t)}}}const qe=t=>-t/1e3,Ge={};var Ye;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ye||(Ye={}));const ze=(t,e)=>new p((s=>{const i=(t,e)=>s.next(e);return t.on(e,i),()=>t.off(e,i)}));class Qe{subscription=new s;videoState=new pt(Ye.INITIALIZING);video;params;hls;textTracksManager=new H;trackLevels=new Map;constructor(t){this.video=q(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ct(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.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);import('hls.js').then((e=>{t||(Ge.Hls=e.default,Ge.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){l(Ge.Hls,'hls.js not loaded'),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Ye.STOPPED)}subscribe(){l(Ge.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,s=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=W(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.firstBytes$,e.firstBytesEvent$),n(r.firstFrame$,e.firstFrameEvent$),n(r.seeked$,e.seekedEvent$),this.subscription.add(U(this.video,t.isLooped,s)),this.subscription.add(V(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.hls,Ge.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Ye.PLAYING),J(t.playbackState,w.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ye.PAUSED),J(t.playbackState,w.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ye.READY&&this.videoState.setState(Ye.READY),this.videoState.getState()===Ye.PLAYING&&this.playIfAllowed()}),s)),n(ze(this.hls,Ge.Events.MANIFEST_PARSED).pipe(h((({levels:t})=>t.reduce(((t,e)=>{const s=e.name||e.height.toString(10),{width:i,height:a}=e,r=Ne(e.attrs.QUALITY??'')??et({width:i,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:s.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:i,height:a},fps:n};return this.trackLevels.set(s,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),n(ze(this.hls,Ge.Events.LEVEL_LOADING).pipe(h((({url:t})=>ct(t)))),e.hostname$),this.subscription.add(M(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const d=t=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,c=ze(this.hls,Ge.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(b(i)).subscribe(e.currentVideoTrack$,s),this.subscription.add(M(t.videoTrack,(()=>d(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(a(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const s=this.hls.levels.indexOf(e),i=this.hls.currentLevel,r=this.hls.levels[i];!r||e.bitrate>r.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(h((t=>t?.id))),onError:s})),n(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const p=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(p.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(t===Ye.INITIALIZING)return;const r=a?.to;switch(s?.to!==w.PAUSED&&i(r)&&this.seek(r),e){case w.STOPPED:switch(t){case Ye.STOPPED:break;case Ye.READY:case Ye.PLAYING:case Ye.PAUSED:this.stop();break;default:n(t)}break;case w.PLAYING:switch(t){case Ye.PLAYING:break;case Ye.STOPPED:this.prepare();break;case Ye.READY:case Ye.PAUSED:this.playIfAllowed();break;default:n(t)}break;case w.PAUSED:switch(t){case Ye.PAUSED:break;case Ye.STOPPED:this.prepare();break;case Ye.READY:this.videoState.setState(Ye.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED);break;case Ye.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(Ye.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Ye.PLAYING);await B(this.video)||(this.videoState.setState(Ye.PAUSED),J(this.params.desiredState.playbackState,w.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Ye.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(Ye.STOPPED),J(this.params.desiredState.playbackState,w.STOPPED,!0)}}class We{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const je=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),Je=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Ke=document.createElement('video'),Xe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Ke.canPlayType?.('application/x-mpegurl')||Ke.canPlayType?.('vnd.apple.mpegURL'))},Ze={mp4:Boolean(Ke.canPlayType?.('video/mp4')),webm:Boolean(Ke.canPlayType?.('video/webm'))},ts={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},es=(ts.h264||ts.h265)&&ts.aac,ss=!je,is=Je||je,as=!Xe.hls||!is,rs=3e4,ns=18e4,os=3,ds=100,hs={cacheDuration:12e4},us={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},cs={maxPausedTime:3e4},ls={maxPausedTime:3e4};class ps{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new s;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,s=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new We(s.filter((e=>i(t.sources[e]))).filter((t=>{switch(t){case P.DASH:return Xe.mse&&Ze.mp4&&es&&ss;case P.DASH_SEP:case P.DASH_SEP_VK:return Xe.mse&&Ze.mp4&&es;case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.DASH_LIVE_WEBM:return Xe.mse&&Ze.webm&&ts.vp9&&ts.opus;case P.DASH_LIVE:case P.DASH_ONDEMAND:return Xe.mse&&Ze.mp4&&es;case P.HLS:case P.HLS_LIVE:case P.HLS_ONDEMAND:return Xe.hls&&Ze.mp4&&is;case P.HLS_JS:return Xe.mse&&Ze.mp4&&es&&as;case P.MPEG:return Ze.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new We(t.chromecastFormatsPriority.filter((e=>i(t.sources[e]))))}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 t=this.chooseDestination(),e=this.chooseFormat(t);if(a(e))return void this.handleNoFormatsError(t);let s;try{s=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:e,provider:s,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=this.params.desiredState.seekPosition,s=e.getTransition();s?i(s.from)&&e.startTransitionTo(s.from):e.startTransitionTo(this.providerOutput.position$.getValue()),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case A.SCREEN:return this.createScreenProvider(e);case A.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:s,desiredState:i}=this.params,a=this.providerOutput;switch(t){case P.DASH:{const r=e[t];return l(r),new ue({container:s,source:r,desiredState:i,output:a,config:hs,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP_VK:case P.DASH_WEBM_VK:{const r=e[t];return l(r),new Xt({container:s,source:r,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP:case P.DASH_WEBM:case P.DASH_ONDEMAND:case P.DASH_LIVE_WEBM:{const r=e[t];return l(r),new Ee({container:s,source:r,desiredState:i,output:a,format:t,config:ls,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS:case P.HLS_ONDEMAND:{const r=e[t];return l(r),new Ve({container:s,source:r,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_LIVE:{const r=e[t];return l(r),new He({container:s,source:r,desiredState:i,output:a,config:cs,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_JS:{const r=e[t];return l(r),new Qe({container:s,source:r,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.MPEG:{const r=e[t];return l(r),new ae({container:s,source:r,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_LIVE:{const r=e[t];return l(r),new xe({container:s,source:r,desiredState:i,output:a,config:us,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:s,desiredState:i,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new se({connection:n,meta:a,container:s,source:e,format:t,desiredState:i,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?A.CHROMECAST:A.SCREEN}chooseFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case A.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.next();case A.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case A.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case A.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let e=[],a=0;const r=new s;var n;return r.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:rs,position$:this.providerOutput.position$,providerChanged$:this.current$},new p((e=>{const i=new s,a=v(n.maxTransitionInterval),r=new t(void 0);o(n.desiredPlaybackState$.stateChangeStarted$.pipe(T(a)),n.desiredPlaybackState$.stateChangeEnded$.pipe(T(void 0)),n.providerChanged$.pipe(h((()=>r.getValue())))).subscribe(r);const d=new s;return i.add(d),i.add(r.subscribe((t=>{d.unsubscribe(),t&&d.add(t.subscribe(e))}))),i}))).pipe(T({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),r.add(this.providerError$.pipe(y(ds,{leading:!1,trailing:!0})).subscribe((()=>{const t=Date.now();this.current$.getValue().destination===A.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):i(e[a])&&t<e[a]+ns?(e=[],this.switchToNextProvider()):(e[a]=t,this.reinitProvider()),a=(a+1)%os}))),r}}const ms=(t,e,s)=>s*e+(1-s)*t;class fs{prevReported=void 0;slow;fast;smoothed;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new ot(`raw_${s}`),this.smoothedSeries$=new ot(`smoothed_${s}`),this.reportedSeries$=new ot(`reported_${s}`)}next(t){this.slow=ms(this.slow,t,this.params.emaAlphaSlow),this.fast=ms(this.fast,t,this.params.emaAlphaFast);const e=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=e(this.slow,this.fast),this.smoothed$.next(this.smoothed),(a(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(t),this.smoothedSeries$.next(this.smoothed)}}var Ss;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Ss||(Ss={}));const gs=new Map;let bs=Ss.RUNTIME;const vs=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(vs,'test'),localStorage.removeItem(vs),bs=Ss.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(vs),bs=Ss.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;bs=Ss.RUNTIME}}})();const Ts=(t,e)=>{switch(bs){case Ss.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ss.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ss.RUNTIME:return void gs.set(t,e);default:n(bs)}},ys=window.navigator.connection,Es=()=>{const t=ys?.downlink;if(i(t)&&10!==t)return 1e3*t},$s=()=>{const t=ys?.rtt;if(i(t)&&3e3!==t)return t},ws=(t,e,s)=>{const i=8*s;return i/(i/t+e)};class Ps{throughput;rtt;subscription=new s;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const s=Ps.load('one_video_throughput')||(e.useBrowserEstimation?Es():void 0)||5e3,a=Ps.load('one_video_rtt')??(e.useBrowserEstimation?$s():void 0)??0;if(this.throughput$=new t(s),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(ws(s,a,e.rttPenaltyRequestSize)),this.throughput=new fs({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new fs({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=Es();t&&this.throughput.next(t);const e=$s();i(e)&&this.rtt.next(e)};ys&&'onchange'in ys&&this.subscription.add(r(ys,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ts('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ts('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(g({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(h((({throughput:t,rtt:s})=>ws(t,s,e.rttPenaltyRequestSize))),b((t=>{const s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-s)/s>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let e=0,i=S();const a=new s;switch(this.subscription.add(a),t.readyState){case 4:break;case 3:case 2:a.add(r(t,'progress').pipe(m()).subscribe((t=>{e=t.loaded,i=S()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,i=S()})))}a.add(r(t,'loadend').subscribe((s=>{if(200===t.status){const t=s.loaded,a=S(),r=t-e,n=a-i;this.addRawSpeed(r,n)}a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let s=0;const i=S();let a=0,r=S();const n=s=>{e.releaseLock(),t.cancel(`Throughput Estimator error: ${s}`).catch((()=>{}))},o=async({done:t,value:d})=>{t?this.addRawSpeed(s,S()-i):d&&(s+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&S()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,S()-r),a=0,r=S()),await(e?.read().then(o,n)))};e?.read().then(o,n)}addRawSpeed(t,e){if(Ps.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const s=8*t/e;return!(!s||!isFinite(s))&&(!(s>1e6)&&(!(s<30)&&(!(t<10240)&&!(e<=20))))}static load(t){const e=(t=>{switch(bs){case Ss.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Ss.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Ss.RUNTIME:return gs.get(t);default:n(bs)}})(t);if(i(e))return parseInt(e,10)??void 0}}const As=(t=(t=>t))=>({playbackState:e,seekPosition:r,playbackAbort$:n,position$:d})=>new p((u=>{let c;const l=e.transitionEnded$.pipe(b((t=>(t.from===w.PAUSED||t.from===w.STOPPED)&&t.to===w.PLAYING))),p=e.stateChangeEnded$.pipe(b((t=>t.from===w.PLAYING&&t.to===w.PAUSED))),m=r.stateChangeEnded$.pipe(b((t=>i(t.to)&&(e.getTransition()?.from??e.getState())===w.PLAYING))),f=r.stateChangeEnded$.pipe(b((t=>a(t.to)&&(e.getTransition()?.from??e.getState())===w.PLAYING))),S=o(l,f).pipe(h((()=>t(d.getValue())))),g=o(p,m,n).pipe(h((()=>t(d.getValue()))));return(new s).add(S.subscribe((e=>{c=t(e)}))).add(g.subscribe((e=>{if(a(c))return;const s={start:c,end:t(e)};c=void 0,u.next(s)})))})),ks=As((t=>t)),_s=As((t=>Math.round(1e3*t)+Date.now())),Ds={[A.SCREEN]:{vod:[P.HLS,P.HLS_ONDEMAND,P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS_JS,P.MPEG],live:[P.HLS_LIVE,P.DASH_LIVE,P.DASH_LIVE_WEBM]},[A.CHROMECAST]:{vod:[P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS,P.HLS_ONDEMAND,P.MPEG],live:[P.HLS_LIVE]}};class Rs{subscription=new s;domContainer;providerContainer;chromecastInitializer;logger=new E;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new pt(w.STOPPED),seekPosition:new pt(void 0),volume:new pt({volume:1,muted:!1}),videoTrack:new pt(void 0),autoVideoTrackSwitching:new pt(!0),isLooped:new pt(!1),externalTextTracks:new pt([]),currentTextTrack:new pt(void 0),textTrackCuesSettings:new pt({})};info={playbackState$:new t(w.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),currentBuffer$:new t(void 0),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(k.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};events={started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,log$:new e};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:rt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const s of Object.keys(R)){const i=R[s],a=t[s];Array.isArray(i)&&Array.isArray(a)?e[s]=a:e[s]='object'==typeof i&&'object'==typeof a?{...i,...a}:a??i}return e})(t),this.chromecastInitializer=new I({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ps(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,s)=>{const i=Reflect.get(t,e,s);return'function'!=typeof i?i:(...s)=>{try{return i.apply(t,s)}catch(t){const i=s.map((t=>JSON.stringify(t,((t,e)=>{const s=typeof e;return['number','string','boolean'].includes(s)?e:null===e?null:`<${s}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${i.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new ps({screenFormatsPriority:[...Ds[A.SCREEN].live,...Ds[A.SCREEN].vod],chromecastFormatsPriority:[...Ds[A.CHROMECAST].live,...Ds[A.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},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(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==w.PLAYING&&t.startTransitionTo(w.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==w.PAUSED&&t.startTransitionTo(w.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==w.STOPPED&&t.startTransitionTo(w.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()===k.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()===k.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const s=e.find((e=>e.quality===t));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){return(void 0===t||this.providerContainer?.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(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(a(t))return this.info.position$.getValue();const e=this.desiredState.seekPosition.getTransition(),s=e?.to??e?.from;return i(s)?s:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(h((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$));const t=new s;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(b((t=>t.to===w.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((t=>t.to===w.PLAYING||t.to===w.PAUSED)),f(0),m()).subscribe((t=>{const e=t.to===w.PLAYING,s=this.info.muted$.getValue(),i=e?s?_.SuccessWithoutSound:_.SuccessWithSound:_.Failed;this.events.startAttempt$.next(i)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((t=>t.to===w.PLAYING)),f(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 w.PAUSED:this.events.willPause$.next();break;case w.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition()?.to;i(t)&&(this.desiredState.seekPosition.setState(t),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition();i(t?.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(e.current$.pipe(h((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(h((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(h((t=>t.map((({quality:t})=>t)).sort(((t,e)=>st(t)?1:st(e)?-1:X(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const s of t)s.fps&&(e[s.quality]=s.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const s=e.providerOutput.element$.getValue();s&&this.info.intrinsicVideoSize$.next({width:s.videoWidth,height:s.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(h((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(h((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekPosition:t,position$:e})=>o(t.stateChangeStarted$.pipe(h((t=>t.to)),b(i)),e.pipe(b((()=>a(t.getState())&&a(t.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(T(!0)),e.providerOutput.seekedEvent$.pipe(T(!1))).pipe(c()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(h((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 n=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>n.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>n.next(!0))));const d=new t(!0);this.subscription.add(e.current$.subscribe((()=>d.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((({to:t})=>t===w.PLAYING)),m()).subscribe((()=>d.next(!1))));let u=0;const p=o(e.providerOutput.isBuffering$,n,d).pipe(h((()=>{const t=e.providerOutput.isBuffering$.getValue(),s=n.getValue()||d.getValue();return t&&!s})),c());this.subscription.add(p.subscribe((t=>{t?u=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(u),this.info.isStalled$.next(!1))})));const f=new s;this.subscription.add(f);const S=o(r(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(b((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),f.unsubscribe(),t){case!0:f.add(_s({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:S,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:f.add(ks({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:S,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(h((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new s;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(b((t=>t.length>0)),m()).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=ht(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(h((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(){const t=this.providerContainer?.providerOutput;l(this.providerContainer),l(t),at={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{it=t})),this.providerContainer.current$.subscribe((({type:t})=>nt('provider',t))),t.duration$.subscribe((t=>nt('duration',t))),t.availableVideoTracks$.pipe(b((t=>!!t.length)),m()).subscribe((t=>nt('tracks',t))),this.events.fatalError$.subscribe(new ot('fatalError')),this.events.managedError$.subscribe(new ot('managedError')),t.position$.subscribe(new ot('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new ot('quality')),t.currentBuffer$.subscribe(new ot('buffer')),t.isBuffering$.subscribe(new ot('isBuffering'))].forEach((t=>this.subscription.add(t))),nt('codecs',Object.keys(ts).filter((t=>ts[t])))}}const Is='@vkontakte/videoplayer-core@2.0.42';export{k as ChromecastState,D as HttpConnectionType,w as PlaybackState,Rs as Player,Is as SDK_VERSION,_ as StartStatus,P as VideoFormat,j as VideoQuality};
6
+ import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as a,fromEvent as r,assertNever as n,merge as o,tap as d,map as h,observableFrom as u,filterChanged as c,assertNonNullable as l,Observable as p,once as m,debounce as f,now as S,combine as g,filter as b,timeout as v,mapTo as y,throttle as T,Logger as E}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import $ from'lodash/debounce';var w,P,A,k,_,D;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(w||(w={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(P||(P={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(A||(A={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(k||(k={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(D||(D={}));const R={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:[P.DASH_WEBM,P.DASH_SEP,P.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 I{connection$=new t(void 0);castState$=new t(k.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(k.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;var i;s(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>t,s.onerror=()=>e,document.body.appendChild(s)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();a(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();a(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(r(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(r(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),h((t=>t.castState))),u([i.getCastState()])).pipe(c(),h(L),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{const n=r===k.CONNECTED,o=s(this.connection$.getValue());if(n&&!o){const s=i.getCurrentSession();l(s);const r=s.getCastDevice(),n=s.getMediaSession()?.media.contentId;(a(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:r}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===k.CONNECTED?s(this.connection$.getValue())?k.CONNECTED:k.AVAILABLE:r)})))}initializeCastApi(){let t,e,i;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:i}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const L=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return k.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return k.AVAILABLE;case cast.framework.CastState.CONNECTING:return k.CONNECTING;case cast.framework.CastState.CONNECTED:return k.CONNECTED;default:return n(t)}};var x,C,O,N;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(x||(x={})),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'}(C||(C={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(O||(O={})),function(t){t.MP4='mp4',t.WEBM='webm'}(N||(N={}));var B=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};const M=(t,e,s,{equal:r=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=a(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();r(e,i)&&t.setState(e)}),o)),r(h,d)||(s(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),c},U=(t,e,i)=>M(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),V=(t,e,i,a)=>M(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),F=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class H{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const a=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(M(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(h((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(M(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(M(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(r(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(r(t,'addtrack'),r(t,'removetrack'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(r(t,'change'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),h((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(r(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const i=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',i))};t.track?.addEventListener('cuechange',i)}))),this.subscription.add(r(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(H.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(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&F(e,t)?e.mode='showing':e.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(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var q=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},G=t=>new p((e=>{let s=0;return(new i).add(r(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(r(t,'loadeddata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(m());class Y{_buffer=[];_source;constructor(t){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:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var z=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{start:s,end:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{start:s,end:a}},Q=t=>new p((e=>{let s=0;return(new i).add(r(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(r(t,'loadedmetadata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(m());const W=t=>{const i=(e,i=(()=>{}))=>r(t,e).pipe(h(i)),a=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>r(t,e)))).pipe(h((()=>t.readyState<3)),c()),n=o(r(t,'progress'),r(t,'timeupdate')).pipe(h((()=>z(t.buffered,t.currentTime)))),d=r(t,'volumechange').pipe(f(0),h((()=>({muted:t.muted,volume:t.volume})))),u=r(t,'error').pipe(h((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=i('timeupdate',(()=>t.currentTime)),p=new e;let m;return l.subscribe((e=>{t.loop&&s(m)&&s(e)&&m>=t.duration-.3&&e<=.3&&p.next(m),m=e})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:p,error$:u,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:i('durationchange',(()=>t.duration)),isBuffering$:a,currentBuffer$:n,volumeState$:d,firstBytes$:Q(t),firstFrame$:G(t)}};var j;!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(j||(j={}));var J=t=>{switch(t){case'mobile':return j.Q_144P;case'lowest':return j.Q_240P;case'low':return j.Q_360P;case'sd':case'medium':return j.Q_480P;case'hd':case'high':return j.Q_720P;case'fullhd':case'full':return j.Q_1080P;case'quadhd':case'quad':return j.Q_1440P;case'ultrahd':case'ultra':return j.Q_2160P}},K=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const X={[j.Q_144P]:{width:256,height:144},[j.Q_240P]:{width:428,height:240},[j.Q_360P]:{width:640,height:360},[j.Q_480P]:{width:854,height:480},[j.Q_720P]:{width:1280,height:720},[j.Q_1080P]:{width:1920,height:1080},[j.Q_1440P]:{width:2560,height:1440},[j.Q_2160P]:{width:3840,height:2160},[j.Q_4320P]:{width:7680,height:4320}},Z=(t,e)=>X[t].height>X[e].height,tt=(t,e)=>X[t].height>=X[e].height,et=(t,e)=>X[t].height<X[e].height,it=(t,e)=>X[t].height<=X[e].height,st=Object.keys(X).sort(((t,e)=>et(t,e)?-1:1)),at=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return st.find((t=>{const e=X[t];return e.width>=s&&e.height>=i}))},rt=t=>t===j.INVARIANT;let nt=!1,ot={};const dt=t=>{t(ot)},ht=(t,e)=>{nt&&(ot.meta=ot.meta??{},ot.meta[t]=e)};class ut{name;constructor(t){this.name=t}next(t){if(!nt)return;ot.series=ot.series??{};const e=ot.series[this.name]??[];e.push([Date.now(),t]),ot.series[this.name]=e}}const ct=new ut('best_bitrate'),lt=(t,{container:e,throughput:i,tuning:r,limits:n,forwardBufferHealth:o,currentRepresentation:d})=>{const h=r.usePixelRatio?window.devicePixelRatio??1:1,u=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},c=u&&at(u),l=t.filter((t=>!rt(t.quality))).sort(((t,e)=>Z(t.quality,e.quality)?-1:1)),p=l.at(-1)?.quality,m=l.at(0)?.quality,f=a(n)||s(n.min)&&s(n.max)&&et(n.max,n.min)||s(n.min)&&m&&Z(n.min,m)||s(n.max)&&p&&et(n.max,p),S=l.filter((t=>{const e=!c||et(t.quality,c),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i>=t.bitrate*(u=o??.5,l=r.bitrateFactorAtEmptyBuffer,p=r.bitrateFactorAtFullBuffer,(l-p)*Math.pow(2,-10*u)+p);var u,l,p;const m=!r.lazyQualitySwitch||!d||(o??.5)>=.5||(t.size?.height||0)<=(d?.height||0),S=f||(a(n.max)||it(t.quality,n.max))&&(a(n.min)||tt(t.quality,n.min));return e&&h&&m&&S}))[0];return S&&S.bitrate&&ct.next(S.bitrate),S??l[Math.ceil((l.length-1)/2)]??t[0]};var pt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)},mt=t=>new URL(t).hostname;const ft=(t,e=300)=>new p((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver($((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()}));class St{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}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(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var gt={};function bt(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function vt(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 yt(t,e,i){return e&&vt(t.prototype,e),i&&vt(t,i),t}function Tt(t){return(Tt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Et(t,e){return(Et=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function $t(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function wt(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?$t(t):e}function Pt(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=Tt(t);if(e){var a=Tt(this).constructor;i=Reflect.construct(s,arguments,a)}else i=s.apply(this,arguments);return wt(this,i)}}function At(t,e,i){return(At='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=Tt(t)););return t}(t,e);if(s){var a=Object.getOwnPropertyDescriptor(s,e);return a.get?a.get.call(i):a.value}})(t,e,i||t)}Object.defineProperty(gt,'__esModule',{value:!0});var kt=function(){function t(){bt(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return yt(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,a=i.length;s<a;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 a=e[i];try{a.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}}]),t}(),_t=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&&Et(t,e)}(i,kt);var e=Pt(i);function i(){var t;return bt(this,i),(t=e.call(this)).listeners||kt.call($t(t)),Object.defineProperty($t(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty($t(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return yt(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)),At(Tt(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),Dt=function(){function t(){bt(this,t),Object.defineProperty(this,'signal',{value:new _t,writable:!0,configurable:!0})}return yt(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&&(Dt.prototype[Symbol.toStringTag]='AbortController',_t.prototype[Symbol.toStringTag]='AbortSignal');var Rt=gt.AbortController=Dt;gt.AbortSignal=_t;var It,Lt=gt.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e,i=t,s=i.fetch,a=i.Request,r=void 0===a?s.Request:a,n=i.AbortController,o=i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,d=void 0!==o&&o;if(!((e={fetch:s,Request:r,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:d}).__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),1):'function'==typeof e.Request&&!e.Request.prototype.hasOwnProperty('signal')||!e.AbortController))return{fetch:s,Request:h};var h=r;(h&&!h.prototype.hasOwnProperty('signal')||d)&&((h=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 u=s;return{fetch:function(t,e){var i=h&&h.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 a=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,u(t,e)])}return u(t,e)},Request:h}},xt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?D.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(It||(It={}));class Ct{throughputEstimator;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new Rt;subscription=new i;constructor({throughputEstimator:t}={}){this.throughputEstimator=t}onHeadersReceived(t){const{type:e,reused:i}=xt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchManifest(t){const e=await Lt(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Ot);return e?(this.onHeadersReceived(e.headers),e.text()):null}async fetchRange(t,e,i,{method:s=It.HEADER,onProgress:a,signal:d}={}){let h=t;const u=new Headers;switch(s){case It.HEADER:u.append('Range',`${e}-${i}`);break;case It.PARAM:{const t=new URL(h,location.href);t.searchParams.append('bytes',`${e}-${i}`),h=t.toString();break}default:n(s)}let c=this.abortAllController.signal;if(d){const t=new Rt;this.subscription.add(o(r(this.abortAllController.signal,'abort'),r(d,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||d.aborted)&&t.abort(),c=t.signal}const l=S(),p=await Lt(fetch).fetch(h,{headers:u,signal:c}).catch(Ot);if(this.throughputEstimator?.addRawRtt(S()-l),!p)return null;if(!p.ok||!p.body)return Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const[m,f]=p.body.tee(),g=m.getReader();this.throughputEstimator?.trackStream(f);const b=parseInt(p.headers.get('Content-Length')??'',10);let v=0;const y=new ArrayBuffer(b),T=new Uint8Array(y),E=new DataView(y);let $=!1;const w=t=>{$=!0,Ot(t)},P=async({done:t,value:e})=>{0===v&&this.lastRequestFirstBytes$.next(S()-l),t?a?.(E,v):e&&(T.set(e,v),v+=e.byteLength,a?.(E,v),await(g?.read().then(P,w)))};return await(g?.read().then(P,w)),$?null:y}fetchRepresentation=async(t,e,i=0)=>{const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0),d+=i;const u=await this.fetchRange(t.url,o,d,{method:It.PARAM});if(!u)return null;const c=new DataView(u,s-o,a-o);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r);else{const i=e.getIndexRange(l);if(i){const e=await this.fetchRange(t.url,i.from,i.to,{method:It.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,l);return{dataView:new DataView(u),segments:m}};destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ot=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Nt,Bt;!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'}(Nt||(Nt={})),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'}(Bt||(Bt={}));const Mt={[Nt.EBML]:{type:Bt.Master},[Nt.EBMLVersion]:{type:Bt.UnsignedInteger},[Nt.EBMLReadVersion]:{type:Bt.UnsignedInteger},[Nt.EBMLMaxIDLength]:{type:Bt.UnsignedInteger},[Nt.EBMLMaxSizeLength]:{type:Bt.UnsignedInteger},[Nt.DocType]:{type:Bt.String},[Nt.DocTypeVersion]:{type:Bt.UnsignedInteger},[Nt.DocTypeReadVersion]:{type:Bt.UnsignedInteger},[Nt.Void]:{type:Bt.Binary},[Nt.Segment]:{type:Bt.Master},[Nt.SeekHead]:{type:Bt.Master},[Nt.Seek]:{type:Bt.Master},[Nt.SeekID]:{type:Bt.Binary},[Nt.SeekPosition]:{type:Bt.UnsignedInteger},[Nt.Info]:{type:Bt.Master},[Nt.TimestampScale]:{type:Bt.UnsignedInteger},[Nt.Duration]:{type:Bt.Float},[Nt.Tracks]:{type:Bt.Master},[Nt.Chapters]:{type:Bt.Master},[Nt.Cluster]:{type:Bt.Master},[Nt.Attachments]:{type:Bt.Master},[Nt.Tags]:{type:Bt.Master},[Nt.Cues]:{type:Bt.Master},[Nt.CuePoint]:{type:Bt.Master},[Nt.CueTime]:{type:Bt.UnsignedInteger},[Nt.CueTrackPositions]:{type:Bt.Master},[Nt.CueTrack]:{type:Bt.UnsignedInteger},[Nt.CueClusterPosition]:{type:Bt.UnsignedInteger},[Nt.CueRelativePosition]:{type:Bt.UnsignedInteger},[Nt.CueDuration]:{type:Bt.UnsignedInteger},[Nt.CueBlockNumber]:{type:Bt.UnsignedInteger},[Nt.CueCodecState]:{type:Bt.UnsignedInteger},[Nt.CueReference]:{type:Bt.Master},[Nt.CueRefTime]:{type:Bt.UnsignedInteger}},Ut=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=Vt(t,i),a=s in Mt,r=a?Mt[s].type:Bt.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 d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+Vt(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,value:c,valueSize:h}},Vt=(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},Ft=(t,e)=>{switch(e){case Bt.SignedInteger:return t.getInt8(0);case Bt.UnsignedInteger:return Vt(t);case Bt.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Bt.String:return new TextDecoder('ascii').decode(t);case Bt.UTF8:return new TextDecoder('utf-8').decode(t);case Bt.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Bt.Master:case Bt.Binary:return t;default:n(e)}},Ht=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Ut(s);if(!e(a))return;a.type===Bt.Master&&Ht(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},qt=[Nt.Info,Nt.SeekHead,Nt.Tracks,Nt.Chapters,Nt.Cluster,Nt.Cues,Nt.Attachments,Nt.Tags],Gt={validateData:t=>{if(t.getUint32(0)!==Nt.EBML)return!1;let e,i,s;const a=Ut(t);return Ht(a.value,(({tag:t,type:a,value:r})=>(t===Nt.EBMLReadVersion?e=Ft(r,a):t===Nt.DocType?i=Ft(r,a):t===Nt.DocTypeReadVersion&&(s=Ft(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return Ht(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===Nt.SeekID){const t=Ft(c,u);n=Vt(t)}else t!==Nt.SeekPosition&&(n=void 0);return t===Nt.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Nt.Info?o=!0:t===Nt.SeekHead?d=!0:t===Nt.TimestampScale?s=Ft(c,u):t===Nt.Duration?a=Ft(c,u):t===Nt.SeekPosition&&n===Nt.Cues?r=Ft(c,u):o&&d&&qt.includes(t)&&(h=!0),!h})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(a,'Failed to parse webm Segment duration'),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(a(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,a=!1;const r=t=>s(t.time)&&s(t.position),n=[];let o;return Ht(t,(({tag:t,type:e,value:s})=>{switch(t){case Nt.Cues:i=!0;break;case Nt.CuePoint:o&&r(o)&&n.push(o),o={};break;case Nt.CueTime:o&&(o.time=Ft(s,e));break;case Nt.CueTrackPositions:break;case Nt.CueClusterPosition:o&&(o.position=Ft(s,e));break;default:i&&qt.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:O.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))}},Yt=new TextDecoder('ascii'),zt={validateData:t=>'ftyp'===Yt.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),a=Yt.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e+1;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}})(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=255&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o+1;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:O.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i}};class Qt{ended$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;subscription=new i;kind;container;containerParser;initData;representations;segments;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;abortController=new Rt;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;constructor(t,e,i,s,{fetcher:a,tuning:r}){switch(this.fetcher=a,this.tuning=r,this.container=i,i){case N.MP4:this.containerParser=zt;break;case N.WEBM:this.containerParser=Gt;break;default:n(i)}this.initData=new Map,this.segments=new Map,this.representations=new Map(s.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}async startWith(t){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`);const i=Math.ceil(1e3*e.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.subscription.add(r(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(r(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const s=await this.fetcher.fetchRepresentation(e,this.containerParser,i).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return!1;const{dataView:a,segments:n}=s,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength-i);this.initData.set(t,o);const d=n.filter((t=>t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength)),h=d.at(-1),u=new DataView(a.buffer,a.byteOffset,d.length&&h?Math.min(h.byte.to-a.byteOffset+1,a.byteLength):a.byteLength-i);return await this.appendDataToBuffer(u),this.segments.set(t,n.map((t=>({...t,status:t.byte.from>=a.byteOffset&&t.byte.to<a.byteOffset+a.byteLength?O.FED:O.NONE})))),this.maintain(0),!0}async switchTo(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)await this.loadAllInitsPromise;else{const e=this.representations.get(t);l(e);const i=await this.fetcher.fetchRepresentation(e,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!i)return;const{dataView:s,segments:a}=i,r=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t,r),this.segments.set(t,a)}const e=this.initData.get(t);l(e,`No init buffer for ${t}`),l(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abortController.abort(),this.abortController=new Rt,this.abortBuffer(),await this.appendDataToBuffer(e,this.abortController.signal),s(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((t=>{t.status===O.FED&&(t.status=O.NONE)}))}async maintain(t){if(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer)||this.ended$.getValue())return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);l(e),l(i);const s=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=pt(this.sourceBuffer.buffered,t);r=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}const n=this.selectForwardBufferSegments(i,r);n.length&&await this.loadSegments(n,e),!this.allInitsLoaded&&!this.loadAllInitsPromise&&s&&s.status===O.FED&&!n.length&&pt(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=i.at(-1);o&&s===o&&o.status===O.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===O.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.forwardBufferTarget));if(-1===i)return[];let s=0;const a=[];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===O.NONE)a.push(i);else if([O.DOWNLOADING,O.DOWNLOADED,O.FED].includes(i.status))break}return a}async loadSegments(t,e){if(!t.length)return;const i=t.at(0).byte.from,s=t.at(-1).byte.to;for(const e of t)e.status=O.DOWNLOADING;const{signal:a}=this.abortController,r=(t,i)=>{t.status=O.DOWNLOADED,this.appendDataToBuffer(i,a).then((i=>{!i||a.aborted?t.status=O.NONE:(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=O.FED)}))},n=(e,s)=>{for(const a of t)a.status===O.DOWNLOADING&&a.byte.from-i>=0&&a.byte.to+1-i<=s&&r(a,new DataView(e.buffer,e.byteOffset+a.byte.from-i,a.byte.to+1-a.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((async()=>{if(a.aborted){for(const e of t)e.status===O.DOWNLOADING&&(e.status=O.NONE);return}const o=await this.fetcher.fetchRange(e.url,i,s,{method:It.PARAM,onProgress:n,signal:a}),d=t.at(-1),h=this.segments.get(e.id)?.at(-1);if(!o)for(const e of t)e.status===O.DOWNLOADING&&(e.status=O.NONE);o&&!a.aborted&&d&&h&&d.status===O.DOWNLOADING&&d===h&&r(d,new DataView(o,d.byte.from-i))})).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=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,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,a),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async appendDataToBuffer(t,e){if(l(this.sourceBuffer),e&&e.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return await Qt.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(t,e);try{this.sourceBuffer.appendBuffer(t)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),!1}return await Qt.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(a(this.sourceBuffer)||a(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);l(t);const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),a=1e3*(s%1>.9?Math.round(s):s);e.push({from:i,to:a})}for(const i of t){const t=e.some((t=>t.from<=i.time.from&&t.to>=i.time.to));i.status!==O.FED||t||(i.status=O.NONE)}}static async waitForBufferUpdate(t){return new Promise((e=>t?t.addEventListener('update',(()=>e())):e()))}}const Wt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},jt=['timeupdate','progress','play','seeked','stalled'];var Jt,Kt;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Jt||(Jt={}));class Xt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new i;fetcher;state$=new St(Jt.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new Ct({throughputEstimator:this.throughputEstimator})}async initManifest(t,e){this.element=t,this.subscription.add(r(t,'waiting').subscribe((()=>{t.duration-t.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(Jt.MANIFEST_LOADED);const i=await this.fetcher.fetchManifest(e);let s;try{s=((t,e)=>{const i={video:[],audio:[],text:[]},s=(new DOMParser).parseFromString(t,'application/xml').children[0],a=s.getElementsByTagName('Period')[0].children;let r=0;const n=s.getAttribute('profiles')?.split(',')??[],o=n.includes(C.WEBM_AS_IN_FFMPEG)||n.includes(C.WEBM_AS_IN_SPEC)?N.WEBM:N.MP4;for(const t of a){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),o=t.getAttribute('contentType')??s?.split('/')[0],d=t.getAttribute('profiles')?.split(',')??[],h=t.querySelectorAll('Representation');for(const u of h){const h=u.getAttribute('mimeType')??s,c=u.getAttribute('codecs')??a??'',l=u.getAttribute('contentType')??h?.split('/')[0]??o,p=t.getAttribute('profiles')?.split(',')??[],m=parseInt(u.getAttribute('width')??'',10),f=parseInt(u.getAttribute('height')??'',10),S=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,g=u.getAttribute('frameRate')??'',b=u.getAttribute('quality')??void 0,v=g?Wt(g):void 0,y=`${u.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${f}p`:'audio'===l?`${S}Kbps`:c}`,T=u.querySelector('BaseURL')?.textContent?.trim()??'',E=new URL(T,e).toString(),$=[...n,...d,...p],w=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[P,A]=w.split('-').map((t=>parseInt(t,10))),k={from:P,to:A},_=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[D,R]=_?_.split('-').map((t=>parseInt(t,10))):[],I=_?{from:D,to:R}:void 0;if(!l||!h)continue;const L={video:x.VIDEO,audio:x.AUDIO,text:x.TEXT}[l];L&&i[L].push({id:y,kind:L,profiles:$,initRange:k,indexRange:I,bitrate:S,mime:h,codecs:c,width:m,height:f,fps:v,quality:b,url:E})}}return{container:o,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}l(s);const a=({mime:e,codecs:i})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${i}"`));return this.manifest={...s,representations:Object.fromEntries(Object.entries(s.representations).map((([t,e])=>[t,e.filter(a)])))},this.manifest.representations.video.length?this.state$.setState(Jt.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}async initRepresentations(t,e){l(this.manifest),l(this.element),this.state$.startTransitionTo(Jt.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning.dash};this.videoBufferManager=new Qt(x.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new Qt(x.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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(o(this.forceEnded$,g({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(b((t=>Object.values(t).every((t=>!0===t)))))).subscribe((()=>{if('open'===this.source?.readyState)try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&await new Promise((t=>this.source?.addEventListener('sourceopen',t)));(await Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])).some((t=>!t))||(this.state$.setState(Jt.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...jt.map((t=>r(this.element,t))),r(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(r(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.tick())}async switchRepresentation(t,e){const i={[x.VIDEO]:this.videoBufferManager,[x.AUDIO]:this.audioBufferManager,[x.TEXT]:null}[t];return l(i),i.switchTo(e)}seek(t){l(this.element),l(this.videoBufferManager),l(this.audioBufferManager),this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),this.element.currentTime=t/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.state$.setState(Jt.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element)return;const t=1e3*this.element.currentTime;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Kt||(Kt={}));const Zt=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?J(r):void 0)??at({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},te=(t,e,i)=>{const s=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class ee{subscription=new i;videoState=new St(Kt.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new H;videoTracks=[];audioRepresentations;constructor(t){this.params=t,this.video=q(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(mt(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new Xt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=W(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,a));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.firstFrame$,t.firstFrameEvent$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(b(s),m()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(U(this.video,e.isLooped,a)),this.subscription.add(V(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),n(ft(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Kt.PLAYING),K(e.playbackState,w.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(Kt.PAUSED),K(e.playbackState,w.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Kt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(b((({to:t})=>t===Jt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Kt.READY)}))),this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,r(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),i=this.player.state$.getTransition();if(t===Jt.NONE||!this.videoTracks.length)return;const s=t===Jt.MANIFEST_LOADED&&!i,a=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState(),n=this.videoTracks.find((({track:{id:t}})=>t===r))?.track;e.autoVideoTrackSwitching.getTransition()&&e.autoVideoTrackSwitching.setState(a);const o=pt(this.video.buffered,1e3*this.video.currentTime),d=Math.min(o/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),h=lt(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),forwardBufferHealth:d}),u=a?h??n:n??h;if(s){const t=u&&this.videoTracks.find((({track:t})=>t===u))?.representation;l(t);const e=te(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);l(e),this.player.initRepresentations(t.id,e.id)}else{const t=u&&this.videoTracks.find((({track:t})=>t===u))?.representation;if(t){const e=te(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(x.VIDEO,t.id),e&&this.player.switchRepresentation(x.AUDIO,e.id)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),h((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,e,t);const d=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=Zt(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)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const r=a?.to;if(i?.to!==w.PAUSED&&s(r)&&t!==Kt.STOPPED&&e!==w.STOPPED&&this.seek(r),e!==w.STOPPED){if(t===Kt.STOPPED)return this.videoState.startTransitionTo(Kt.READY),void this.prepare();switch(t){case Kt.READY:return void(e===w.PAUSED?(this.videoState.setState(Kt.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(Kt.PLAYING),this.playIfAllowed()));case Kt.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(Kt.PAUSED),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case Kt.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Kt.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}else t!==Kt.STOPPED&&(this.videoState.startTransitionTo(Kt.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(Kt.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(Kt.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}))}}var ie;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(ie||(ie={}));var se=(t,e=0,i=ie.OFFSET_P)=>{switch(i){case ie.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case ie.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t};var ae;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ae||(ae={}));class re{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new St(ae.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case P.MPEG:case P.DASH:case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.HLS:case P.HLS_JS:case P.HLS_ONDEMAND:return!1;case P.HLS_LIVE:case P.DASH_LIVE:case P.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(h((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(h((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const d=(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 e;t.add(i.pipe(f(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let n=NaN;t.add(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);const r=this.params.desiredState.seekPosition.getTransition();(s(r)&&a(r.to)||Math.abs(e-n)>5)&&i.next(e),n=e}))),t.add(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),a=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==a&&this.params.output.isBuffering$.next(a),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),K(this.params.desiredState.playbackState,w.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:n(i)}})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),d(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));d(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(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(ae.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):(this.videoState.setState(ae.PLAYING),K(this.params.desiredState.playbackState,w.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();this.videoState.getTransition()?.to!==ae.PAUSED&&t!==ae.PLAYING||(this.videoState.setState(ae.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==ae.PLAYING&&t!==ae.PAUSED||(this.videoState.setState(ae.PLAYING),K(this.params.desiredState.playbackState,w.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===ae.READY&&this.videoState.setState(ae.READY)}handleRemoteStop(){this.videoState.getState()!==ae.STOPPED&&this.videoState.setState(ae.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}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(t){const e=this.params.source;let i,a,r;switch(t){case P.MPEG:{const s=e[t];l(s);const n=Object.keys(s).sort(((t,e)=>t===e?0:t===j.INVARIANT?1:e===j.INVARIANT?-1:et(t,e)?1:-1))[0];l(n);const o=s[n];l(o),i=o,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS:case P.HLS_ONDEMAND:{const s=e[t];l(s),i=s.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM_VK:case P.DASH_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS_LIVE:{const s=e[t];l(s),i=se(s.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case P.DASH_LIVE_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case P.HLS_JS:case P.DASH:case P.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 n(t)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:h}=this.params.meta;return s(d)&&(o.metadata.title=d),s(h)&&(o.metadata.subtitle=h),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekPosition.getTransition();return e.currentTime=i?this.params.output.isLive$.getValue()?0:i.to??0:0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(v(7e3).subscribe((()=>e('timeout(7000)'))))}));Promise.race([e,i]).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})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(r)};`}),i===w.STOPPED)return void(t!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.STOPPED),this.stop()));if(e)return;const o=r?.to;if(a?.to!==w.PAUSED&&s(o)&&t!==ae.STOPPED)this.seek(o);else switch(i){case w.PLAYING:switch(t){case ae.PLAYING:break;case ae.PAUSED:case ae.READY:this.videoState.startTransitionTo(ae.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case ae.PLAYING:this.videoState.startTransitionTo(ae.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ae.PAUSED:break;case ae.READY:this.videoState.startTransitionTo(ae.PAUSED),this.videoState.setState(ae.PAUSED);break;case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();break;default:n(t)}break;default:n(i)}}}var ne;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ne||(ne={}));class oe{subscription=new i;videoState=new St(ne.STOPPED);video;trackUrls={};params;textTracksManager=new H;constructor(t){this.params=t,this.video=q(t.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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(U(this.video,e.isLooped,i)),this.subscription.add(V(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ne.PLAYING),K(e.playbackState,w.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ne.PAUSED),K(e.playbackState,w.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ne.READY&&this.videoState.setState(ne.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();l(t,'MpegProvider: track is not selected');const{url:e}=this.trackUrls[t];l(e,`MpegProvider: No url for ${t}`),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(mt(e))}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(ne.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===w.STOPPED)return void(t!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===ne.STOPPED)return this.videoState.startTransitionTo(ne.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=r?.to;switch(i?.to!==w.PAUSED&&s(o)&&this.seek(o),t){case ne.READY:return void(e===w.PAUSED?(this.videoState.setState(ne.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()));case ne.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case ne.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}class de{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(l(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('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 he{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){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),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(he._str2ua(t.substr(o))),o=t.length};this._lastXhr=new de(t.baseURL+'&bytes='+e+'-'+i,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.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(),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=he._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(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class ue{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),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='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){new de(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,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Wt(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,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 a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.end-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.end&&(a=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*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}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 he({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),a=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?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 a=.1;if(s.toTime<i.end+a){const e=this._findRef(s.toTime);e&&e.toTime<i.end+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e=!1){this._stream&&this._buffer.getByTime(t)&&!e?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!a(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let i;for(let s=0;s<e.length;s++){const a=e[s];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const i=e[e.length-1];if(t>i.toTime)return i}return i}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const i=e[e.length-1];return t.fromTime===i.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 ce;!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'}(ce||(ce={}));const le=[ce.PAUSED,ce.PLAYING];class pe{videoState=new St(ce.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new H;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=q(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(mt(this.params.source.url)),this.buffer=new Y(this.video),this.dash=new ue({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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=W(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.firstFrame$,t.firstFrameEvent$),this.subscription.add(d.seeking$.subscribe((()=>{a(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===ce.PLAYING||this.videoState.getState()===ce.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(U(this.video,e.isLooped,i)),this.subscription.add(V(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(ft(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(ce.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(ce.PLAYING),K(this.params.desiredState.playbackState,w.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(ce.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(h((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(o(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$,r(this.video,'progress')).pipe(h((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),o=this.elementSize$.getValue(),d=n();let h;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&s(a))h=a;else{const i=pt(this.video.buffered,1e3*this.video.currentTime),s=Math.min(i/this.params.tuning.dash.forwardBufferTarget,1);h=lt(e.map((({track:t})=>t)),{container:o,throughput:r,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:s,currentRepresentation:t})?.id}return s(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(g({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(b((t=>t.to===ce.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(b(s))}).pipe(m()).subscribe((()=>this.videoState.setState(ce.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(b(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=pt(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(mt(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=xt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(m()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(b(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}handleManifestReady=t=>{const e=[];for(const i of t){const t=i.name??i.id??i.height.toString(10),s=(i.name&&J(i.name))??at(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(ce.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t};seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(ce.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(r)};`}),i===w.STOPPED)return void(t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.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(ce.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)));if(e)return;const o=r?.to;switch(a?.to!==w.PAUSED&&s(o)&&le.includes(t)&&this.seek(o),t){case ce.STOPPED:return this.videoState.startTransitionTo(ce.MANIFEST_LOADED),void this.prepare();case ce.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ce.INITIAL_REPRESENTATION_SELECTED);case ce.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ce.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ce.METADATA_LOADED:return this.videoState.startTransitionTo(ce.READY),void this.dash.seek(o??0);case ce.READY:return void(i===w.PAUSED?(this.videoState.setState(ce.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):i===w.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()));case ce.PLAYING:return void(i===w.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):a?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case ce.PAUSED:return void(i===w.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):a?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}var me=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},fe=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 Se=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class ge{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=Se(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.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(Se),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${s}-${a}`);const n=r.toString(),o=new Rt,d=o.signal,h={url:t,from:s,to:a,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(h)));const u=t=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Lt(fetch).fetch(n,{signal:d}).then((t=>{if(!t.ok||!t.body)return void this.onBigRequestError(h);const[e,i]=t.body.tee();this.params.onDownloadStream?.(i);const s=e.getReader(),a=parseInt(t.headers.get('Content-Length')??'',10);h.data=new ArrayBuffer(a);const r=new Uint8Array(h.data),n=async({done:t,value:e})=>{t?this.onBigRequestProgress(h):e&&(r.set(e,h.loaded),h.loaded+=e.byteLength,this.onBigRequestProgress(h),await(s?.read().then(n,ge.suppressStreamErrors).catch(u)))};s?.read().then(n,ge.suppressStreamErrors).catch(u)}),ge.suppressAbort).catch((t=>this.onBigRequestError(h,t))),h}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a}){if(!this.activeRequests.has(t)||!a)return;const r=this.dashJsRequestQueue.get(t)??[];for(const n of r){const{request:r}=n,[o,d]=Se(r),h=o>=e&&d<=e+s,u=e>=o&&e+s<d,c=a.slice(o-e,Math.min(d-e+1,s));(h||u)&&(r.requestStartDate=r.requestStartDate??new Date,r.firstByteDate=r.firstByteDate??new Date,r.bytesLoaded=c.byteLength,r.bytesTotal=i-e),h?(r.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==n))),n.success?.(c,'',t),this.dashMetrics?.addHttpRequest(r,t,200,{},[])):u&&n.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const a=this.dashJsRequestQueue.get(t)??[];for(const t of a){const[a,r]=Se(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=Se(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class be{baseLoader;config;bigRequest;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(be.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;be.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const ve=(t,e)=>{const i=new ge(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new be(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var ye=i=>{const a=new t(1/0),r=new e;let n=NaN,o=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,r.next(Date.now()-n)),i(...t)},n=Date.now(),o=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r}};class Te{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){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 Ee={};var $e;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}($e||($e={}));const we=(t,e)=>new p((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Pe{subscription=new i;videoState=new St($e.DOWNLOADING_LIB);video;player;params;textTracksManager=new H;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new Te;destroyBigRequest;constructor(t){this.video=q(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(mt(this.params.source.url)),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Ee.MediaPlayer=e.MediaPlayer,Ee.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Ee.MediaPlayer,'dashjs not loaded'),l(Ee.Debug,'dashjs not loaded'),this.player=Ee.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?Wt(t.frameRate+''):void 0),!0)));(this.params.format===P.DASH_WEBM||this.params.format===P.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=ve(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&&fe(this.player),me(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState($e.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(ft(this.video),this.elementSize$),r(we(this.player,'error').pipe(h((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),r(we(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=we(this.player,'qualityChangeRendered').pipe(b((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(b(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(b((({to:t})=>t===$e.STREAM_INITIALIZED)),m()).subscribe((()=>{this.subscription.add(M(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(a(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:n.pipe(h((t=>t?.id))),onError:i}))}),i)),this.subscription.add(M(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),r(we(this.player,'bufferStateChanged').pipe(b((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(we(this.player,'fragmentLoadingStarted').pipe(h((t=>mt(t.request.url)))),t.hostname$),r(we(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=at(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState($e.STREAM_INITIALIZED),this.videoState.startTransitionTo($e.READY)})),r(we(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(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=lt(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),r(g({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(b(s))}).pipe(b((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>Ae(t)))),this.params.output.duration$);const d=we(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(g({availableFrom:this.availableFrom$.pipe(b(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(b((()=>!1===this.isLive$.getValue()))),t.position$),r(we(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(we(this.player,'playbackEnded'),t.endedEvent$),r(we(this.player,'playbackProgress').pipe(h((()=>z(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(we(this.player,'playbackPlaying'),(()=>{this.videoState.setState($e.PLAYING),K(e.playbackState,w.PLAYING)})),r(we(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState($e.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(we(this.player,'playbackPaused'),(()=>{this.videoState.setState($e.PAUSED),K(e.playbackState,w.PAUSED)})),r(we(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===$e.READY&&this.videoState.setState($e.READY)})),r(this.isLive$,t.isLive$),r(ft(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l}=ye(this.player);r(c,this.maxSeekBackTime$),r(l.pipe(m()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(g({isLive:this.isLive$,isShort:t.duration$.pipe(h((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(d.pipe(b((t=>t>this.params.tuning.insufficientBufferRuleMargin)),m()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(we(this.player,'manifestLoaded').pipe(m()).subscribe((()=>{const e=Date.now();this.subscription.add(we(this.player,'playbackPlaying').pipe(m()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-e)),i))}),i)),this.subscription.add(U(this.video,e.isLooped,i));const{volumeState$:p,looped$:S}=W(this.video);this.subscription.add(V(this.video,e.volume,p,i)),this.subscription.add(p.subscribe(t.volume$,i)),this.subscription.add(S.subscribe(t.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($e.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)}prepare(){this.videoState.startTransitionTo($e.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(Ae(i));const s=se(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ie.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo($e.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo($e.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition(),r=this.isLive$.getValue();if(this.videoState.getTransition())return;if(t===$e.DOWNLOADING_LIB||t===$e.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==w.PAUSED&&s(o)&&t!==$e.STOPPED&&e!==w.STOPPED&&(r?this.seek(o+Ae(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case w.STOPPED:switch(t){case $e.STOPPED:break;case $e.PLAYING:case $e.PAUSED:case $e.READY:this.stop();break;default:n(t)}break;case w.PLAYING:switch(t){case $e.PLAYING:break;case $e.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(Ae(this.liveOffset.getTotalOffset()))):this.seek(Ae(this.liveOffset.getTotalOffset()))),this.play();break;case $e.READY:this.play();break;case $e.STOPPED:this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case $e.PLAYING:this.pause(),this.liveOffset.pause();break;case $e.PAUSED:break;case $e.READY:this.videoState.setState($e.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED);break;case $e.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}const Ae=t=>-t/1e3;function ke(){return S()}function _e(t){return ke()-t}function De(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Re(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,p=0,m=!1,f='arraybuffer',S=7e3,g=2e3,b=()=>{if(c)return;l(h);const t=_e(h);let e;if(t<g)return e=g-t,void setTimeout(b,e);g*=2,g>S&&(g=S),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=ke(),o=new r,o.open('get',t);let i,s=0,a=0;const p=()=>(l(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=ke();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(p(),t)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=ke(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(m=t,T),withJSONResponse:()=>(f='json',T),withRetryCount:t=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(S=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return T}class Ie{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class Le{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=ke(),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=Re(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=ke()-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=ke()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const t=this._getParallelRequestCount(),e=ke();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class xe{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new Ie(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=De(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=De(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=>{this.destroyed||(e(`Video element error: ${t.error?.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,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{l(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e()})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Le(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:r}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=Re(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{l(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},S=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void S(1);const i=ke()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,S(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else S(1)},v=t=>{let i;const a=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=i.dur.length-1;t>=0&&(e-=i.dur[t]/1e3,!(e<=0));--t);}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=Re(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),r({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=a();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=a(),r=t?t.chunkIdx+1:0,n=r-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return h(r-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let r,d,h,c,S,g,T,E=v(t.jidxUrl),$=0;const w=()=>{S&&(clearTimeout(S),S=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=$+t,i=ke(),s=Math.min(1e4,e-i);$=i;const a=()=>{u||p()&&E.seek((()=>{p()&&($=ke(),P(),w())}))};s>0?S=window.setTimeout((()=>{this.paused?w():a()}),s):a()},P=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?w():(y(),this._initPlayerWith(t)));D(i)}else w()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let a,r,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=ke(),h=i.currentTime;!this.paused&&i.buffered.length>1&&g===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==h&&(g=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},k=()=>{d&&r&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,P()})))},_=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{p()&&f(_(t),((e,i)=>{if(p()){if(i/=1e3,d=e,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}k()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{r=!0,k()})))};n=!0,E.seek((t=>{p()&&($=ke(),t?(c=t,!a(e)||t.startTS>e?D(t):(h=t,P())):w())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=ke();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&_e(r)<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=ke();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=Re(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;B(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return 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 Ce;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ce||(Ce={}));const Oe=[Ce.PAUSED,Ce.PLAYING,Ce.READY],Ne=[Ce.PAUSED,Ce.PLAYING,Ce.READY];class Be{subscription=new i;video;videoState=new St(Ce.STOPPED);dash;representations$=new t([]);textTracksManager=new H;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new Te;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=q(t.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(mt(this.params.source.url)),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=W(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ce.READY&&this.videoState.setState(Ce.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(Ce.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.videoState.setState(Ce.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h(Me)).subscribe(this.params.output.duration$)).add(g({zeroTime:this.zeroTime$.pipe(b(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(U(this.video,this.params.desiredState.isLooped,e)).add(V(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(Q(this.video).subscribe(this.params.output.firstBytesEvent$)).add(G(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&X[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Ce.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(w.STOPPED);break;case Ce.MANIFEST_READY:case Ce.READY:break;case Ce.PAUSED:this.params.desiredState.playbackState.setState(w.PAUSED);break;case Ce.PLAYING:this.params.desiredState.playbackState.setState(w.PLAYING);break;default:return n(t.to)}}),e)).add(o(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekPosition.stateChangeStarted$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new xe({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(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:lt(t.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()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;l(r),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;l(e),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}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(Me(i)),this.dash.reinit(se(this.params.source.url,i)),this.params.output.seekedEvent$.next()}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,i=[];for(const t of e){const e=t.name??t.index.toString(10),s=J(t.name)??at(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===Ce.MANIFEST_READY&&this.videoState.setState(Ce.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(r)};`}),i===w.STOPPED)return void(t!==Ce.STOPPED&&(this.videoState.startTransitionTo(Ce.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Ce.STOPPED)));if(e)return;if(Ne.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}const o=r?.to;if(a?.to!==w.PAUSED&&s(o)&&Oe.includes(t))this.seek(o+Me(this.liveOffset.getTotalPausedTime()));else switch(t){case Ce.STOPPED:return this.videoState.startTransitionTo(Ce.MANIFEST_READY),void this.dash.attachSource(se(this.params.source.url));case Ce.MANIFEST_READY:this.videoState.startTransitionTo(Ce.READY),this.prepare();break;case Ce.READY:return void(i===w.PAUSED?this.videoState.setState(Ce.PAUSED):i===w.PLAYING&&(this.videoState.startTransitionTo(Ce.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Ce.PAUSED)}))));case Ce.PLAYING:return void(i===w.PAUSED&&(this.videoState.startTransitionTo(Ce.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Ce.PAUSED:return void(i===w.PLAYING&&(this.videoState.startTransitionTo(Ce.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(Ce.PAUSED)})),this.params.output.position$.next(Me(this.liveOffset.getTotalOffset()))):this.seek(Me(this.liveOffset.getTotalOffset()))));default:return n(t)}}}const Me=t=>-t/1e3,Ue=t=>{let e=null;if(t.QUALITY&&(e=J(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=at({width:i,height:s})}return e??null},Ve=async(t,e=t)=>{const i=await Lt(fetch).fetch(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=Ue(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Fe;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Fe||(Fe={}));class He{subscription=new i;videoState=new St(Fe.STOPPED);video;params;textTracksManager=new H;manifests$=new t([]);constructor(t){this.params=t,this.video=q(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:j.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(mt(this.params.source.url)),Ve(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(U(this.video,e.isLooped,i)),this.subscription.add(V(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Fe.PLAYING),K(e.playbackState,w.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Fe.PAUSED),K(e.playbackState,w.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Fe.READY&&this.videoState.setState(Fe.READY),this.videoState.getState()===Fe.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.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(mt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Fe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i))),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();a(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(Fe.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===w.STOPPED)return void(t!==Fe.STOPPED&&(this.videoState.startTransitionTo(Fe.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(Fe.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===Fe.STOPPED)return this.videoState.startTransitionTo(Fe.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(Fe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(d&&!a(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const h=d?.to;switch(i?.to!==w.PAUSED&&s(h)&&this.seek(h),t){case Fe.READY:return void(e===w.PAUSED?(this.videoState.setState(Fe.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(Fe.PLAYING),this.playIfAllowed()));case Fe.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(Fe.PAUSED),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case Fe.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Fe.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));case Fe.CHANGING_MANIFEST:break;default:return n(t)}}}var qe;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(qe||(qe={}));class Ge{subscription=new i;videoState=new St(qe.STOPPED);video;params;textTracksManager=new H;manifests$=new t([]);maxSeekBackTime$;liveOffset=new Te;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:j.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Ve(se(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.params.output.isLive$.next(!0),this.params.output.hostname$.next(mt(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=W(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(V(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(qe.PLAYING),K(e.playbackState,w.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(qe.PAUSED),K(e.playbackState,w.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===qe.READY&&this.videoState.setState(qe.READY),this.videoState.getState()===qe.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h(Ye)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.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(mt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===qe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const t=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(t||void 0)}),i)),this.subscription.add(g({startTime:this.manifestStartTime$.pipe(b(s)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,u(['init'])).pipe(f(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(a(t))return;const e=se(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await Lt(fetch).fetch(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(e).then((t=>{a(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(qe.PAUSED),this.liveOffset.pause(),K(this.params.desiredState.playbackState,w.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(Ye(i)),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===w.STOPPED)return void(t!==qe.STOPPED&&(this.videoState.startTransitionTo(qe.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(qe.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===qe.STOPPED)return this.videoState.startTransitionTo(qe.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(qe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const e=Ye(this.liveOffset.getTotalOffset());return this.prepare(),void(d&&!a(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const h=d?.to;if(i?.to!==w.PAUSED&&s(h))return this.videoState.startTransitionTo(qe.READY),this.seek(h+Ye(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case qe.READY:return void(e===w.PAUSED?(this.videoState.setState(qe.PAUSED),this.liveOffset.pause(),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(qe.PLAYING),this.playIfAllowed()));case qe.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(qe.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case qe.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(qe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Ye(this.liveOffset.getTotalOffset()))):this.seek(Ye(this.liveOffset.getTotalOffset()))):i?.to===w.PAUSED&&(K(this.params.desiredState.playbackState,w.PAUSED),this.liveOffset.pause()));case qe.CHANGING_MANIFEST:break;default:return n(t)}}}const Ye=t=>-t/1e3,ze={};var Qe;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Qe||(Qe={}));const We=(t,e)=>new p((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class je{subscription=new i;videoState=new St(Qe.INITIALIZING);video;params;hls;textTracksManager=new H;trackLevels=new Map;constructor(t){this.video=q(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(mt(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.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},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(ze.Hls=e.default,ze.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(ze.Hls,'hls.js not loaded'),this.hls=new ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Qe.STOPPED)}subscribe(){l(ze.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=W(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.firstBytes$,e.firstBytesEvent$),n(r.firstFrame$,e.firstFrameEvent$),n(r.seeked$,e.seekedEvent$),this.subscription.add(U(this.video,t.isLooped,i)),this.subscription.add(V(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(We(this.hls,ze.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),K(t.playbackState,w.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),K(t.playbackState,w.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY),this.videoState.getState()===Qe.PLAYING&&this.playIfAllowed()}),i)),n(We(this.hls,ze.Events.MANIFEST_PARSED).pipe(h((({levels:t})=>t.reduce(((t,e)=>{const i=e.name||e.height.toString(10),{width:s,height:a}=e,r=J(e.attrs.QUALITY??'')??at({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),n(We(this.hls,ze.Events.LEVEL_LOADING).pipe(h((({url:t})=>mt(t)))),e.hostname$),this.subscription.add(M(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track;n(t.autoVideoTrackLimits.stateChangeEnded$,(({to:t})=>{if(t.max){let e=-1;for(const{track:i,level:s}of this.trackLevels.values())!rt(i.quality)&&it(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())!rt(i.quality)&&tt(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 c=We(this.hls,ze.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(b(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(M(t.videoTrack,(()=>d(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(a(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const i=this.hls.levels.indexOf(e),s=this.hls.currentLevel,r=this.hls.levels[s];!r||e.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:c.pipe(h((t=>t?.id))),onError:i})),n(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const p=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(f(0));this.subscription.add(p.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(t===Qe.INITIALIZING)return;const r=a?.to;switch(i?.to!==w.PAUSED&&s(r)&&this.seek(r),e){case w.STOPPED:switch(t){case Qe.STOPPED:break;case Qe.READY:case Qe.PLAYING:case Qe.PAUSED:this.stop();break;default:n(t)}break;case w.PLAYING:switch(t){case Qe.PLAYING:break;case Qe.STOPPED:this.prepare();break;case Qe.READY:case Qe.PAUSED:this.playIfAllowed();break;default:n(t)}break;case w.PAUSED:switch(t){case Qe.PAUSED:break;case Qe.STOPPED:this.prepare();break;case Qe.READY:this.videoState.setState(Qe.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED);break;case Qe.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(Qe.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Qe.PLAYING);await B(this.video)||(this.videoState.setState(Qe.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Qe.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(Qe.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)}}class Je{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const Ke=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),Xe=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Ze=document.createElement('video'),ti={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Ze.canPlayType?.('application/x-mpegurl')||Ze.canPlayType?.('vnd.apple.mpegURL'))},ei={mp4:Boolean(Ze.canPlayType?.('video/mp4')),webm:Boolean(Ze.canPlayType?.('video/webm'))},ii={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},si=(ii.h264||ii.h265)&&ii.aac,ai=!Ke,ri=Xe||Ke,ni=!ti.hls||!ri,oi=3e4,di=18e4,hi=3,ui=100,ci={cacheDuration:12e4},li={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},pi={maxPausedTime:3e4},mi={maxPausedTime:3e4};class fi{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new i;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,i=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new Je(i.filter((e=>s(t.sources[e]))).filter((t=>{switch(t){case P.DASH:return ti.mse&&ei.mp4&&si&&ai;case P.DASH_SEP:case P.DASH_SEP_VK:return ti.mse&&ei.mp4&&si;case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.DASH_LIVE_WEBM:return ti.mse&&ei.webm&&ii.vp9&&ii.opus;case P.DASH_LIVE:case P.DASH_ONDEMAND:return ti.mse&&ei.mp4&&si;case P.HLS:case P.HLS_LIVE:case P.HLS_ONDEMAND:return ti.hls&&ei.mp4&&ri;case P.HLS_JS:return ti.mse&&ei.mp4&&si&&ni;case P.MPEG:return ei.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new Je(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}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 t=this.chooseDestination(),e=this.chooseFormat(t);if(a(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=this.params.desiredState.seekPosition,i=e.getTransition();i?s(i.from)&&e.startTransitionTo(i.from):e.startTransitionTo(this.providerOutput.position$.getValue()),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case A.SCREEN:return this.createScreenProvider(e);case A.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,a=this.providerOutput;switch(t){case P.DASH:{const r=e[t];return l(r),new pe({container:i,source:r,desiredState:s,output:a,config:ci,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP_VK:case P.DASH_WEBM_VK:{const r=e[t];return l(r),new ee({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP:case P.DASH_WEBM:case P.DASH_ONDEMAND:case P.DASH_LIVE_WEBM:{const r=e[t];return l(r),new Pe({container:i,source:r,desiredState:s,output:a,format:t,config:mi,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS:case P.HLS_ONDEMAND:{const r=e[t];return l(r),new He({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_LIVE:{const r=e[t];return l(r),new Ge({container:i,source:r,desiredState:s,output:a,config:pi,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_JS:{const r=e[t];return l(r),new je({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.MPEG:{const r=e[t];return l(r),new oe({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_LIVE:{const r=e[t];return l(r),new Be({container:i,source:r,desiredState:s,output:a,config:li,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new re({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?A.CHROMECAST:A.SCREEN}chooseFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case A.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.next();case A.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case A.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case A.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let e=[],a=0;const r=new i;var n;return r.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:oi,position$:this.providerOutput.position$,providerChanged$:this.current$},new p((e=>{const s=new i,a=v(n.maxTransitionInterval),r=new t(void 0);o(n.desiredPlaybackState$.stateChangeStarted$.pipe(y(a)),n.desiredPlaybackState$.stateChangeEnded$.pipe(y(void 0)),n.providerChanged$.pipe(h((()=>r.getValue())))).subscribe(r);const d=new i;return s.add(d),s.add(r.subscribe((t=>{d.unsubscribe(),t&&d.add(t.subscribe(e))}))),s}))).pipe(y({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),r.add(this.providerError$.pipe(T(ui,{leading:!1,trailing:!0})).subscribe((()=>{const t=Date.now();this.current$.getValue().destination===A.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(e[a])&&t<e[a]+di?(e=[],this.switchToNextProvider()):(e[a]=t,this.reinitProvider()),a=(a+1)%hi}))),r}}const Si=(t,e,i)=>i*e+(1-i)*t;class gi{prevReported=void 0;slow;fast;smoothed;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new ut(`raw_${i}`),this.smoothedSeries$=new ut(`smoothed_${i}`),this.reportedSeries$=new ut(`reported_${i}`)}next(t){this.slow=Si(this.slow,t,this.params.emaAlphaSlow),this.fast=Si(this.fast,t,this.params.emaAlphaFast);const e=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=e(this.slow,this.fast),this.smoothed$.next(this.smoothed),(a(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(t),this.smoothedSeries$.next(this.smoothed)}}var bi;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(bi||(bi={}));const vi=new Map;let yi=bi.RUNTIME;const Ti=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Ti,'test'),localStorage.removeItem(Ti),yi=bi.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(Ti),yi=bi.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;yi=bi.RUNTIME}}})();const Ei=(t,e)=>{switch(yi){case bi.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case bi.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case bi.RUNTIME:return void vi.set(t,e);default:n(yi)}},$i=window.navigator.connection,wi=()=>{const t=$i?.downlink;if(s(t)&&10!==t)return 1e3*t},Pi=()=>{const t=$i?.rtt;if(s(t)&&3e3!==t)return t},Ai=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class ki{throughput;rtt;subscription=new i;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=ki.load('one_video_throughput')||(e.useBrowserEstimation?wi():void 0)||5e3,a=ki.load('one_video_rtt')??(e.useBrowserEstimation?Pi():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Ai(i,a,e.rttPenaltyRequestSize)),this.throughput=new gi({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new gi({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=wi();t&&this.throughput.next(t);const e=Pi();s(e)&&this.rtt.next(e)};$i&&'onchange'in $i&&this.subscription.add(r($i,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ei('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ei('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(g({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(h((({throughput:t,rtt:i})=>Ai(t,i,e.rttPenaltyRequestSize))),b((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let e=0,s=S();const a=new i;switch(this.subscription.add(a),t.readyState){case 4:break;case 3:case 2:a.add(r(t,'progress').pipe(m()).subscribe((t=>{e=t.loaded,s=S()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,s=S()})))}a.add(r(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=S(),r=t-e,n=a-s;this.addRawSpeed(r,n)}a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=S();let a=0,r=S();const n=i=>{e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:t,value:d})=>{t?this.addRawSpeed(i,S()-s):d&&(i+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&S()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,S()-r),a=0,r=S()),await(e?.read().then(o,n)))};e?.read().then(o,n)}addRawSpeed(t,e){if(ki.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(t){const e=(t=>{switch(yi){case bi.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case bi.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case bi.RUNTIME:return vi.get(t);default:n(yi)}})(t);if(s(e))return parseInt(e,10)??void 0}}const _i=(t=(t=>t))=>({playbackState:e,seekPosition:r,playbackAbort$:n,looped$:d,position$:u})=>new p((c=>{let l;const p=e.transitionEnded$.pipe(b((t=>(t.from===w.PAUSED||t.from===w.STOPPED)&&t.to===w.PLAYING))),m=e.stateChangeEnded$.pipe(b((t=>t.from===w.PLAYING&&t.to===w.PAUSED))),f=r.stateChangeEnded$.pipe(b((t=>s(t.to)&&(e.getTransition()?.from??e.getState())===w.PLAYING))),S=r.stateChangeEnded$.pipe(b((t=>a(t.to)&&(e.getTransition()?.from??e.getState())===w.PLAYING))),g=o(p,S).pipe(h((()=>t(u.getValue())))),v=o(o(m,f,n).pipe(h((()=>t(u.getValue())))),d.pipe(h(t)));return(new i).add(g.subscribe((e=>{l=t(e)}))).add(v.subscribe((e=>{const i=t(e);if(a(l)||l===i)return;const s={start:l,end:i};l=void 0,c.next(s)})))})),Di=_i((t=>t)),Ri=_i((t=>Math.round(1e3*t)+Date.now())),Ii={[A.SCREEN]:{vod:[P.HLS,P.HLS_ONDEMAND,P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS_JS,P.MPEG],live:[P.HLS_LIVE,P.DASH_LIVE,P.DASH_LIVE_WEBM]},[A.CHROMECAST]:{vod:[P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS,P.HLS_ONDEMAND,P.MPEG],live:[P.HLS_LIVE]}};class Li{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new E;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new St(w.STOPPED),seekPosition:new St(void 0),volume:new St({volume:1,muted:!1}),videoTrack:new St(void 0),autoVideoTrackSwitching:new St(!0),autoVideoTrackLimits:new St({}),isLooped:new St(!1),externalTextTracks:new St([]),currentTextTrack:new St(void 0),textTrackCuesSettings:new St({})};info={playbackState$:new t(w.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimits$:new t({}),currentBuffer$:new t(void 0),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(k.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};events={started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,log$:new e};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:dt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(R)){const s=R[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new I({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ki(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}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new fi({screenFormatsPriority:[...Ii[A.SCREEN].live,...Ii[A.SCREEN].vod],chromecastFormatsPriority:[...Ii[A.CHROMECAST].live,...Ii[A.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},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(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==w.PLAYING&&t.startTransitionTo(w.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==w.PAUSED&&t.startTransitionTo(w.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==w.STOPPED&&t.startTransitionTo(w.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()===k.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()===k.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.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=>({type:'external',...t})))),this}selectTextTrack(t){return(void 0===t||this.providerContainer?.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(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(a(t))return this.info.position$.getValue();const e=this.desiredState.seekPosition.getTransition(),i=e?.to??e?.from;return s(i)?i:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(h((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.autoQualityLimits$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(b((t=>t.to===w.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((t=>t.to===w.PLAYING||t.to===w.PAUSED)),f(0),m()).subscribe((t=>{const e=t.to===w.PLAYING,i=this.info.muted$.getValue(),s=e?i?_.SuccessWithoutSound:_.SuccessWithSound:_.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((t=>t.to===w.PLAYING)),f(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 w.PAUSED:this.events.willPause$.next();break;case w.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition()?.to;s(t)&&(this.desiredState.seekPosition.setState(t),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition();s(t?.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(e.current$.pipe(h((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(h((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(h((t=>t.map((({quality:t})=>t)).sort(((t,e)=>rt(t)?1:rt(e)?-1:Z(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(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(h((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(h((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekPosition:t,position$:e})=>o(t.stateChangeStarted$.pipe(h((t=>t.to)),b(s)),e.pipe(b((()=>a(t.getState())&&a(t.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(y(!0)),e.providerOutput.seekedEvent$.pipe(y(!1))).pipe(c()).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(h((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 n=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>n.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>n.next(!0))));const d=new t(!0);this.subscription.add(e.current$.subscribe((()=>d.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((({to:t})=>t===w.PLAYING)),m()).subscribe((()=>d.next(!1))));let u=0;const p=o(e.providerOutput.isBuffering$,n,d).pipe(h((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=n.getValue()||d.getValue();return t&&!i})),c());this.subscription.add(p.subscribe((t=>{t?u=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(u),this.info.isStalled$.next(!1))})));const f=new i;this.subscription.add(f);const S=o(r(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(b((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),f.unsubscribe(),t){case!0:f.add(Ri({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:S,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:f.add(Di({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:S,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(h((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(b((t=>t.length>0)),m()).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=lt(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(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(h((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(){const t=this.providerContainer?.providerOutput;l(this.providerContainer),l(t),ot={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{nt=t})),this.providerContainer.current$.subscribe((({type:t})=>ht('provider',t))),t.duration$.subscribe((t=>ht('duration',t))),t.availableVideoTracks$.pipe(b((t=>!!t.length)),m()).subscribe((t=>ht('tracks',t))),this.events.fatalError$.subscribe(new ut('fatalError')),this.events.managedError$.subscribe(new ut('managedError')),t.position$.subscribe(new ut('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new ut('quality')),t.currentBuffer$.subscribe(new ut('buffer')),t.isBuffering$.subscribe(new ut('isBuffering'))].forEach((t=>this.subscription.add(t))),ht('codecs',Object.keys(ii).filter((t=>ii[t])))}}const xi='@vkontakte/videoplayer-core@2.0.45';export{k as ChromecastState,D as HttpConnectionType,w as PlaybackState,Li as Player,xi as SDK_VERSION,_ as StartStatus,P as VideoFormat,j as VideoQuality};