@vkontakte/videoplayer-core 2.0.46 → 2.0.47

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.46
3
- * Mon, 28 Mar 2022 12:12:14 GMT
4
- * https://st.mycdn.me/static/playersdk/2-0-46/doc/
2
+ * @vkontakte/videoplayer-core v2.0.47
3
+ * Wed, 06 Apr 2022 17:51:39 GMT
4
+ * https://st.mycdn.me/static/playersdk/2-0-47/doc/
5
5
  */
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 T,throttle as y,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:856,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=Object.keys(X).sort(((t,e)=>tt(t,e)?-1:1)),it=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return et.find((t=>{const e=X[t];return e.width>=s&&e.height>=i}))},st=t=>t===j.INVARIANT;let at=!1,rt={};const nt=t=>{t(rt)},ot=(t,e)=>{at&&(rt.meta=rt.meta??{},rt.meta[t]=e)};class dt{name;constructor(t){this.name=t}next(t){if(!at)return;rt.series=rt.series??{};const e=rt.series[this.name]??[];e.push([Date.now(),t]),rt.series[this.name]=e}}const ht=new dt('best_bitrate'),ut=(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&&it(u),l=t.filter((t=>!st(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)&&tt(n.max,n.min)||s(n.min)&&m&&Z(n.min,m)||s(n.max)&&p&&tt(n.max,p),S=l.filter((t=>{const e=!c||tt(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)||(g=t.quality,b=n.max,X[g].height<=X[b].height))&&(a(n.min)||((t,e)=>X[t].height>=X[e].height)(t.quality,n.min));var g,b;return e&&h&&m&&S}))[0];return S&&S.bitrate&&ht.next(S.bitrate),S??l[Math.ceil((l.length-1)/2)]??t[0]};var ct=(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)},lt=t=>new URL(t).hostname;const pt=(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 mt{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 ft={};function St(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function gt(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 bt(t,e,i){return e&&gt(t.prototype,e),i&&gt(t,i),t}function vt(t){return(vt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Tt(t,e){return(Tt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function yt(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function Et(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?yt(t):e}function $t(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=vt(t);if(e){var a=vt(this).constructor;i=Reflect.construct(s,arguments,a)}else i=s.apply(this,arguments);return Et(this,i)}}function wt(t,e,i){return(wt='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=vt(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(ft,'__esModule',{value:!0});var Pt=function(){function t(){St(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return bt(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}(),At=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&&Tt(t,e)}(i,Pt);var e=$t(i);function i(){var t;return St(this,i),(t=e.call(this)).listeners||Pt.call(yt(t)),Object.defineProperty(yt(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(yt(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return bt(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)),wt(vt(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),kt=function(){function t(){St(this,t),Object.defineProperty(this,'signal',{value:new At,writable:!0,configurable:!0})}return bt(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&&(kt.prototype[Symbol.toStringTag]='AbortController',At.prototype[Symbol.toStringTag]='AbortSignal');var _t=ft.AbortController=kt;ft.AbortSignal=At;var Dt,Rt=ft.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}},It=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'}(Dt||(Dt={}));class Lt{throughputEstimator;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new _t;subscription=new i;constructor({throughputEstimator:t}={}){this.throughputEstimator=t}onHeadersReceived(t){const{type:e,reused:i}=It(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchManifest(t){const e=await Rt(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(xt);return e?(this.onHeadersReceived(e.headers),e.text()):null}async fetchRange(t,e,i,{method:s=Dt.HEADER,onProgress:a,signal:d}={}){let h=t;const u=new Headers;switch(s){case Dt.HEADER:u.append('Range',`${e}-${i}`);break;case Dt.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 _t;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 Rt(fetch).fetch(h,{headers:u,signal:c}).catch(xt);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,xt(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,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:Dt.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:Dt.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 xt=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Ct,Ot;!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'}(Ot||(Ot={}));const Nt={[Ct.EBML]:{type:Ot.Master},[Ct.EBMLVersion]:{type:Ot.UnsignedInteger},[Ct.EBMLReadVersion]:{type:Ot.UnsignedInteger},[Ct.EBMLMaxIDLength]:{type:Ot.UnsignedInteger},[Ct.EBMLMaxSizeLength]:{type:Ot.UnsignedInteger},[Ct.DocType]:{type:Ot.String},[Ct.DocTypeVersion]:{type:Ot.UnsignedInteger},[Ct.DocTypeReadVersion]:{type:Ot.UnsignedInteger},[Ct.Void]:{type:Ot.Binary},[Ct.Segment]:{type:Ot.Master},[Ct.SeekHead]:{type:Ot.Master},[Ct.Seek]:{type:Ot.Master},[Ct.SeekID]:{type:Ot.Binary},[Ct.SeekPosition]:{type:Ot.UnsignedInteger},[Ct.Info]:{type:Ot.Master},[Ct.TimestampScale]:{type:Ot.UnsignedInteger},[Ct.Duration]:{type:Ot.Float},[Ct.Tracks]:{type:Ot.Master},[Ct.Chapters]:{type:Ot.Master},[Ct.Cluster]:{type:Ot.Master},[Ct.Attachments]:{type:Ot.Master},[Ct.Tags]:{type:Ot.Master},[Ct.Cues]:{type:Ot.Master},[Ct.CuePoint]:{type:Ot.Master},[Ct.CueTime]:{type:Ot.UnsignedInteger},[Ct.CueTrackPositions]:{type:Ot.Master},[Ct.CueTrack]:{type:Ot.UnsignedInteger},[Ct.CueClusterPosition]:{type:Ot.UnsignedInteger},[Ct.CueRelativePosition]:{type:Ot.UnsignedInteger},[Ct.CueDuration]:{type:Ot.UnsignedInteger},[Ct.CueBlockNumber]:{type:Ot.UnsignedInteger},[Ct.CueCodecState]:{type:Ot.UnsignedInteger},[Ct.CueReference]:{type:Ot.Master},[Ct.CueRefTime]:{type:Ot.UnsignedInteger}},Bt=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=Mt(t,i),a=s in Nt,r=a?Nt[s].type:Ot.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))+Mt(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}},Mt=(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},Ut=(t,e)=>{switch(e){case Ot.SignedInteger:return t.getInt8(0);case Ot.UnsignedInteger:return Mt(t);case Ot.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Ot.String:return new TextDecoder('ascii').decode(t);case Ot.UTF8:return new TextDecoder('utf-8').decode(t);case Ot.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Ot.Master:case Ot.Binary:return t;default:n(e)}},Vt=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Bt(s);if(!e(a))return;a.type===Ot.Master&&Vt(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Ft=[Ct.Info,Ct.SeekHead,Ct.Tracks,Ct.Chapters,Ct.Cluster,Ct.Cues,Ct.Attachments,Ct.Tags],Ht={validateData:t=>{if(t.getUint32(0)!==Ct.EBML)return!1;let e,i,s;const a=Bt(t);return Vt(a.value,(({tag:t,type:a,value:r})=>(t===Ct.EBMLReadVersion?e=Ut(r,a):t===Ct.DocType?i=Ut(r,a):t===Ct.DocTypeReadVersion&&(s=Ut(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 Vt(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===Ct.SeekID){const t=Ut(c,u);n=Mt(t)}else t!==Ct.SeekPosition&&(n=void 0);return t===Ct.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Ct.Info?o=!0:t===Ct.SeekHead?d=!0:t===Ct.TimestampScale?s=Ut(c,u):t===Ct.Duration?a=Ut(c,u):t===Ct.SeekPosition&&n===Ct.Cues?r=Ut(c,u):o&&d&&Ft.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 Vt(t,(({tag:t,type:e,value:s})=>{switch(t){case Ct.Cues:i=!0;break;case Ct.CuePoint:o&&r(o)&&n.push(o),o={};break;case Ct.CueTime:o&&(o.time=Ut(s,e));break;case Ct.CueTrackPositions:break;case Ct.CueClusterPosition:o&&(o.position=Ut(s,e));break;default:i&&Ft.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}}}))}},qt=new TextDecoder('ascii'),Gt={validateData:t=>'ftyp'===qt.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=qt.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 Yt{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 _t;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=Gt;break;case N.WEBM:this.containerParser=Ht;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 _t,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=ct(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&&ct(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:Dt.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 Yt.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 Yt.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 zt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},Qt=['timeupdate','progress','play','seeked','stalled'];var Wt,jt;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Wt||(Wt={}));class Jt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new i;fetcher;state$=new mt(Wt.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 Lt({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(Wt.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?zt(g):void 0,T=`${u.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${f}p`:'audio'===l?`${S}Kbps`:c}`,y=u.querySelector('BaseURL')?.textContent?.trim()??'',E=new URL(y,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:T,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(Wt.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(Wt.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 Yt(x.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new Yt(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(Wt.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...Qt.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(Wt.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'}(jt||(jt={}));const Kt=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?J(r):void 0)??it({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Xt=(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 Zt{subscription=new i;videoState=new mt(jt.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(lt(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Jt({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(pt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(jt.PLAYING),K(e.playbackState,w.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(jt.PAUSED),K(e.playbackState,w.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===jt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(b((({to:t})=>t===Wt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(jt.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===Wt.NONE||!this.videoTracks.length)return;const s=t===Wt.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=ct(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=ut(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=Xt(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=Xt(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=Kt(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!==jt.STOPPED&&e!==w.STOPPED&&this.seek(r),e!==w.STOPPED){if(t===jt.STOPPED)return this.videoState.startTransitionTo(jt.READY),void this.prepare();switch(t){case jt.READY:return void(e===w.PAUSED?(this.videoState.setState(jt.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(jt.PLAYING),this.playIfAllowed()));case jt.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(jt.PAUSED),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case jt.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(jt.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}else t!==jt.STOPPED&&(this.videoState.startTransitionTo(jt.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(jt.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(jt.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0))}))}}var te;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(te||(te={}));var ee=(t,e=0,i=te.OFFSET_P)=>{switch(i){case te.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case te.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 ie;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ie||(ie={}));class se{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new mt(ie.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(ie.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):(this.videoState.setState(ie.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!==ie.PAUSED&&t!==ie.PLAYING||(this.videoState.setState(ie.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==ie.PLAYING&&t!==ie.PAUSED||(this.videoState.setState(ie.PLAYING),K(this.params.desiredState.playbackState,w.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY)}handleRemoteStop(){this.videoState.getState()!==ie.STOPPED&&this.videoState.setState(ie.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:tt(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=ee(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!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.stop()));if(e)return;const o=r?.to;if(a?.to!==w.PAUSED&&s(o)&&t!==ie.STOPPED)this.seek(o);else switch(i){case w.PLAYING:switch(t){case ie.PLAYING:break;case ie.PAUSED:case ie.READY:this.videoState.startTransitionTo(ie.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ie.STOPPED:this.videoState.startTransitionTo(ie.READY),this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case ie.PLAYING:this.videoState.startTransitionTo(ie.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ie.PAUSED:break;case ie.READY:this.videoState.startTransitionTo(ie.PAUSED),this.videoState.setState(ie.PAUSED);break;case ie.STOPPED:this.videoState.startTransitionTo(ie.READY),this.prepare();break;default:n(t)}break;default:n(i)}}}var ae;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ae||(ae={}));class re{subscription=new i;videoState=new mt(ae.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(ae.PLAYING),K(e.playbackState,w.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ae.PAUSED),K(e.playbackState,w.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ae.READY&&this.videoState.setState(ae.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()===ae.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(lt(e))}playIfAllowed(){B(this.video).then((t=>{t||(this.videoState.setState(ae.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!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.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===ae.STOPPED)return this.videoState.startTransitionTo(ae.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 ae.READY:return void(e===w.PAUSED?(this.videoState.setState(ae.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):e===w.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()));case ae.PLAYING:return void(e===w.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case ae.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}class ne{_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 oe{_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(oe._str2ua(t.substr(o))),o=t.length};this._lastXhr=new ne(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=oe._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 de{_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 ne(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?zt(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 oe({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 he;!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'}(he||(he={}));const ue=[he.PAUSED,he.PLAYING];class ce{videoState=new mt(he.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(lt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Y(this.video),this.dash=new de({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()===he.PLAYING||this.videoState.getState()===he.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(pt(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===he.READY&&this.videoState.setState(he.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(he.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(he.PLAYING),K(this.params.desiredState.playbackState,w.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(he.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=ct(this.video.buffered,1e3*this.video.currentTime),s=Math.min(i/this.params.tuning.dash.forwardBufferTarget,1);h=ut(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===he.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(b(s))}).pipe(m()).subscribe((()=>this.videoState.setState(he.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=ct(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(lt(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=It(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))??it(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(he.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(he.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!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)));if(e)return;const o=r?.to;switch(a?.to!==w.PAUSED&&s(o)&&ue.includes(t)&&this.seek(o),t){case he.STOPPED:return this.videoState.startTransitionTo(he.MANIFEST_LOADED),void this.prepare();case he.MANIFEST_LOADED:return void this.videoState.startTransitionTo(he.INITIAL_REPRESENTATION_SELECTED);case he.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(he.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case he.METADATA_LOADED:return this.videoState.startTransitionTo(he.READY),void this.dash.seek(o??0);case he.READY:return void(i===w.PAUSED?(this.videoState.setState(he.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED)):i===w.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()));case he.PLAYING:return void(i===w.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):a?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case he.PAUSED:return void(i===w.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):a?.to===w.PAUSED&&K(this.params.desiredState.playbackState,w.PAUSED));default:return n(t)}}}var le=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)},pe=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 me=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class fe{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]=me(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(me),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 _t,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 Rt(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,fe.suppressStreamErrors).catch(u)))};s?.read().then(n,fe.suppressStreamErrors).catch(u)}),fe.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]=me(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]=me(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]=me(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 Se{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(Se.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;Se.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const ge=(t,e)=>{const i=new fe(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 Se(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var be=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 ve{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 Te={};var ye;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ye||(ye={}));const Ee=(t,e)=>new p((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class $e{subscription=new i;videoState=new mt(ye.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 ve;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(lt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),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||(Te.MediaPlayer=e.MediaPlayer,Te.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Te.MediaPlayer,'dashjs not loaded'),l(Te.Debug,'dashjs not loaded'),this.player=Te.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?zt(t.frameRate+''):void 0),!0)));(this.params.format===P.DASH_WEBM||this.params.format===P.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=ge(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&&pe(this.player),le(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(ye.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(pt(this.video),this.elementSize$),r(Ee(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(Ee(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Ee(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===ye.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(Ee(this.player,'bufferStateChanged').pipe(b((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(Ee(this.player,'fragmentLoadingStarted').pipe(h((t=>lt(t.request.url)))),t.hostname$),r(Ee(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=it(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(ye.STREAM_INITIALIZED),this.videoState.startTransitionTo(ye.READY)})),r(Ee(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=ut(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})=>we(t)))),this.params.output.duration$);const d=Ee(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(Ee(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(Ee(this.player,'playbackEnded'),t.endedEvent$),r(Ee(this.player,'playbackProgress').pipe(h((()=>z(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(Ee(this.player,'playbackPlaying'),(()=>{this.videoState.setState(ye.PLAYING),K(e.playbackState,w.PLAYING)})),r(Ee(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ye.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Ee(this.player,'playbackPaused'),(()=>{this.videoState.setState(ye.PAUSED),K(e.playbackState,w.PAUSED)})),r(Ee(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===ye.READY&&this.videoState.setState(ye.READY)})),r(this.isLive$,t.isLive$),r(pt(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}=be(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(Ee(this.player,'manifestLoaded').pipe(m()).subscribe((()=>{const e=Date.now();this.subscription.add(Ee(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(ye.STOPPED),K(this.params.desiredState.playbackState,w.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(ye.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(we(i));const s=ee(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,te.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(ye.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(ye.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===ye.DOWNLOADING_LIB||t===ye.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==w.PAUSED&&s(o)&&t!==ye.STOPPED&&e!==w.STOPPED&&(r?this.seek(o+we(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case w.STOPPED:switch(t){case ye.STOPPED:break;case ye.PLAYING:case ye.PAUSED:case ye.READY:this.stop();break;default:n(t)}break;case w.PLAYING:switch(t){case ye.PLAYING:break;case ye.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(we(this.liveOffset.getTotalOffset()))):this.seek(we(this.liveOffset.getTotalOffset()))),this.play();break;case ye.READY:this.play();break;case ye.STOPPED:this.prepare();break;default:n(t)}break;case w.PAUSED:switch(t){case ye.PLAYING:this.pause(),this.liveOffset.pause();break;case ye.PAUSED:break;case ye.READY:this.videoState.setState(ye.PAUSED),K(this.params.desiredState.playbackState,w.PAUSED);break;case ye.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 we=t=>-t/1e3;function Pe(){return S()}function Ae(t){return Pe()-t}function ke(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 _e(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=Ae(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(),i&&i()}},T=()=>{h=Pe(),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=Pe();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=Pe(),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)=>(s(t)&&(g=t),s(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 De{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 Re{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=Pe(),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=_e(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Pe()-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=Pe()}_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=Pe();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 Ie{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 De(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=ke(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=ke(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 Re(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=_e(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=Pe()-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=_e(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)}}}},T=()=>{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,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,i=Pe(),s=Math.min(1e4,e-i);$=i;const a=()=>{u||p()&&E.seek((()=>{p()&&($=Pe(),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():(T(),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=Pe(),h=i.currentTime;!this.paused&&i.buffered.length>1&&g===h&&d-y>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==h&&(g=h,y=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()&&($=Pe(),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: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=Pe();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&&Ae(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=Pe();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=_e(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 Le;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Le||(Le={}));const xe=[Le.PAUSED,Le.PLAYING,Le.READY],Ce=[Le.PAUSED,Le.PLAYING,Le.READY];class Oe{subscription=new i;video;videoState=new mt(Le.STOPPED);dash;representations$=new t([]);textTracksManager=new H;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new ve;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(lt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),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===Le.READY&&this.videoState.setState(Le.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(Le.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.videoState.setState(Le.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h(Ne)).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 Le.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(w.STOPPED);break;case Le.MANIFEST_READY:case Le.READY:break;case Le.PAUSED:this.params.desiredState.playbackState.setState(w.PAUSED);break;case Le.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 Ie({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:ut(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(Ne(i)),this.dash.reinit(ee(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)??it(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===Le.MANIFEST_READY&&this.videoState.setState(Le.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!==Le.STOPPED&&(this.videoState.startTransitionTo(Le.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Le.STOPPED)));if(e)return;if(Ce.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)&&xe.includes(t))this.seek(o+Ne(this.liveOffset.getTotalPausedTime()));else switch(t){case Le.STOPPED:return this.videoState.startTransitionTo(Le.MANIFEST_READY),void this.dash.attachSource(ee(this.params.source.url));case Le.MANIFEST_READY:this.videoState.startTransitionTo(Le.READY),this.prepare();break;case Le.READY:return void(i===w.PAUSED?this.videoState.setState(Le.PAUSED):i===w.PLAYING&&(this.videoState.startTransitionTo(Le.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Le.PAUSED)}))));case Le.PLAYING:return void(i===w.PAUSED&&(this.videoState.startTransitionTo(Le.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Le.PAUSED:return void(i===w.PLAYING&&(this.videoState.startTransitionTo(Le.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(Le.PAUSED)})),this.params.output.position$.next(Ne(this.liveOffset.getTotalOffset()))):this.seek(Ne(this.liveOffset.getTotalOffset()))));default:return n(t)}}}const Ne=t=>-t/1e3,Be=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=it({width:i,height:s})}return e??null},Me=async(t,e=t)=>{const i=await Rt(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=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(s[++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 i;videoState=new mt(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(lt(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,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(Ue.PLAYING),K(e.playbackState,w.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ue.PAUSED),K(e.playbackState,w.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ue.READY&&this.videoState.setState(Ue.READY),this.videoState.getState()===Ue.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(lt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Ue.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(Ue.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!==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),K(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(i?.to!==w.PAUSED&&s(h)&&this.seek(h),t){case Ue.READY:return void(e===w.PAUSED?(this.videoState.setState(Ue.PAUSED),K(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()):i?.to===w.PLAYING&&K(this.params.desiredState.playbackState,w.PLAYING));case Ue.PAUSED:return void(e===w.PLAYING?(this.videoState.startTransitionTo(Ue.PLAYING),this.playIfAllowed()):i?.to===w.PAUSED&&K(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 i;videoState=new mt(Fe.STOPPED);video;params;textTracksManager=new H;manifests$=new t([]);maxSeekBackTime$;liveOffset=new ve;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]),Me(ee(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(lt(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(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)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h(qe)).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(lt(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(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=ee(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await Rt(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(),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(qe(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!==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 e=qe(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(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(),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.liveOffset.pause(),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.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()))):i?.to===w.PAUSED&&(K(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((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class Qe{subscription=new i;videoState=new mt(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(lt(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||(Ge.Hls=e.default,Ge.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),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,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(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),K(t.playbackState,w.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ye.PAUSED),K(t.playbackState,w.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ye.READY&&this.videoState.setState(Ye.READY),this.videoState.getState()===Ye.PLAYING&&this.playIfAllowed()}),i)),n(ze(this.hls,Ge.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??'')??it({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(ze(this.hls,Ge.Events.LEVEL_LOADING).pipe(h((({url:t})=>lt(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,c=ze(this.hls,Ge.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===Ye.INITIALIZING)return;const r=a?.to;switch(i?.to!==w.PAUSED&&s(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),K(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),K(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),K(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'))},ti={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"'))},ei=(ti.h264||ti.h265)&&ti.aac,ii=!je,si=Je||je,ai=!Xe.hls||!si,ri=3e4,ni=18e4,oi=3,di=100,hi={cacheDuration:12e4},ui={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},ci={maxPausedTime:3e4},li={maxPausedTime:3e4};class pi{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([]),autoVideoTrackLimitingAvailable$:new t(!1),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 We(i.filter((e=>s(t.sources[e]))).filter((t=>{switch(t){case P.DASH:return Xe.mse&&Ze.mp4&&ei&&ii;case P.DASH_SEP:case P.DASH_SEP_VK:return Xe.mse&&Ze.mp4&&ei;case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.DASH_LIVE_WEBM:return Xe.mse&&Ze.webm&&ti.vp9&&ti.opus;case P.DASH_LIVE:case P.DASH_ONDEMAND:return Xe.mse&&Ze.mp4&&ei;case P.HLS:case P.HLS_LIVE:case P.HLS_ONDEMAND:return Xe.hls&&Ze.mp4&&si;case P.HLS_JS:return Xe.mse&&Ze.mp4&&ei&&ai;case P.MPEG:return Ze.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new We(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 ce({container:i,source:r,desiredState:s,output:a,config:hi,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 Zt({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 $e({container:i,source:r,desiredState:s,output:a,format:t,config:li,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: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 He({container:i,source:r,desiredState:s,output:a,config:ci,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_JS:{const r=e[t];return l(r),new Qe({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 re({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 Oe({container:i,source:r,desiredState:s,output:a,config:ui,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 se({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:ri,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(T(a)),n.desiredPlaybackState$.stateChangeEnded$.pipe(T(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(T({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),r.add(this.providerError$.pipe(y(di,{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]+ni?(e=[],this.switchToNextProvider()):(e[a]=t,this.reinitProvider()),a=(a+1)%oi}))),r}}const mi=(t,e,i)=>i*e+(1-i)*t;class fi{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 dt(`raw_${i}`),this.smoothedSeries$=new dt(`smoothed_${i}`),this.reportedSeries$=new dt(`reported_${i}`)}next(t){this.slow=mi(this.slow,t,this.params.emaAlphaSlow),this.fast=mi(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 Si;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Si||(Si={}));const gi=new Map;let bi=Si.RUNTIME;const vi=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(vi,'test'),localStorage.removeItem(vi),bi=Si.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(vi),bi=Si.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;bi=Si.RUNTIME}}})();const Ti=(t,e)=>{switch(bi){case Si.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Si.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Si.RUNTIME:return void gi.set(t,e);default:n(bi)}},yi=window.navigator.connection,Ei=()=>{const t=yi?.downlink;if(s(t)&&10!==t)return 1e3*t},$i=()=>{const t=yi?.rtt;if(s(t)&&3e3!==t)return t},wi=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Pi{throughput;rtt;subscription=new i;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Pi.load('one_video_throughput')||(e.useBrowserEstimation?Ei():void 0)||5e3,a=Pi.load('one_video_rtt')??(e.useBrowserEstimation?$i():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(wi(i,a,e.rttPenaltyRequestSize)),this.throughput=new fi({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new fi({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=Ei();t&&this.throughput.next(t);const e=$i();s(e)&&this.rtt.next(e)};yi&&'onchange'in yi&&this.subscription.add(r(yi,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ti('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ti('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})=>wi(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(Pi.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(bi){case Si.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Si.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Si.RUNTIME:return gi.get(t);default:n(bi)}})(t);if(s(e))return parseInt(e,10)??void 0}}const Ai=(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)})))})),ki=Ai((t=>t)),_i=Ai((t=>Math.round(1e3*t)+Date.now())),Di={[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 Ri{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new E;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new mt(w.STOPPED),seekPosition:new mt(void 0),volume:new mt({volume:1,muted:!1}),videoTrack:new mt(void 0),autoVideoTrackSwitching:new mt(!0),autoVideoTrackLimits:new mt({}),isLooped:new mt(!1),externalTextTracks:new mt([]),currentTextTrack:new mt(void 0),textTrackCuesSettings:new mt({})};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),autoQualityLimitingAvailable$:new t(!1),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:nt};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 Pi(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 pi({screenFormatsPriority:[...Di[A.SCREEN].live,...Di[A.SCREEN].vod],chromecastFormatsPriority:[...Di[A.CHROMECAST].live,...Di[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)=>st(t)?1:st(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.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(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(T(!0)),e.providerOutput.seekedEvent$.pipe(T(!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(_i({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(ki({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=ut(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),rt={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{at=t})),this.providerContainer.current$.subscribe((({type:t})=>ot('provider',t))),t.duration$.subscribe((t=>ot('duration',t))),t.availableVideoTracks$.pipe(b((t=>!!t.length)),m()).subscribe((t=>ot('tracks',t))),this.events.fatalError$.subscribe(new dt('fatalError')),this.events.managedError$.subscribe(new dt('managedError')),t.position$.subscribe(new dt('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new dt('quality')),t.currentBuffer$.subscribe(new dt('buffer')),t.isBuffering$.subscribe(new dt('isBuffering'))].forEach((t=>this.subscription.add(t))),ot('codecs',Object.keys(ti).filter((t=>ti[t])))}}const Ii='@vkontakte/videoplayer-core@2.0.46';export{k as ChromecastState,D as HttpConnectionType,w as PlaybackState,Ri as Player,Ii 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 g,filter as S,interval as b,timeout as v,combine as T,mapTo as y,throttle as E,Logger as $}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import w from'lodash/debounce';var P,A,k,_,D,R;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),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'}(A||(A={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(k||(k={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(D||(D={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(R||(R={}));const I={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:[A.DASH_WEBM,A.DASH_SEP,A.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,gapWatchdogInterval:50};class L{connection$=new t(void 0);castState$=new t(_.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(_.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(x),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{const n=r===_.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===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.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 x=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return n(t)}};var C,O,N,B;!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'}(O||(O={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(N||(N={})),function(t){t.MP4='mp4',t.WEBM='webm'}(B||(B={}));var M=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 U=(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},V=(t,e,i)=>U(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),F=(t,e,i,a)=>U(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}),H=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class q{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(U(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(U(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(U(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(q.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)&&H(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 G=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},Y=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 z{_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 Q=(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}},W=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 j=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((()=>Q(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$:W(t),firstFrame$:Y(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 K=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}},X=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const Z={[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:856,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}},tt=(t,e)=>Z[t].height>Z[e].height,et=(t,e)=>Z[t].height<Z[e].height,it=Object.keys(Z).sort(((t,e)=>et(t,e)?-1:1)),st=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return it.find((t=>{const e=Z[t];return e.width>=s&&e.height>=i}))},at=t=>t===J.INVARIANT;let rt=!1,nt={};const ot=t=>{t(nt)},dt=(t,e)=>{rt&&(nt.meta=nt.meta??{},nt.meta[t]=e)};class ht{name;constructor(t){this.name=t}next(t){if(!rt)return;nt.series=nt.series??{};const e=nt.series[this.name]??[];e.push([Date.now(),t]),nt.series[this.name]=e}}const ut=new ht('best_bitrate'),ct=(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&&st(u),l=t.filter((t=>!at(t.quality))).sort(((t,e)=>tt(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&&tt(n.min,m)||s(n.max)&&p&&et(n.max,p),g=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),g=f||(a(n.max)||(S=t.quality,b=n.max,Z[S].height<=Z[b].height))&&(a(n.min)||((t,e)=>Z[t].height>=Z[e].height)(t.quality,n.min));var S,b;return e&&h&&m&&g}))[0];return g&&g.bitrate&&ut.next(g.bitrate),g??l[Math.ceil((l.length-1)/2)]??t[0]};var lt=(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)},pt=t=>new URL(t).hostname;const mt=(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(w((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 ft{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 St(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function bt(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 vt(t,e,i){return e&&bt(t.prototype,e),i&&bt(t,i),t}function Tt(t){return(Tt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function yt(t,e){return(yt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Et(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function $t(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?Et(t):e}function wt(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 $t(this,i)}}function Pt(t,e,i){return(Pt='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 At=function(){function t(){St(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return vt(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}(),kt=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&&yt(t,e)}(i,At);var e=wt(i);function i(){var t;return St(this,i),(t=e.call(this)).listeners||At.call(Et(t)),Object.defineProperty(Et(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(Et(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return vt(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)),Pt(Tt(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),_t=function(){function t(){St(this,t),Object.defineProperty(this,'signal',{value:new kt,writable:!0,configurable:!0})}return vt(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&&(_t.prototype[Symbol.toStringTag]='AbortController',kt.prototype[Symbol.toStringTag]='AbortSignal');var Dt=gt.AbortController=_t;gt.AbortSignal=kt;var Rt,It=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}},Lt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?R.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'}(Rt||(Rt={}));class xt{throughputEstimator;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new Dt;subscription=new i;constructor({throughputEstimator:t}={}){this.throughputEstimator=t}onHeadersReceived(t){const{type:e,reused:i}=Lt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchManifest(t){const e=await It(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Ct);return e?(this.onHeadersReceived(e.headers),e.text()):null}async fetchRange(t,e,i,{method:s=Rt.HEADER,onProgress:a,signal:d}={}){let h=t;const u=new Headers;switch(s){case Rt.HEADER:u.append('Range',`${e}-${i}`);break;case Rt.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 Dt;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=g(),p=await It(fetch).fetch(h,{headers:u,signal:c}).catch(Ct);if(this.throughputEstimator?.addRawRtt(g()-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(),S=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,Ct(t)},P=async({done:t,value:e})=>{0===v&&this.lastRequestFirstBytes$.next(g()-l),t?a?.(E,v):e&&(y.set(e,v),v+=e.byteLength,a?.(E,v),await(S?.read().then(P,w)))};return await(S?.read().then(P,w)),$?null:T}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:Rt.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:Rt.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 Ct=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Ot,Nt;!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'}(Ot||(Ot={})),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'}(Nt||(Nt={}));const Bt={[Ot.EBML]:{type:Nt.Master},[Ot.EBMLVersion]:{type:Nt.UnsignedInteger},[Ot.EBMLReadVersion]:{type:Nt.UnsignedInteger},[Ot.EBMLMaxIDLength]:{type:Nt.UnsignedInteger},[Ot.EBMLMaxSizeLength]:{type:Nt.UnsignedInteger},[Ot.DocType]:{type:Nt.String},[Ot.DocTypeVersion]:{type:Nt.UnsignedInteger},[Ot.DocTypeReadVersion]:{type:Nt.UnsignedInteger},[Ot.Void]:{type:Nt.Binary},[Ot.Segment]:{type:Nt.Master},[Ot.SeekHead]:{type:Nt.Master},[Ot.Seek]:{type:Nt.Master},[Ot.SeekID]:{type:Nt.Binary},[Ot.SeekPosition]:{type:Nt.UnsignedInteger},[Ot.Info]:{type:Nt.Master},[Ot.TimestampScale]:{type:Nt.UnsignedInteger},[Ot.Duration]:{type:Nt.Float},[Ot.Tracks]:{type:Nt.Master},[Ot.Chapters]:{type:Nt.Master},[Ot.Cluster]:{type:Nt.Master},[Ot.Attachments]:{type:Nt.Master},[Ot.Tags]:{type:Nt.Master},[Ot.Cues]:{type:Nt.Master},[Ot.CuePoint]:{type:Nt.Master},[Ot.CueTime]:{type:Nt.UnsignedInteger},[Ot.CueTrackPositions]:{type:Nt.Master},[Ot.CueTrack]:{type:Nt.UnsignedInteger},[Ot.CueClusterPosition]:{type:Nt.UnsignedInteger},[Ot.CueRelativePosition]:{type:Nt.UnsignedInteger},[Ot.CueDuration]:{type:Nt.UnsignedInteger},[Ot.CueBlockNumber]:{type:Nt.UnsignedInteger},[Ot.CueCodecState]:{type:Nt.UnsignedInteger},[Ot.CueReference]:{type:Nt.Master},[Ot.CueRefTime]:{type:Nt.UnsignedInteger}},Mt=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=Ut(t,i),a=s in Bt,r=a?Bt[s].type:Nt.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))+Ut(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}},Ut=(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},Vt=(t,e)=>{switch(e){case Nt.SignedInteger:return t.getInt8(0);case Nt.UnsignedInteger:return Ut(t);case Nt.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Nt.String:return new TextDecoder('ascii').decode(t);case Nt.UTF8:return new TextDecoder('utf-8').decode(t);case Nt.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Nt.Master:case Nt.Binary:return t;default:n(e)}},Ft=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Mt(s);if(!e(a))return;a.type===Nt.Master&&Ft(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Ht=[Ot.Info,Ot.SeekHead,Ot.Tracks,Ot.Chapters,Ot.Cluster,Ot.Cues,Ot.Attachments,Ot.Tags],qt={validateData:t=>{if(t.getUint32(0)!==Ot.EBML)return!1;let e,i,s;const a=Mt(t);return Ft(a.value,(({tag:t,type:a,value:r})=>(t===Ot.EBMLReadVersion?e=Vt(r,a):t===Ot.DocType?i=Vt(r,a):t===Ot.DocTypeReadVersion&&(s=Vt(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 Ft(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===Ot.SeekID){const t=Vt(c,u);n=Ut(t)}else t!==Ot.SeekPosition&&(n=void 0);return t===Ot.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Ot.Info?o=!0:t===Ot.SeekHead?d=!0:t===Ot.TimestampScale?s=Vt(c,u):t===Ot.Duration?a=Vt(c,u):t===Ot.SeekPosition&&n===Ot.Cues?r=Vt(c,u):o&&d&&Ht.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 Ft(t,(({tag:t,type:e,value:s})=>{switch(t){case Ot.Cues:i=!0;break;case Ot.CuePoint:o&&r(o)&&n.push(o),o={};break;case Ot.CueTime:o&&(o.time=Vt(s,e));break;case Ot.CueTrackPositions:break;case Ot.CueClusterPosition:o&&(o.position=Vt(s,e));break;default:i&&Ht.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:N.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}}}))}},Gt=new TextDecoder('ascii'),Yt={validateData:t=>'ftyp'===Gt.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=Gt.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:N.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i}};class zt{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;abortController=new Dt;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;bufferUpdateQueue=[];bufferUpdateQueueInProgress=!1;constructor(t,e,i,s,{fetcher:a,tuning:r}){switch(this.fetcher=a,this.tuning=r,this.container=i,i){case B.MP4:this.containerParser=Yt;break;case B.WEBM:this.containerParser=qt;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?N.FED:N.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 Dt,this.abortBuffer(),await this.appendDataToBuffer(e,this.abortController.signal),s(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((t=>{t.status===N.FED&&(t.status=N.NONE)}))}async maintain(t){if(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer)||this.onLastSegment$.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=lt(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===N.FED&&!n.length&&lt(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&&o.status===N.FED&&(this.fullyBuffered$.next(!0),s===o&&this.onLastSegment$.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===N.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===N.NONE)a.push(i);else if([N.DOWNLOADING,N.DOWNLOADED,N.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=N.DOWNLOADING;const{signal:a}=this.abortController,r=(t,i)=>{t.status=N.DOWNLOADED,this.appendDataToBuffer(i,a).then((i=>{if(!i||a.aborted)t.status=N.NONE;else if(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=N.FED,this.sourceBuffer){let i={representation:e.id,from:t.time.from,to:t.time.to};for(let e=0;e<this.sourceBuffer.buffered.length;e++){const s=1e3*this.sourceBuffer.buffered.start(e),a=1e3*this.sourceBuffer.buffered.end(e);if(!(a<=t.time.from||s>=t.time.to)){if(s<=t.time.from&&a>=t.time.to){i=void 0;break}a>t.time.from&&a<t.time.to&&(i.from=a),s<t.time.to&&s>t.time.from&&(i.to=s)}}i&&i.to>i.from&&this.gaps.push(i)}}))},n=(e,s)=>{for(const a of t)a.status===N.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===N.DOWNLOADING&&(e.status=N.NONE);return}const o=await this.fetcher.fetchRange(e.url,i,s,{method:Rt.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===N.DOWNLOADING&&(e.status=N.NONE);o&&!a.aborted&&d&&h&&d.status===N.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;const i=()=>{if(this.bufferUpdateQueueInProgress)return;this.bufferUpdateQueueInProgress=!0;const t=this.bufferUpdateQueue.shift();if(!t)return void(this.bufferUpdateQueueInProgress=!1);const{data:e,callback:s}=t;if(!this.sourceBuffer)return this.bufferUpdateQueueInProgress=!1,void s(!1);try{this.sourceBuffer.appendBuffer(e)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),this.bufferUpdateQueueInProgress=!1,void s(!1)}zt.waitForBufferUpdate(this.sourceBuffer).then((()=>{this.bufferUpdateQueueInProgress=!1,s(!0),i()}))};return new Promise((e=>{this.bufferUpdateQueue.push({data:t,callback:e}),this.sourceBuffer?this.sourceBuffer.updating?zt.waitForBufferUpdate(this.sourceBuffer).then(i):i():e(!1)}))}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!==N.FED||t||(i.status=N.NONE)}}static async waitForBufferUpdate(t){return new Promise((e=>t?t.addEventListener('updateend',(()=>e())):e()))}}const Qt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},Wt=['timeupdate','progress','play','seeked','stalled'];var jt,Jt;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(jt||(jt={}));class Kt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new i;fetcher;state$=new ft(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;gapWatchdogStarted=!1;gapWatchdogSubscription;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new xt({throughputEstimator:this.throughputEstimator})}async initManifest(t,e){this.element=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(O.WEBM_AS_IN_FFMPEG)||n.includes(O.WEBM_AS_IN_SPEC)?B.WEBM:B.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),g=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,S=u.getAttribute('frameRate')??'',b=u.getAttribute('quality')??void 0,v=S?Qt(S):void 0,T=`${u.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${f}p`:'audio'===l?`${g}Kbps`:c}`,y=u.querySelector('BaseURL')?.textContent?.trim()??'',E=new URL(y,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:C.VIDEO,audio:C.AUDIO,text:C.TEXT}[l];L&&i[L].push({id:T,kind:L,profiles:$,initRange:k,indexRange:I,bitrate:g,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 zt(C.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new zt(C.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$,o(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(S((()=>!(!this.videoBufferManager||!this.audioBufferManager)&&[this.videoBufferManager.fullyBuffered$.getValue(),this.audioBufferManager.fullyBuffered$.getValue()].every((t=>t))&&[this.videoBufferManager.onLastSegment$.getValue(),this.audioBufferManager.onLastSegment$.getValue()].some((t=>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(...Wt.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.subscription.add(r(this.element,'waiting').subscribe((()=>{if(this.element&&2===this.element.readyState&&!this.element.seeking)for(let t=0;t<this.element.buffered.length;t++){if(this.element.buffered.start(t)<=this.element.currentTime&&this.element.buffered.end(t)>this.element.currentTime){this.element.currentTime=this.element.currentTime;break}}}))),this.tick())}async switchRepresentation(t,e){const i={[C.VIDEO]:this.videoBufferManager,[C.AUDIO]:this.audioBufferManager,[C.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||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=b(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;for(const e of[this.videoBufferManager,this.audioBufferManager])for(const i of e.gaps)if(i.from<=t&&i.to>t&&e.playingRepresentation$.getValue()===i.representation){if(1e3*this.element.duration-i.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=i.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Jt||(Jt={}));const Xt=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?K(r):void 0)??st({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Zt=(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 te{subscription=new i;videoState=new ft(Jt.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new q;videoTracks=[];audioRepresentations;constructor(t){this.params=t,this.video=G(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(pt(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Kt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=j(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(S(s),m()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(V(this.video,e.isLooped,a)),this.subscription.add(F(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),n(mt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Jt.PLAYING),X(e.playbackState,P.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(Jt.PAUSED),X(e.playbackState,P.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Jt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(S((({to:t})=>t===jt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Jt.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=lt(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=ct(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=Zt(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=Zt(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(C.VIDEO,t.id),e&&this.player.switchRepresentation(C.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=Xt(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!==P.PAUSED&&s(r)&&t!==Jt.STOPPED&&e!==P.STOPPED&&this.seek(r),e!==P.STOPPED){if(t===Jt.STOPPED)return this.videoState.startTransitionTo(Jt.READY),void this.prepare();switch(t){case Jt.READY:return void(e===P.PAUSED?(this.videoState.setState(Jt.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Jt.PLAYING),this.playIfAllowed()));case Jt.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Jt.PAUSED),this.video.pause()):i?.to===P.PLAYING&&X(this.params.desiredState.playbackState,P.PLAYING));case Jt.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Jt.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&X(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Jt.STOPPED&&(this.videoState.startTransitionTo(Jt.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(Jt.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){M(this.video).then((t=>{t||(this.videoState.setState(Jt.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var ee;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(ee||(ee={}));var ie=(t,e=0,i=ee.OFFSET_P)=>{switch(i){case ee.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case ee.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 se;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(se||(se={}));class ae{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new ft(se.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 A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_SEP_VK:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_VK:case A.HLS:case A.HLS_JS:case A.HLS_ONDEMAND:return!1;case A.HLS_LIVE:case A.DASH_LIVE:case A.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(),X(this.params.desiredState.playbackState,P.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default: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(se.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(se.PLAYING),X(this.params.desiredState.playbackState,P.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!==se.PAUSED&&t!==se.PLAYING||(this.videoState.setState(se.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==se.PLAYING&&t!==se.PAUSED||(this.videoState.setState(se.PLAYING),X(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===se.READY&&this.videoState.setState(se.READY)}handleRemoteStop(){this.videoState.getState()!==se.STOPPED&&this.videoState.setState(se.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 A.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 A.HLS:case A.HLS_ONDEMAND:{const s=e[t];l(s),i=s.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_SEP_VK:case A.DASH_ONDEMAND:case A.DASH_WEBM_VK:case A.DASH_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS_LIVE:{const s=e[t];l(s),i=ie(s.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case A.DASH_LIVE_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case A.HLS_JS:case A.DASH:case A.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===P.STOPPED)return void(t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.stop()));if(e)return;const o=r?.to;if(a?.to!==P.PAUSED&&s(o)&&t!==se.STOPPED)this.seek(o);else switch(i){case P.PLAYING:switch(t){case se.PLAYING:break;case se.PAUSED:case se.READY:this.videoState.startTransitionTo(se.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case se.STOPPED:this.videoState.startTransitionTo(se.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case se.PLAYING:this.videoState.startTransitionTo(se.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case se.PAUSED:break;case se.READY:this.videoState.startTransitionTo(se.PAUSED),this.videoState.setState(se.PAUSED);break;case se.STOPPED:this.videoState.startTransitionTo(se.READY),this.prepare();break;default:n(t)}break;default:n(i)}}}var re;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(re||(re={}));class ne{subscription=new i;videoState=new ft(re.STOPPED);video;trackUrls={};params;textTracksManager=new q;constructor(t){this.params=t,this.video=G(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=j(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(V(this.video,e.isLooped,i)),this.subscription.add(F(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(re.PLAYING),X(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(re.PAUSED),X(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.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()===re.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(pt(e))}playIfAllowed(){M(this.video).then((t=>{t||(this.videoState.setState(re.PAUSED),X(this.params.desiredState.playbackState,P.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===P.STOPPED)return void(t!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===re.STOPPED)return this.videoState.startTransitionTo(re.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!==P.PAUSED&&s(o)&&this.seek(o),t){case re.READY:return void(e===P.PAUSED?(this.videoState.setState(re.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()));case re.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):i?.to===P.PLAYING&&X(this.params.desiredState.playbackState,P.PLAYING));case re.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&X(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}class oe{_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 de{_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(de._str2ua(t.substr(o))),o=t.length};this._lastXhr=new oe(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=de._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 he{_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 oe(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?Qt(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 de({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 ue;!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'}(ue||(ue={}));const ce=[ue.PAUSED,ue.PLAYING];class le{videoState=new ft(ue.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new q;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=G(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(pt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new z(this.video),this.dash=new he({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=j(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()===ue.PLAYING||this.videoState.getState()===ue.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(V(this.video,e.isLooped,i)),this.subscription.add(F(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(mt(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ue.READY&&this.videoState.setState(ue.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(ue.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(ue.PLAYING),X(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(ue.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=lt(this.video.buffered,1e3*this.video.currentTime),s=Math.min(i/this.params.tuning.dash.forwardBufferTarget,1);h=ct(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(T({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(S((t=>t.to===ue.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(S(s))}).pipe(m()).subscribe((()=>this.videoState.setState(ue.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(S(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=lt(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(pt(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Lt(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(S(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&&K(i.name))??st(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(ue.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(){M(this.video).then((t=>{t||(this.videoState.setState(ue.PAUSED),X(this.params.desiredState.playbackState,P.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===P.STOPPED)return void(t!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0)));if(e)return;const o=r?.to;switch(a?.to!==P.PAUSED&&s(o)&&ce.includes(t)&&this.seek(o),t){case ue.STOPPED:return this.videoState.startTransitionTo(ue.MANIFEST_LOADED),void this.prepare();case ue.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ue.INITIAL_REPRESENTATION_SELECTED);case ue.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ue.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ue.METADATA_LOADED:return this.videoState.startTransitionTo(ue.READY),void this.dash.seek(o??0);case ue.READY:return void(i===P.PAUSED?(this.videoState.setState(ue.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()));case ue.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):a?.to===P.PLAYING&&X(this.params.desiredState.playbackState,P.PLAYING));case ue.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):a?.to===P.PAUSED&&X(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}var pe=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)},me=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 fe=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]=fe(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(fe),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 Dt,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 It(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]=fe(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]=fe(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]=fe(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 Se{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(Se.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;Se.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const be=(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 Se(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var ve=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 ye={};var Ee;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ee||(Ee={}));const $e=(t,e)=>new p((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class we{subscription=new i;videoState=new ft(Ee.DOWNLOADING_LIB);video;player;params;textTracksManager=new q;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=G(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(pt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),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||(ye.MediaPlayer=e.MediaPlayer,ye.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(ye.MediaPlayer,'dashjs not loaded'),l(ye.Debug,'dashjs not loaded'),this.player=ye.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?Qt(t.frameRate+''):void 0),!0)));(this.params.format===A.DASH_WEBM||this.params.format===A.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=be(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&&me(this.player),pe(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Ee.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(mt(this.video),this.elementSize$),r($e(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($e(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=$e(this.player,'qualityChangeRendered').pipe(S((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(S(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(S((({to:t})=>t===Ee.STREAM_INITIALIZED)),m()).subscribe((()=>{this.subscription.add(U(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(U(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),r($e(this.player,'bufferStateChanged').pipe(S((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r($e(this.player,'fragmentLoadingStarted').pipe(h((t=>pt(t.request.url)))),t.hostname$),r($e(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=st(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(Ee.STREAM_INITIALIZED),this.videoState.startTransitionTo(Ee.READY)})),r($e(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=ct(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(T({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(S(s))}).pipe(S((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>Pe(t)))),this.params.output.duration$);const d=$e(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(T({availableFrom:this.availableFrom$.pipe(S(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(S((()=>!1===this.isLive$.getValue()))),t.position$),r($e(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r($e(this.player,'playbackEnded'),t.endedEvent$),r($e(this.player,'playbackProgress').pipe(h((()=>Q(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r($e(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Ee.PLAYING),X(e.playbackState,P.PLAYING)})),r($e(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Ee.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r($e(this.player,'playbackPaused'),(()=>{this.videoState.setState(Ee.PAUSED),X(e.playbackState,P.PAUSED)})),r($e(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===Ee.READY&&this.videoState.setState(Ee.READY)})),r(this.isLive$,t.isLive$),r(mt(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}=ve(this.player);r(c,this.maxSeekBackTime$),r(l.pipe(m()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(T({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(S((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($e(this.player,'manifestLoaded').pipe(m()).subscribe((()=>{const e=Date.now();this.subscription.add($e(this.player,'playbackPlaying').pipe(m()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-e)),i))}),i)),this.subscription.add(V(this.video,e.isLooped,i));const{volumeState$:p,looped$:g}=j(this.video);this.subscription.add(F(this.video,e.volume,p,i)),this.subscription.add(p.subscribe(t.volume$,i)),this.subscription.add(g.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(Ee.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Ee.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(Pe(i));const s=ie(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ee.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(Ee.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Ee.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===Ee.DOWNLOADING_LIB||t===Ee.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==P.PAUSED&&s(o)&&t!==Ee.STOPPED&&e!==P.STOPPED&&(r?this.seek(o+Pe(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case P.STOPPED:switch(t){case Ee.STOPPED:break;case Ee.PLAYING:case Ee.PAUSED:case Ee.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Ee.PLAYING:break;case Ee.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(Pe(this.liveOffset.getTotalOffset()))):this.seek(Pe(this.liveOffset.getTotalOffset()))),this.play();break;case Ee.READY:this.play();break;case Ee.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Ee.PLAYING:this.pause(),this.liveOffset.pause();break;case Ee.PAUSED:break;case Ee.READY:this.videoState.setState(Ee.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED);break;case Ee.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 Pe=t=>-t/1e3;function Ae(){return g()}function ke(t){return Ae()-t}function _e(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 De(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,p=0,m=!1,f='arraybuffer',g=7e3,S=2e3,b=()=>{if(c)return;l(h);const t=ke(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,T()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},T=()=>{h=Ae(),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=Ae();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=Ae(),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)=>(s(t)&&(S=t),s(e)&&(g=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 Re{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 Ie{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=Ae(),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=De(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ae()-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=Ae()}_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=Ae();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 Le{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 Re(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=_e(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=_e(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 Ie(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=De(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()},g=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},S=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 g(1);const i=Ae()-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,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(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=De(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&&S(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)}}}},T=()=>{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,g,S,y,E=v(t.jidxUrl),$=0;const w=()=>{g&&(clearTimeout(g),g=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=$+t,i=Ae(),s=Math.min(1e4,e-i);$=i;const a=()=>{u||p()&&E.seek((()=>{p()&&($=Ae(),P(),w())}))};s>0?g=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():(T(),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=Ae(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-y>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,y=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()&&($=Ae(),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: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=Ae();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&&ke(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=Ae();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=De(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;M(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 xe;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xe||(xe={}));const Ce=[xe.PAUSED,xe.PLAYING,xe.READY],Oe=[xe.PAUSED,xe.PLAYING,xe.READY];class Ne{subscription=new i;video;videoState=new ft(xe.STOPPED);dash;representations$=new t([]);textTracksManager=new q;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=G(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(pt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=j(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===xe.READY&&this.videoState.setState(xe.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(xe.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.videoState.setState(xe.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h(Be)).subscribe(this.params.output.duration$)).add(T({zeroTime:this.zeroTime$.pipe(S(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(V(this.video,this.params.desiredState.isLooped,e)).add(F(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(W(this.video).subscribe(this.params.output.firstBytesEvent$)).add(Y(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Z[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case xe.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case xe.MANIFEST_READY:case xe.READY:break;case xe.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case xe.PLAYING:this.params.desiredState.playbackState.setState(P.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 Le({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:ct(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(Be(i)),this.dash.reinit(ie(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=K(t.name)??st(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===xe.MANIFEST_READY&&this.videoState.setState(xe.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===P.STOPPED)return void(t!==xe.STOPPED&&(this.videoState.startTransitionTo(xe.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(xe.STOPPED)));if(e)return;if(Oe.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!==P.PAUSED&&s(o)&&Ce.includes(t))this.seek(o+Be(this.liveOffset.getTotalPausedTime()));else switch(t){case xe.STOPPED:return this.videoState.startTransitionTo(xe.MANIFEST_READY),void this.dash.attachSource(ie(this.params.source.url));case xe.MANIFEST_READY:this.videoState.startTransitionTo(xe.READY),this.prepare();break;case xe.READY:return void(i===P.PAUSED?this.videoState.setState(xe.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(xe.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(xe.PAUSED)}))));case xe.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(xe.PAUSED),this.liveOffset.pause(),this.dash.pause()));case xe.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(xe.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(xe.PAUSED)})),this.params.output.position$.next(Be(this.liveOffset.getTotalOffset()))):this.seek(Be(this.liveOffset.getTotalOffset()))));default:return n(t)}}}const Be=t=>-t/1e3,Me=t=>{let e=null;if(t.QUALITY&&(e=K(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=st({width:i,height:s})}return e??null},Ue=async(t,e=t)=>{const i=await It(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=Me(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 Ve;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ve||(Ve={}));class Fe{subscription=new i;videoState=new ft(Ve.STOPPED);video;params;textTracksManager=new q;manifests$=new t([]);constructor(t){this.params=t,this.video=G(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(pt(this.params.source.url)),Ue(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=j(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(V(this.video,e.isLooped,i)),this.subscription.add(F(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(Ve.PLAYING),X(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ve.PAUSED),X(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ve.READY&&this.videoState.setState(Ve.READY),this.videoState.getState()===Ve.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(pt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Ve.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(){M(this.video).then((t=>{t||(this.videoState.setState(Ve.PAUSED),X(this.params.desiredState.playbackState,P.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===P.STOPPED)return void(t!==Ve.STOPPED&&(this.videoState.startTransitionTo(Ve.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(Ve.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===Ve.STOPPED)return this.videoState.startTransitionTo(Ve.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(Ve.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!==P.PAUSED&&s(h)&&this.seek(h),t){case Ve.READY:return void(e===P.PAUSED?(this.videoState.setState(Ve.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ve.PLAYING),this.playIfAllowed()));case Ve.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ve.PAUSED),this.video.pause()):i?.to===P.PLAYING&&X(this.params.desiredState.playbackState,P.PLAYING));case Ve.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ve.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&X(this.params.desiredState.playbackState,P.PAUSED));case Ve.CHANGING_MANIFEST:break;default:return n(t)}}}var He;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(He||(He={}));class qe{subscription=new i;videoState=new ft(He.STOPPED);video;params;textTracksManager=new q;manifests$=new t([]);maxSeekBackTime$;liveOffset=new Te;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=G(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]),Ue(ie(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(pt(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=j(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(F(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(He.PLAYING),X(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(He.PAUSED),X(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===He.READY&&this.videoState.setState(He.READY),this.videoState.getState()===He.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h(Ge)).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(pt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===He.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(T({startTime:this.manifestStartTime$.pipe(S(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=ie(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await It(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(){M(this.video).then((t=>{t||(this.videoState.setState(He.PAUSED),this.liveOffset.pause(),X(this.params.desiredState.playbackState,P.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(Ge(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===P.STOPPED)return void(t!==He.STOPPED&&(this.videoState.startTransitionTo(He.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(He.STOPPED),X(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===He.STOPPED)return this.videoState.startTransitionTo(He.READY),void this.prepare();if(r||o){const t=this.videoState.getState();this.videoState.setState(He.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const e=Ge(this.liveOffset.getTotalOffset());return this.prepare(),void(d&&!a(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const h=d?.to;if(i?.to!==P.PAUSED&&s(h))return this.videoState.startTransitionTo(He.READY),this.seek(h+Ge(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case He.READY:return void(e===P.PAUSED?(this.videoState.setState(He.PAUSED),this.liveOffset.pause(),X(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(He.PLAYING),this.playIfAllowed()));case He.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(He.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&X(this.params.desiredState.playbackState,P.PLAYING));case He.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(He.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Ge(this.liveOffset.getTotalOffset()))):this.seek(Ge(this.liveOffset.getTotalOffset()))):i?.to===P.PAUSED&&(X(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case He.CHANGING_MANIFEST:break;default:return n(t)}}}const Ge=t=>-t/1e3,Ye={};var ze;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ze||(ze={}));const Qe=(t,e)=>new p((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class We{subscription=new i;videoState=new ft(ze.INITIALIZING);video;params;hls;textTracksManager=new q;trackLevels=new Map;constructor(t){this.video=G(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(pt(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||(Ye.Hls=e.default,Ye.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Ye.Hls,'hls.js not loaded'),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ze.STOPPED)}subscribe(){l(Ye.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=j(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(V(this.video,t.isLooped,i)),this.subscription.add(F(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qe(this.hls,Ye.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(ze.PLAYING),X(t.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(ze.PAUSED),X(t.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ze.READY&&this.videoState.setState(ze.READY),this.videoState.getState()===ze.PLAYING&&this.playIfAllowed()}),i)),n(Qe(this.hls,Ye.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=K(e.attrs.QUALITY??'')??st({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(Qe(this.hls,Ye.Events.LEVEL_LOADING).pipe(h((({url:t})=>pt(t)))),e.hostname$),this.subscription.add(U(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,c=Qe(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(S(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(U(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===ze.INITIALIZING)return;const r=a?.to;switch(i?.to!==P.PAUSED&&s(r)&&this.seek(r),e){case P.STOPPED:switch(t){case ze.STOPPED:break;case ze.READY:case ze.PLAYING:case ze.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case ze.PLAYING:break;case ze.STOPPED:this.prepare();break;case ze.READY:case ze.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case ze.PAUSED:break;case ze.STOPPED:this.prepare();break;case ze.READY:this.videoState.setState(ze.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED);break;case ze.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(ze.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ze.PLAYING);await M(this.video)||(this.videoState.setState(ze.PAUSED),X(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ze.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(ze.STOPPED),X(this.params.desiredState.playbackState,P.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 Je=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),Ke=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Xe=document.createElement('video'),Ze={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Xe.canPlayType?.('application/x-mpegurl')||Xe.canPlayType?.('vnd.apple.mpegURL'))},ti={mp4:Boolean(Xe.canPlayType?.('video/mp4')),webm:Boolean(Xe.canPlayType?.('video/webm'))},ei={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"'))},ii=(ei.h264||ei.h265)&&ei.aac,si=!Je,ai=Ke||Je,ri=!Ze.hls||!ai,ni=3e4,oi=18e4,di=3,hi=100,ui={cacheDuration:12e4},ci={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},li={maxPausedTime:3e4},pi={maxPausedTime:3e4};class mi{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([]),autoVideoTrackLimitingAvailable$:new t(!1),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 A.DASH:return Ze.mse&&ti.mp4&&ii&&si;case A.DASH_SEP:case A.DASH_SEP_VK:return Ze.mse&&ti.mp4&&ii;case A.DASH_WEBM:case A.DASH_WEBM_VK:case A.DASH_LIVE_WEBM:return Ze.mse&&ti.webm&&ei.vp9&&ei.opus;case A.DASH_LIVE:case A.DASH_ONDEMAND:return Ze.mse&&ti.mp4&&ii;case A.HLS:case A.HLS_LIVE:case A.HLS_ONDEMAND:return Ze.hls&&ti.mp4&&ai;case A.HLS_JS:return Ze.mse&&ti.mp4&&ii&&ri;case A.MPEG:return ti.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 k.SCREEN:return this.createScreenProvider(e);case k.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 A.DASH:{const r=e[t];return l(r),new le({container:i,source:r,desiredState:s,output:a,config:ui,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_SEP_VK:case A.DASH_WEBM_VK:{const r=e[t];return l(r),new te({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_ONDEMAND:case A.DASH_LIVE_WEBM:{const r=e[t];return l(r),new we({container:i,source:r,desiredState:s,output:a,format:t,config:pi,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS:case A.HLS_ONDEMAND:{const r=e[t];return l(r),new Fe({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS_LIVE:{const r=e[t];return l(r),new qe({container:i,source:r,desiredState:s,output:a,config:li,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS_JS:{const r=e[t];return l(r),new We({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.MPEG:{const r=e[t];return l(r),new ne({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE:{const r=e[t];return l(r),new Ne({container:i,source:r,desiredState:s,output:a,config:ci,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 ae({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()?k.CHROMECAST:k.SCREEN}chooseFormat(t){switch(t){case k.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case k.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case k.SCREEN:return this.screenFormatsIterator.next();case k.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case k.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case k.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:ni,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(E(hi,{leading:!1,trailing:!0})).subscribe((()=>{const t=Date.now();this.current$.getValue().destination===k.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(e[a])&&t<e[a]+oi?(e=[],this.switchToNextProvider()):(e[a]=t,this.reinitProvider()),a=(a+1)%di}))),r}}const fi=(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 ht(`raw_${i}`),this.smoothedSeries$=new ht(`smoothed_${i}`),this.reportedSeries$=new ht(`reported_${i}`)}next(t){this.slow=fi(this.slow,t,this.params.emaAlphaSlow),this.fast=fi(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 Si;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Si||(Si={}));const bi=new Map;let vi=Si.RUNTIME;const Ti=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Ti,'test'),localStorage.removeItem(Ti),vi=Si.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Ti),vi=Si.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;vi=Si.RUNTIME}}})();const yi=(t,e)=>{switch(vi){case Si.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Si.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Si.RUNTIME:return void bi.set(t,e);default:n(vi)}},Ei=window.navigator.connection,$i=()=>{const t=Ei?.downlink;if(s(t)&&10!==t)return 1e3*t},wi=()=>{const t=Ei?.rtt;if(s(t)&&3e3!==t)return t},Pi=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Ai{throughput;rtt;subscription=new i;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Ai.load('one_video_throughput')||(e.useBrowserEstimation?$i():void 0)||5e3,a=Ai.load('one_video_rtt')??(e.useBrowserEstimation?wi():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Pi(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=$i();t&&this.throughput.next(t);const e=wi();s(e)&&this.rtt.next(e)};Ei&&'onchange'in Ei&&this.subscription.add(r(Ei,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{yi('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{yi('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(T({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(h((({throughput:t,rtt:i})=>Pi(t,i,e.rttPenaltyRequestSize))),S((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=g();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=g()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,s=g()})))}a.add(r(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=g(),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=g();let a=0,r=g();const n=i=>{e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:t,value:d})=>{t?this.addRawSpeed(i,g()-s):d&&(i+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&g()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,g()-r),a=0,r=g()),await(e?.read().then(o,n)))};e?.read().then(o,n)}addRawSpeed(t,e){if(Ai.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(vi){case Si.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Si.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Si.RUNTIME:return bi.get(t);default:n(vi)}})(t);if(s(e))return parseInt(e,10)??void 0}}const ki=(t=(t=>t))=>({playbackState:e,seekPosition:r,playbackAbort$:n,looped$:d,position$:u})=>new p((c=>{let l;const p=e.transitionEnded$.pipe(S((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),m=e.stateChangeEnded$.pipe(S((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),f=r.stateChangeEnded$.pipe(S((t=>s(t.to)&&(e.getTransition()?.from??e.getState())===P.PLAYING))),g=r.stateChangeEnded$.pipe(S((t=>a(t.to)&&(e.getTransition()?.from??e.getState())===P.PLAYING))),b=o(p,g).pipe(h((()=>t(u.getValue())))),v=o(o(m,f,n).pipe(h((()=>t(u.getValue())))),d.pipe(h(t)));return(new i).add(b.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)})))})),_i=ki((t=>t)),Di=ki((t=>Math.round(1e3*t)+Date.now())),Ri={[k.SCREEN]:{vod:[A.HLS,A.HLS_ONDEMAND,A.DASH_WEBM_VK,A.DASH_WEBM,A.DASH,A.DASH_SEP_VK,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS_JS,A.MPEG],live:[A.HLS_LIVE,A.DASH_LIVE,A.DASH_LIVE_WEBM]},[k.CHROMECAST]:{vod:[A.DASH_WEBM_VK,A.DASH_WEBM,A.DASH_SEP_VK,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG],live:[A.HLS_LIVE]}};class Ii{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new $;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new ft(P.STOPPED),seekPosition:new ft(void 0),volume:new ft({volume:1,muted:!1}),videoTrack:new ft(void 0),autoVideoTrackSwitching:new ft(!0),autoVideoTrackLimits:new ft({}),isLooped:new ft(!1),externalTextTracks:new ft([]),currentTextTrack:new ft(void 0),textTrackCuesSettings:new ft({})};info={playbackState$:new t(P.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),autoQualityLimitingAvailable$:new t(!1),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(_.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:ot};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(I)){const s=I[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 L({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ai(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 mi({screenFormatsPriority:[...Ri[k.SCREEN].live,...Ri[k.SCREEN].vod],chromecastFormatsPriority:[...Ri[k.CHROMECAST].live,...Ri[k.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()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.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()===_.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()===_.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(S((t=>t.to===P.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===P.PLAYING||t.to===P.PAUSED)),f(0),m()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?D.SuccessWithoutSound:D.SuccessWithSound:D.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===P.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 P.PAUSED:this.events.willPause$.next();break;case P.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)=>at(t)?1:at(e)?-1:tt(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.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(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)),S(s)),e.pipe(S((()=>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(S((({to:t})=>t===P.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 g=o(r(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(S((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),f.unsubscribe(),t){case!0:f.add(Di({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:g,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:f.add(_i({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:g,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(S((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=ct(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),nt={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{rt=t})),this.providerContainer.current$.subscribe((({type:t})=>dt('provider',t))),t.duration$.subscribe((t=>dt('duration',t))),t.availableVideoTracks$.pipe(S((t=>!!t.length)),m()).subscribe((t=>dt('tracks',t))),this.events.fatalError$.subscribe(new ht('fatalError')),this.events.managedError$.subscribe(new ht('managedError')),t.position$.subscribe(new ht('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new ht('quality')),t.currentBuffer$.subscribe(new ht('buffer')),t.isBuffering$.subscribe(new ht('isBuffering'))].forEach((t=>this.subscription.add(t))),dt('codecs',Object.keys(ei).filter((t=>ei[t])))}}const Li='@vkontakte/videoplayer-core@2.0.47';export{_ as ChromecastState,R as HttpConnectionType,P as PlaybackState,Ii as Player,Li as SDK_VERSION,D as StartStatus,A as VideoFormat,J as VideoQuality};