@vkontakte/videoplayer-core 2.0.41 → 2.0.42-beta.0

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.cjs.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @vkontakte/videoplayer-core v2.0.42-beta.0
3
+ * Tue, 15 Mar 2022 18:51:36 GMT
4
+ * https://st.mycdn.me/static/playersdk/2-0-42/doc/
5
+ */
6
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var e=require('@vkontakte/videoplayer-shared');function t(e){return e&&'object'==typeof e&&'default'in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if('default'!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var i=t(require('lodash/debounce'));var a,r,o,n,d,u;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP_VK',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM_VK',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS_JS',r.HLS_LIVE='HLS_LIVE',function(e){e.SCREEN='SCREEN',e.CHROMECAST='CHROMECAST'}(o||(o={})),exports.ChromecastState=void 0,(n=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',n.AVAILABLE='AVAILABLE',n.CONNECTING='CONNECTING',n.CONNECTED='CONNECTED',exports.StartStatus=void 0,(d=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',d.SuccessWithoutSound='success_without_sound',d.Failed='failed',exports.HttpConnectionType=void 0,(u=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',u.HTTP2='http2',u.QUIC='quic';const h={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33};class c{connection$=new e.ValueSubject(void 0);castState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new e.Subject;contentId;realCastState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new e.Subscription;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),t.isDisabled||!s)return;var i;e.isNonNullable(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{e&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((e,t)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>e,s.onerror=()=>t,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(((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)}))}toggleConnection(){e.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const s=this.connection$.getValue();e.isNullable(s)||(s.remotePlayer.volumeLevel=t,s.remotePlayerController.setVolumeLevel())}setMuted(t){const s=this.connection$.getValue();e.isNullable(s)||t!==s.remotePlayer.isMuted&&s.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,s=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(e.fromEvent(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 e.assertNever(t.sessionState)}}))).add(e.merge(e.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(e.tap((e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})})),e.map((e=>e.castState))),e.observableFrom([i.getCastState()])).pipe(e.filterChanged(),e.map(l),e.tap((e=>{this.log({message:`realCastState$: ${e}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{const r=a===exports.ChromecastState.CONNECTED,o=e.isNonNullable(this.connection$.getValue());if(r&&!o){const a=i.getCurrentSession();e.assertNonNullable(a);const r=a.getCastDevice(),o=a.getMediaSession()?.media.contentId;(e.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:s,session:a,castDevice:r}))}else!r&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?e.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(e){return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:e})}}}const l=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return e.assertNever(t)}};var p,m,S,b;!function(e){e.VIDEO='video',e.AUDIO='audio',e.TEXT='text'}(p||(p={})),function(e){e.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',e.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(m||(m={})),function(e){e.NONE='none',e.DOWNLOADING='downloading',e.DOWNLOADED='downloaded',e.FED='fed'}(S||(S={})),function(e){e.MP4='mp4',e.WEBM='webm'}(b||(b={}));var f=async e=>{const t=e.muted;try{await e.play()}catch(s){if(s instanceof DOMException&&(20===s.code||'AbortError'===s.name))return!1;if(t)return console.warn(s),!1;e.muted=!0;try{await e.play()}catch(t){return e.muted=!1,console.warn(t),!1}}return!0};const g=(t,s,i,{equal:a=((e,t)=>e===t),changed$:r,onError:o}={})=>{const n=t.getState(),d=s(),u=e.isNullable(r),h=new e.Subscription;return r&&h.add(r.subscribe((e=>{const s=t.getState();a(e,s)&&t.setState(e)}),o)),a(d,n)||(i(n),u&&t.setState(n)),h.add(t.stateChangeStarted$.subscribe((e=>{i(e.to),u&&t.setState(e.to)}),o)),h},v=(t,s,i)=>g(s,(()=>t.loop),(s=>{e.isNonNullable(s)&&(t.loop=s)}),{onError:i}),y=(t,s,i,a)=>g(s,(()=>({muted:t.muted,volume:t.volume})),(s=>{e.isNonNullable(s)&&(t.muted=s.muted,t.volume=s.volume)}),{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:i,onError:a}),T=(e,t)=>{if(e.id===t)return!0;const[s,i,a]=t.split('|');return e.language===i&&e.label===a};class E{available$=new e.Subject;current$=new e.ValueSubject(void 0);error$=new e.Subject;video;cueSettings;subscription=new e.Subscription;externalTracks=new Map;connect(t,s,i){this.video=t,this.cueSettings=s.textTrackCuesSettings,this.subscribe();const a=e=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:e})};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(g(s.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{e.isNonNullable(t)&&this.setExternal(t)}),{equal:(t,s)=>e.isNonNullable(t)&&e.isNonNullable(s)&&t.length===s.length&&t.every((({id:e},t)=>e===s[t].id)),changed$:this.available$.pipe(e.map((e=>e.filter((({type:e})=>'external'===e))))),onError:a})),this.subscription.add(g(s.currentTextTrack,(()=>{if(this.video)return;const e=this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e));return e&&this.htmlTextTrackToITextTrack(e).id}),(e=>this.select(e)),{changed$:this.current$,onError:a})),this.subscription.add(g(s.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)})))}subscribe(){e.assertNonNullable(this.video);const{textTracks:t}=this.video;this.subscription.add(e.fromEvent(t,'addtrack').subscribe((()=>{const e=this.current$.getValue();this.select(e)}))),this.subscription.add(e.merge(e.fromEvent(t,'addtrack'),e.fromEvent(t,'removetrack'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().map((e=>this.htmlTextTrackToITextTrack(e))))),e.filterChanged(((e,t)=>e.length===t.length&&e.every((({id:e},s)=>e===t[s].id))))).subscribe(this.available$)),this.subscription.add(e.merge(e.fromEvent(t,'change'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e)))),e.map((e=>e&&this.htmlTextTrackToITextTrack(e).id)),e.filterChanged()).subscribe(this.current$));const s=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(e.fromEvent(t,'addtrack').subscribe((e=>{e.track?.addEventListener('cuechange',s);const t=e=>{const s=e.target?.cues??null;s&&s.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener('cuechange',t))};e.track?.addEventListener('cuechange',t)}))),this.subscription.add(e.fromEvent(t,'removetrack').subscribe((e=>{e.track?.removeEventListener('cuechange',s)})))}applyCueSettings(t){if(!t||!t.length)return;const s=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;e.isNonNullable(s.align)&&(t.align=s.align),e.isNonNullable(s.position)&&(t.position=s.position),e.isNonNullable(s.size)&&(t.size=s.size),e.isNonNullable(s.line)&&(t.line=s.line)}}htmlTextTracksAsArray(t=!1){e.assertNonNullable(this.video);const s=[...this.video.textTracks];return t?s:s.filter(E.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=''!==e.id?e.id:(e=>['__',e.language,e.label].join('|'))(e);return this.externalTracks.has(i)?{id:i,type:'external',language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:'internal',language:t,label:s}}static isHealthyTrack(e){return'metadata'!==e.kind&&(''!==e.id||''!==e.label||''!==e.language)}setExternal(e){e.filter((({id:e})=>!this.externalTracks.has(e))).forEach((e=>this.attach(e))),Array.from(this.externalTracks.keys()).filter((t=>!e.find((e=>e.id===t)))).forEach((e=>this.detach(e)))}select(t){e.assertNonNullable(this.video);for(const s of this.htmlTextTracksAsArray(!0))e.isNonNullable(t)&&T(s,t)?s.mode='showing':s.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName('track'))){const t=e.getAttribute('id');t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(t){e.assertNonNullable(this.video);const s=document.createElement('track');s.setAttribute('src',t.url),s.setAttribute('id',t.id),t.label&&s.setAttribute('label',t.label),t.language&&s.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(s)}detach(t){e.assertNonNullable(this.video);const s=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));s&&this.video.removeChild(s),this.externalTracks.delete(t)}}var P=e=>{const t=document.createElement('video');return t.setAttribute('crossorigin','anonymous'),t.setAttribute('playsinline','playsinline'),e.appendChild(t),t},k=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadeddata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());class ${_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let s=this._source.buffered.start(t);const i=this._source.buffered.end(t);s>e&&s-e<3&&(s=e),this._buffer.push({start:s,end:i,i:t})}return this._buffer.sort((function(e,t){return e.start-t.start})),this._buffer}getByTime(e){return this._buffer.find((t=>e>=t.start&&e<t.end))}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.start-e.end<(t||3))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach((({start:i,end:a})=>{const r=i>=e&&i<t,o=a>=e&&a<t;r&&o||(r?s(t,a):o?s(i,e):i<e&&a>t?(s(t,a),s(i,e)):s(i,a))}))}destroy(){this._buffer=[]}}var w=(e,t,s=3)=>{let i=0,a=0;for(let r=0;r<e.length;r++){const o=e.start(r),n=e.end(r);if(o<=t&&t<=n){if(i=o,a=n,!s)return{start:i,end:a};for(let t=r-1;t>=0;t--)e.end(t)+s>=i&&(i=e.start(t));for(let t=r+1;t<e.length;t++)e.start(t)-s<=a&&(a=e.end(t))}}return{start:i,end:a}},A=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadedmetadata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());const N=t=>{const s=(s,i=(()=>{}))=>e.fromEvent(t,s).pipe(e.map(i)),i=e.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((s=>e.fromEvent(t,s)))).pipe(e.map((()=>t.readyState<3)),e.filterChanged()),a=e.merge(e.fromEvent(t,'progress'),e.fromEvent(t,'timeupdate')).pipe(e.map((()=>w(t.buffered,t.currentTime)))),r=e.fromEvent(t,'volumechange').pipe(e.debounce(0),e.map((()=>({muted:t.muted,volume:t.volume})))),o=e.fromEvent(t,'error').pipe(e.map((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}})));return{playing$:s('playing'),pause$:s('pause'),canplay$:s('canplay'),ended$:s('ended'),error$:o,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:s('timeupdate',(()=>t.currentTime)),durationChange$:s('durationchange',(()=>t.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:r,firstBytes$:A(t),firstFrame$:k(t)}};var x,D=(e,t,s=!1)=>{const i=e.getTransition();!s&&i&&i.to!==t||e.setState(t)};exports.VideoQuality=void 0,(x=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',x.Q_144P='144p',x.Q_240P='240p',x.Q_360P='360p',x.Q_480P='480p',x.Q_720P='720p',x.Q_1080P='1080p',x.Q_1440P='1440p',x.Q_2160P='2160p',x.Q_4320P='4320p';const _={[exports.VideoQuality.Q_144P]:144,[exports.VideoQuality.Q_240P]:240,[exports.VideoQuality.Q_360P]:360,[exports.VideoQuality.Q_480P]:480,[exports.VideoQuality.Q_720P]:720,[exports.VideoQuality.Q_1080P]:1080,[exports.VideoQuality.Q_1440P]:1440,[exports.VideoQuality.Q_2160P]:2160,[exports.VideoQuality.Q_4320P]:4320},R=(e,t)=>_[e]>_[t],I=(e,t)=>_[e]<_[t],C=Object.keys(_).sort(((e,t)=>I(e,t)?-1:1)),L=({width:e,height:t},s)=>((e,t=.02)=>[...C].find((s=>_[s]*(1+t)>=e)))(Math.min(e,t),s),O=e=>e===exports.VideoQuality.INVARIANT;let V=!1,M={};const B=e=>{e(M)},U=(e,t)=>{V&&(M.meta=M.meta??{},M.meta[e]=t)};class F{name;constructor(e){this.name=e}next(e){if(!V)return;M.series=M.series??{};const t=M.series[this.name]??[];t.push([Date.now(),e]),M.series[this.name]=t}}const H=new F('best_bitrate'),q=(t,{container:s,throughput:i,tuning:a,forwardBufferHealth:r,currentRepresentation:o})=>{const n=a.usePixelRatio?window.devicePixelRatio??1:1,d=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*n*a.containerSizeFactor,height:s.height*n*a.containerSizeFactor},u=d&&L(d,0),h=t.filter((e=>!O(e.quality))).sort(((e,t)=>R(e.quality,t.quality)?-1:1)),c=h.filter((t=>{const s=!u||I(t.quality,u),n=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i>=t.bitrate*(d=r??.5,h=a.bitrateFactorAtEmptyBuffer,c=a.bitrateFactorAtFullBuffer,(h-c)*Math.pow(2,-10*d)+c);var d,h,c;const l=!a.lazyQualitySwitch||!o||(r??.5)>=.5||(t.size?.height||0)<=(o?.height||0);return s&&n&&l}))[0];return c&&c.bitrate&&H.next(c.bitrate),c??h[h.length-1]??t[0]};var G=(e,t)=>{let s=0;for(let i=0;i<e.length;i++){const a=1e3*e.start(i),r=1e3*e.end(i);a<=t&&t<=r&&(s=r)}return Math.max(s-t,0)},j=e=>new URL(e).hostname;const Y=(t,s=300)=>new e.Observable((a=>{const{width:r,height:o}=t.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(i.default((t=>{const s=t[0];if(!s)return;let i,r;s.contentBoxSize&&s.contentBoxSize[0]?(r=s.contentBoxSize[0].blockSize,i=s.contentBoxSize[0].inlineSize):s.contentRect&&(i=s.contentRect.width,r=s.contentRect.height),e.isNonNullable(i)&&e.isNonNullable(r)&&a.next({width:i,height:r})}),s));return n.observe(t),()=>n.disconnect()}));class z{state;transition;transitionStarted$=new e.Subject;transitionEnded$=new e.Subject;transitionUpdated$=new e.Subject;forceChanged$=new e.Subject;stateChangeStarted$=e.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=e.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(t){const s=this.transition,i=this.state;i===t||e.isNonNullable(s)&&s.to===t||(this.state=t,s?(this.transition={from:s.from,to:t,canceledTransition:s},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 Q,W=e=>{const t=e.get('X-Delivery-Type'),s=e.get('X-Reused');return{type:null===t?exports.HttpConnectionType.HTTP1:t??void 0,reused:null===s?void 0:{1:!0,0:!1}[s]??void 0}};!function(e){e[e.HEADER=0]='HEADER',e[e.PARAM=1]='PARAM'}(Q||(Q={}));class J{throughputEstimator;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new AbortController;subscription=new e.Subscription;constructor({throughputEstimator:e}={}){this.throughputEstimator=e}onHeadersReceived(e){const{type:t,reused:s}=W(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchManifest(e){const t=await fetch(e,{signal:this.abortAllController.signal}).catch(K);return t?(this.onHeadersReceived(t.headers),t.text()):null}async fetchRange(t,s,i,{method:a=Q.HEADER,onProgress:r,signal:o}={}){let n=t;const d=new Headers;switch(a){case Q.HEADER:d.append('Range',`${s}-${i}`);break;case Q.PARAM:{const e=new URL(n,location.href);e.searchParams.append('bytes',`${s}-${i}`),n=e.toString();break}default:e.assertNever(a)}let u=this.abortAllController.signal;if(o){const t=new AbortController;this.subscription.add(e.merge(e.fromEvent(this.abortAllController.signal,'abort'),e.fromEvent(o,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&t.abort(),u=t.signal}const h=e.now(),c=await fetch(n,{headers:d,signal:u}).catch(K);if(this.throughputEstimator?.addRawRtt(e.now()-h),!c)return null;if(!c.ok||!c.body)return Promise.reject(new Error(`Fetch error ${c.status}: ${c.statusText}`));this.onHeadersReceived(c.headers);const[l,p]=c.body.tee(),m=l.getReader();this.throughputEstimator?.trackStream(p);const S=parseInt(c.headers.get('Content-Length')??'',10);let b=0;const f=new ArrayBuffer(S),g=new Uint8Array(f),v=new DataView(f);let y=!1;const T=e=>{y=!0,K(e)},E=async({done:t,value:s})=>{0===b&&this.lastRequestFirstBytes$.next(e.now()-h),t?r?.(v,b):s&&(g.set(s,b),b+=s.byteLength,r?.(v,b),await(m?.read().then(E,T)))};return await(m?.read().then(E,T)),y?null:f}fetchRepresentation=async(e,t,s=0)=>{const{from:i,to:a}=e.initRange;let r,o,n=i,d=a,u=!1;e.indexRange&&(r=e.indexRange.from,o=e.indexRange.to,u=a+1===r,u&&(n=Math.min(r,i),d=Math.max(o,a))),n=Math.min(n,0),d+=s;const h=await this.fetchRange(e.url,n,d,{method:Q.PARAM});if(!h)return null;const c=new DataView(h,i-n,a-n);if(!t.validateData(c))throw new Error('Invalid media file');const l=t.parseInit(c);let p;if(u&&void 0!==r&&void 0!==o)p=new DataView(h,r-n,o-r);else{const s=t.getIndexRange(l);if(s){const t=await this.fetchRange(e.url,s.from,s.to,{method:Q.PARAM});if(!t)return null;p=new DataView(t)}}if(!p)throw new ReferenceError('No way to load representation index');const m=t.parseSegments(p,l);return{dataView:new DataView(h),segments:m}};destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const K=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e};var X,Z;!function(e){e[e.EBML=440786851]='EBML',e[e.EBMLVersion=17030]='EBMLVersion',e[e.EBMLReadVersion=17143]='EBMLReadVersion',e[e.EBMLMaxIDLength=17138]='EBMLMaxIDLength',e[e.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',e[e.DocType=17026]='DocType',e[e.DocTypeVersion=17031]='DocTypeVersion',e[e.DocTypeReadVersion=17029]='DocTypeReadVersion',e[e.Void=236]='Void',e[e.Segment=408125543]='Segment',e[e.SeekHead=290298740]='SeekHead',e[e.Seek=19899]='Seek',e[e.SeekID=21419]='SeekID',e[e.SeekPosition=21420]='SeekPosition',e[e.Info=357149030]='Info',e[e.TimestampScale=2807729]='TimestampScale',e[e.Duration=17545]='Duration',e[e.Tracks=374648427]='Tracks',e[e.Chapters=272869232]='Chapters',e[e.Cluster=524531317]='Cluster',e[e.Attachments=423732329]='Attachments',e[e.Tags=307544935]='Tags',e[e.Cues=475249515]='Cues',e[e.CuePoint=187]='CuePoint',e[e.CueTime=179]='CueTime',e[e.CueTrackPositions=183]='CueTrackPositions',e[e.CueTrack=247]='CueTrack',e[e.CueClusterPosition=241]='CueClusterPosition',e[e.CueRelativePosition=240]='CueRelativePosition',e[e.CueDuration=178]='CueDuration',e[e.CueBlockNumber=21368]='CueBlockNumber',e[e.CueCodecState=234]='CueCodecState',e[e.CueReference=219]='CueReference',e[e.CueRefTime=150]='CueRefTime'}(X||(X={})),function(e){e.SignedInteger='int',e.UnsignedInteger='uint',e.Float='float',e.String='string',e.UTF8='utf8',e.Date='date',e.Master='master',e.Binary='binary'}(Z||(Z={}));const ee={[X.EBML]:{type:Z.Master},[X.EBMLVersion]:{type:Z.UnsignedInteger},[X.EBMLReadVersion]:{type:Z.UnsignedInteger},[X.EBMLMaxIDLength]:{type:Z.UnsignedInteger},[X.EBMLMaxSizeLength]:{type:Z.UnsignedInteger},[X.DocType]:{type:Z.String},[X.DocTypeVersion]:{type:Z.UnsignedInteger},[X.DocTypeReadVersion]:{type:Z.UnsignedInteger},[X.Void]:{type:Z.Binary},[X.Segment]:{type:Z.Master},[X.SeekHead]:{type:Z.Master},[X.Seek]:{type:Z.Master},[X.SeekID]:{type:Z.Binary},[X.SeekPosition]:{type:Z.UnsignedInteger},[X.Info]:{type:Z.Master},[X.TimestampScale]:{type:Z.UnsignedInteger},[X.Duration]:{type:Z.Float},[X.Tracks]:{type:Z.Master},[X.Chapters]:{type:Z.Master},[X.Cluster]:{type:Z.Master},[X.Attachments]:{type:Z.Master},[X.Tags]:{type:Z.Master},[X.Cues]:{type:Z.Master},[X.CuePoint]:{type:Z.Master},[X.CueTime]:{type:Z.UnsignedInteger},[X.CueTrackPositions]:{type:Z.Master},[X.CueTrack]:{type:Z.UnsignedInteger},[X.CueClusterPosition]:{type:Z.UnsignedInteger},[X.CueRelativePosition]:{type:Z.UnsignedInteger},[X.CueDuration]:{type:Z.UnsignedInteger},[X.CueBlockNumber]:{type:Z.UnsignedInteger},[X.CueCodecState]:{type:Z.UnsignedInteger},[X.CueReference]:{type:Z.Master},[X.CueRefTime]:{type:Z.UnsignedInteger}},te=e=>{const t=e.getUint8(0);let s=0;128&t?s=1:64&t?s=2:32&t?s=3:16&t&&(s=4);const i=se(e,s),a=i in ee,r=a?ee[i].type:Z.Binary,o=e.getUint8(s);let n=0;128&o?n=1:64&o?n=2:32&o?n=3:16&o?n=4:8&o?n=5:4&o?n=6:2&o?n=7:1&o&&(n=8);const d=new DataView(e.buffer,e.byteOffset+s+1,n-1),u=((o&255>>n)<<8*(n-1))+se(d),h=s+n;let c;return c=h+u>e.byteLength?new DataView(e.buffer,e.byteOffset+h):new DataView(e.buffer,e.byteOffset+h,u),{tag:a?i:'0x'+i.toString(16).toUpperCase(),type:r,value:c,valueSize:u}},se=(e,t=e.byteLength)=>{switch(t){case 1:return e.getUint8(0);case 2:return e.getUint16(0);case 3:return e.getUint16(0)<<8|e.getUint8(2);case 4:return e.getUint32(0);case 5:return e.getUint32(0)<<8|e.getUint8(4);case 6:return e.getUint32(0)<<16|e.getUint16(4);case 7:return e.getUint32(0)<<32|e.getUint16(4)<<8|e.getUint8(6);case 8:return e.getUint32(0)<<32|e.getUint32(4)}return 0},ie=(t,s)=>{switch(s){case Z.SignedInteger:return t.getInt8(0);case Z.UnsignedInteger:return se(t);case Z.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Z.String:return new TextDecoder('ascii').decode(t);case Z.UTF8:return new TextDecoder('utf-8').decode(t);case Z.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Z.Master:case Z.Binary:return t;default:e.assertNever(s)}},ae=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=te(i);if(!t(a))return;a.type===Z.Master&&ae(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},re=[X.Info,X.SeekHead,X.Tracks,X.Chapters,X.Cluster,X.Cues,X.Attachments,X.Tags],oe={validateData:e=>{if(e.getUint32(0)!==X.EBML)return!1;let t,s,i;const a=te(e);return ae(a.value,(({tag:e,type:a,value:r})=>(e===X.EBMLReadVersion?t=ie(r,a):e===X.DocType?s=ie(r,a):e===X.DocTypeReadVersion&&(i=ie(r,a)),!0))),(void 0===t||t<=1)&&void 0!==s&&'webm'===s&&(void 0===i||i<=2)},parseInit:t=>{let s,i,a,r,o,n,d=!1,u=!1,h=!1;return ae(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===X.SeekID){const e=ie(c,t);n=se(e)}else e!==X.SeekPosition&&(n=void 0);return e===X.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===X.Info?d=!0:e===X.SeekHead?u=!0:e===X.TimestampScale?a=ie(c,t):e===X.Duration?r=ie(c,t):e===X.SeekPosition&&n===X.Cues?o=ie(c,t):d&&u&&re.includes(e)&&(h=!0),!h})),e.assertNonNullable(s,'Failed to parse webm Segment start'),e.assertNonNullable(i,'Failed to parse webm Segment end'),e.assertNonNullable(r,'Failed to parse webm Segment duration'),a=a??1e6,{segmentStart:Math.round(s/1e9*a*1e3),segmentEnd:Math.round(i/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:t=>{if(e.isNullable(t.cuesSeekPosition))return;const s=t.segmentStart+t.cuesSeekPosition;return{from:s,to:s+1048576}},parseSegments:(t,s)=>{let i=!1,a=!1;const r=t=>e.isNonNullable(t.time)&&e.isNonNullable(t.position),o=[];let n;return ae(t,(({tag:e,type:t,value:s})=>{switch(e){case X.Cues:i=!0;break;case X.CuePoint:n&&r(n)&&o.push(n),n={};break;case X.CueTime:n&&(n.time=ie(s,t));break;case X.CueTrackPositions:break;case X.CueClusterPosition:n&&(n.position=ie(s,t));break;default:i&&re.includes(e)&&(a=!0)}return!(i&&a)})),n&&r(n)&&o.push(n),o.map(((e,t)=>{const{time:i,position:a}=e,r=o[t+1];return{status:S.NONE,time:{from:i,to:r?r.time:s.segmentDuration},byte:{from:s.segmentStart+a,to:r?s.segmentStart+r.position-1:s.segmentEnd-1}}}))}},ne=new TextDecoder('ascii'),de={validateData:e=>'ftyp'===ne.decode(new DataView(e.buffer,e.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:e=>{const t=(e=>{let t=0,s=e.getUint32(t);t+=4;const i=new DataView(e.buffer,e.byteOffset+t,4),a=ne.decode(i);t+=4,0===s?s=1/0:1===s&&(t+=8,s=1/0);const r=Math.min(s,e.byteLength)-t+1;return{id:a,size:s,contents:new DataView(e.buffer,e.byteOffset+t,r)}})(e),s=[];let i=0;const a=()=>{const e=t.contents.getUint32(i);return i+=4,e};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),o=a(),n=a(),d=255&a();let u=o/r*1e3,h=e.byteOffset+e.byteLength+n+1;for(let e=0;e<d;e++){const e=a(),t=e>>>31,i=e<<1>>>1,o=a();if(a(),0!==t)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;s.push({status:S.NONE,time:{from:u,to:u+n},byte:{from:h,to:h+i-1}}),u+=n,h+=i}return s}};class ue{ended$=new e.ValueSubject(!1);playingRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;subscription=new e.Subscription;kind;container;containerParser;initData;representations;segments;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;abortController=new AbortController;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;constructor(t,s,i,a,{fetcher:r,tuning:o}){switch(this.fetcher=r,this.tuning=o,this.container=i,i){case b.MP4:this.containerParser=de;break;case b.WEBM:this.containerParser=oe;break;default:e.assertNever(i)}this.initData=new Map,this.segments=new Map,this.representations=new Map(a.map((e=>[e.id,e]))),this.kind=t,this.mediaSource=s,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}async startWith(t){const s=this.representations.get(t);e.assertNonNullable(s,`Cannot find representation ${t}`);const i=Math.ceil(1e3*s.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${s.mime}; codecs="${s.codecs}"`),this.subscription.add(e.fromEvent(this.sourceBuffer,'updateEnd').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejecte by browser',thrown:e})))),this.subscription.add(e.fromEvent(this.sourceBuffer,'error').subscribe((e=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:e}))));const a=await this.fetcher.fetchRepresentation(s,this.containerParser,i).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!a)return!1;const{dataView:r,segments:o}=a,n=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength-i);this.initData.set(t,n);const d=o.filter((e=>e.byte.from>=r.byteOffset&&e.byte.to<r.byteOffset+r.byteLength)),u=d.at(-1),h=new DataView(r.buffer,r.byteOffset,d.length&&u?Math.min(u.byte.to-r.byteOffset+1,r.byteLength):r.byteLength-i);return await this.appendDataToBuffer(h),this.segments.set(t,o.map((e=>({...e,status:e.byte.from>=r.byteOffset&&e.byte.to<r.byteOffset+r.byteLength?S.FED:S.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 s=this.representations.get(t);e.assertNonNullable(s);const i=await this.fetcher.fetchRepresentation(s,this.containerParser,0).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!i)return;const{dataView:a,segments:r}=i,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(t,o),this.segments.set(t,r)}const s=this.initData.get(t);e.assertNonNullable(s,`No init buffer for ${t}`),e.assertNonNullable(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abortController.abort(),this.abortController=new AbortController;try{this.sourceBuffer.abort()}catch(e){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:e})}await this.appendDataToBuffer(s,this.abortController.signal),e.isNonNullable(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((e=>{e.status===S.FED&&(e.status=S.NONE)}))}async maintain(t){if(e.isNullable(this.downloadingRepresentationId)||e.isNullable(this.playingRepresentationId)||e.isNullable(this.sourceBuffer)||this.ended$.getValue())return;const s=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);e.assertNonNullable(s),e.assertNonNullable(i);const a=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=G(this.sourceBuffer.buffered,t);r=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}const o=this.selectForwardBufferSegments(i,r);o.length&&await this.loadSegments(o,s),!this.allInitsLoaded&&!this.loadAllInitsPromise&&a&&a.status===S.FED&&!o.length&&G(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((e=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:e})));const n=i.at(-1);n&&a===n&&n.status===S.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.sourceBuffer.abort(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.abortController.abort()}selectForwardBufferSegments(e,t){const s=e.findIndex((({status:e,time:{from:s,to:i}})=>e===S.NONE&&(s>t||s<=t&&i>=t)&&i<=t+this.tuning.forwardBufferTarget));if(-1===s)return[];let i=0;const a=[];for(let t=s;t<e.length&&i<=this.tuning.segmentRequestSize;t++){const s=e[t];if(i+=s.byte.to+1-s.byte.from,s.status===S.NONE)a.push(s);else if([S.DOWNLOADING,S.DOWNLOADED,S.FED].includes(s.status))break}return a}async loadSegments(e,t){if(!e.length)return;const s=e.at(0).byte.from,i=e.at(-1).byte.to;for(const t of e)t.status=S.DOWNLOADING;const{signal:a}=this.abortController,r=(e,s)=>{e.status=S.DOWNLOADED,this.appendDataToBuffer(s,a).then((s=>{!s||a.aborted?e.status=S.NONE:(this.playingRepresentationId=t.id,this.playingRepresentation$.next(this.playingRepresentationId),e.status=S.FED)}))},o=(t,i)=>{for(const a of e)a.status===S.DOWNLOADING&&a.byte.from-s>=0&&a.byte.to+1-s<=i&&r(a,new DataView(t.buffer,t.byteOffset+a.byte.from-s,a.byte.to+1-a.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((async()=>{if(a.aborted){for(const t of e)t.status===S.DOWNLOADING&&(t.status=S.NONE);return}const n=await this.fetcher.fetchRange(t.url,s,i,{method:Q.PARAM,onProgress:o,signal:a}),d=e.at(-1),u=this.segments.get(t.id)?.at(-1);if(!n)for(const t of e)t.status===S.DOWNLOADING&&(t.status=S.NONE);n&&!a.aborted&&d&&u&&d.status===S.DOWNLOADING&&d===u&&r(d,new DataView(n,d.byte.from-s))})).catch((e=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:e}))),this.segmentDownloadPromise}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=Promise.all(Array.from(this.representations.entries()).map((([e,t])=>this.initData.has(e)?Promise.resolve():this.fetcher.fetchRepresentation(t,this.containerParser).then((t=>{if(!t)return;const{dataView:s,segments:i}=t,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(e,a),this.segments.set(e,i)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async appendDataToBuffer(t,s){if(e.assertNonNullable(this.sourceBuffer),s&&s.aborted)return!1;if(this.sourceBuffer.updating)return await ue.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(t,s);try{this.sourceBuffer.appendBuffer(t)}catch(e){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:e}),!1}return await ue.waitForBufferUpdate(this.sourceBuffer),!0}checkEjectedSegments(){if(e.isNullable(this.sourceBuffer)||e.isNullable(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);e.assertNonNullable(t);const s=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const t=1e3*this.sourceBuffer.buffered.start(e),i=this.sourceBuffer.buffered.end(e),a=1e3*(i%1>.9?Math.round(i):i);s.push({from:t,to:a})}for(const e of t){const t=s.some((t=>t.from<=e.time.from&&t.to>=e.time.to));e.status!==S.FED||t||(e.status=S.NONE)}}static async waitForBufferUpdate(e){return new Promise((t=>e?e.addEventListener('update',(()=>t())):t()))}}const he=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)},ce=['timeupdate','progress','play','seeked','stalled'];var le,pe;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(le||(le={}));class me{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new z(le.NONE);currentVideoRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);forceEnded$=new e.Subject;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new J({throughputEstimator:this.throughputEstimator})}async initManifest(t,s){this.element=t,this.subscription.add(e.fromEvent(t,'waiting').subscribe((()=>{t.duration-t.currentTime<this.tuning.endGapTolerance/1e3&&this.forceEnded$.next()}),(e=>this.error$.next({id:'ForceEnd',message:'Error when forcing stream end',thrown:e})))),this.state$.startTransitionTo(le.MANIFEST_LOADED);const i=await this.fetcher.fetchManifest(s);let a;try{a=((e,t)=>{const s={video:[],audio:[],text:[]},i=(new DOMParser).parseFromString(e,'application/xml').children[0],a=i.getElementsByTagName('Period')[0].children;let r=0;const o=i.getAttribute('profiles')?.split(',')??[],n=o.includes(m.WEBM_AS_IN_FFMPEG)||o.includes(m.WEBM_AS_IN_SPEC)?b.WEBM:b.MP4;for(const e of a){const i=e.getAttribute('mimeType'),a=e.getAttribute('codecs'),n=e.getAttribute('contentType')??i?.split('/')[0],d=e.getAttribute('profiles')?.split(',')??[],u=e.querySelectorAll('Representation');for(const h of u){const u=h.getAttribute('mimeType')??i,c=h.getAttribute('codecs')??a??'',l=h.getAttribute('contentType')??u?.split('/')[0]??n,m=e.getAttribute('profiles')?.split(',')??[],S=parseInt(h.getAttribute('width')??'',10),b=parseInt(h.getAttribute('height')??'',10),f=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,g=h.getAttribute('frameRate')??'',v=g?he(g):void 0,y=`${h.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${b}p`:'audio'===l?`${f}Kbps`:c}`,T=h.querySelector('BaseURL')?.textContent?.trim()??'',E=new URL(T,t).toString(),P=[...o,...d,...m],k=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[$,w]=k.split('-').map((e=>parseInt(e,10))),A={from:$,to:w},N=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[x,D]=N?N.split('-').map((e=>parseInt(e,10))):[],_=N?{from:x,to:D}:void 0;if(!l||!u)continue;const R={video:p.VIDEO,audio:p.AUDIO,text:p.TEXT}[l];R&&s[R].push({id:y,kind:R,profiles:P,initRange:A,indexRange:_,bitrate:f,mime:u,codecs:c,width:S,height:b,fps:v,url:E})}}return{container:n,representations:s}})(i??'',s)}catch(e){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:e})}e.assertNonNullable(a);const r=({mime:e,codecs:s})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${s}"`));return this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map((([e,t])=>[e,t.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(le.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}async initRepresentations(t,s){e.assertNonNullable(this.manifest),e.assertNonNullable(this.element),this.state$.startTransitionTo(le.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 ue(p.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new ue(p.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(e.merge(this.forceEnded$,e.combine({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(e.filter((e=>Object.values(e).every((e=>!0===e)))))).subscribe((()=>{if('open'===this.source?.readyState)try{this.source?.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(e.merge(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((e=>this.source?.addEventListener('sourceopen',e)));(await Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])).some((e=>!e))||(this.state$.setState(le.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...ce.map((t=>e.fromEvent(this.element,t))),e.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:e})}))),this.subscription.add(e.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.tick())}async switchRepresentation(t,s){const i={[p.VIDEO]:this.videoBufferManager,[p.AUDIO]:this.audioBufferManager,[p.TEXT]:null}[t];return e.assertNonNullable(i),i.switchTo(s)}seek(t){e.assertNonNullable(this.element),e.assertNonNullable(this.videoBufferManager),e.assertNonNullable(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(le.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element)return;const e=1e3*this.element.currentTime;this.videoBufferManager?.maintain(e),this.audioBufferManager?.maintain(e)}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(pe||(pe={}));const Se=({id:e,width:t,height:s,bitrate:i,fps:a})=>{const r=L({width:t,height:s});return r&&{id:e,quality:r,bitrate:i,size:{width:t,height:s},fps:a}},be=(e,t,s)=>{const i=Array.from(t).sort(((e,t)=>t.bitrate-e.bitrate)).indexOf(s);return e.at(Math.round(e.length*i/t.length))??e.at(-1)};class fe{subscription=new e.Subscription;videoState=new z(pe.STOPPED);video;player;params;elementSize$=new e.ValueSubject(void 0);textTracksManager=new E;videoTracks=[];audioRepresentations;constructor(e){this.params=e,this.video=P(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(j(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new me({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=N(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},r=(e,t)=>this.subscription.add(e.subscribe(t,a));r(i.timeUpdate$,t.position$),r(i.durationChange$,t.duration$),r(i.ended$,t.endedEvent$),r(i.error$,t.error$),r(i.isBuffering$,t.isBuffering$),r(i.currentBuffer$,t.currentBuffer$),r(i.firstFrame$,t.firstFrameEvent$),r(this.player.error$,t.error$),r(this.player.lastConnectionType$,t.httpConnectionType$),r(this.player.lastConnectionReused$,t.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(e.filter(e.isNonNullable),e.once()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(v(this.video,s.isLooped,a)),this.subscription.add(y(this.video,s.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),r(Y(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(pe.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(pe.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===pe.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===le.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(pe.READY)}))),this.subscription.add(e.merge(this.player.state$.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.elementSize$,e.fromEvent(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),i=this.player.state$.getTransition();if(t===le.NONE||!this.videoTracks.length)return;const a=t===le.MANIFEST_LOADED&&!i,r=s.autoVideoTrackSwitching.getState(),o=s.videoTrack.getState(),n=this.videoTracks.find((({track:{id:e}})=>e===o))?.track;s.autoVideoTrackSwitching.getTransition()&&s.autoVideoTrackSwitching.setState(r);const d=G(this.video.buffered,1e3*this.video.currentTime),u=Math.min(d/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),h=q(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:u}),c=r?h??n:n??h;if(a){const t=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;e.assertNonNullable(t);const s=be(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),t);e.assertNonNullable(s),this.player.initRepresentations(t.id,s.id)}else{const e=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;if(e){const t=be(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),e);this.player.switchRepresentation(p.VIDEO,e.id),t&&this.player.switchRepresentation(p.AUDIO,t.id)}}}))),this.subscription.add(this.player.currentVideoRepresentation$.pipe(e.filterChanged(),e.map((e=>e&&this.videoTracks.find((({representation:{id:t}})=>t===e))?.track))).subscribe(t.currentVideoTrack$)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,a))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const t of e.representations.video){const e=Se(t);e&&this.videoTracks.push({track:e,representation:t})}this.audioRepresentations=Array.from(e.representations.audio).sort(((e,t)=>t.bitrate-e.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e)))}seek(e){this.params.output.willSeekEvent$.next(),this.player.seek(1e3*e)}syncPlayback=()=>{const t=this.videoState.getState(),s=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!==exports.PlaybackState.PAUSED&&e.isNonNullable(r)&&t!==pe.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(r),s!==exports.PlaybackState.STOPPED){if(t===pe.STOPPED)return this.videoState.startTransitionTo(pe.READY),void this.prepare();switch(t){case pe.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(pe.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed()));case pe.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case pe.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.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(pe.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(pe.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var ge;!function(e){e[e.OFFSET_P=0]='OFFSET_P',e[e.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(ge||(ge={}));var ve=(t,s=0,i=ge.OFFSET_P)=>{switch(i){case ge.OFFSET_P:return t.replace('_offset_p',0===s?'':'_'+s.toFixed(0));case ge.PLAYBACK_SHIFT:{if(0===s)return t;const e=new URL(t);return e.searchParams.append('playback_shift',s.toFixed(0)),e.toString()}default:e.assertNever(i)}return t};var ye;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ye||(ye={}));class Te{subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new z(ye.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 exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return e.assertNever(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const s=this.params.connection.session.getMediaSession();s&&this.restoreSession(s),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new e.Subscription;this.subscription.add(t),this.subscription.add(e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>`stateChangeStarted$ ${JSON.stringify(e)}`))),this.videoState.stateChangeEnded$.pipe(e.map((e=>`stateChangeEnded$ ${JSON.stringify(e)}`)))).subscribe((e=>this.log({message:`[videoState] ${e}`}))));const s=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new e.Subject;t.add(s.pipe(e.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let i=NaN;t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const a=t.value;this.params.output.position$.next(a);const r=this.params.desiredState.seekPosition.getTransition();(e.isNonNullable(r)&&e.isNullable(r.to)||Math.abs(a-i)>5)&&s.next(a),i=a}))),t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)})))}s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:s}=this.params.connection,i=t.value,a=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:e.assertNever(i)}})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}));s(e.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback)}restoreSession(e){this.log({message:'restoreSession'});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(ye.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(ye.PLAYING),D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekPosition.setState(void 0)}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==ye.PAUSED&&e!==ye.PLAYING||(this.videoState.setState(ye.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==ye.PLAYING&&e!==ye.PAUSED||(this.videoState.setState(ye.PLAYING),D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===ye.READY&&this.videoState.setState(ye.READY)}handleRemoteStop(){this.videoState.getState()!==ye.STOPPED&&this.videoState.setState(ye.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};s.volume===t.volume&&s.muted==s.muted||this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(t){const s=this.params.source;let i,a,r;switch(t){case exports.VideoFormat.MPEG:{const o=s[t];e.assertNonNullable(o);const n=Object.keys(o).sort(((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:I(e,t)?1:-1))[0];e.assertNonNullable(n);const d=o[n];e.assertNonNullable(d),i=d,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const o=s[t];e.assertNonNullable(o),i=ve(o.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const e='Unsupported format for Chromecast',t=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:e,thrown:t}),t}default:return e.assertNever(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:n,subtitle:d}=this.params.meta;return e.isNonNullable(n)&&(o.metadata.title=n),e.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return t.currentTime=s?this.params.output.isLive$.getValue()?0:s.to??0:0,t}loadMedia(t){const s=this.params.connection.session.loadMedia(t),i=new Promise(((t,s)=>{this.loadMediaTimeoutSubscription.add(e.timeout(7e3).subscribe((()=>s('timeout(7000)'))))}));Promise.race([s,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});const e=this.params.desiredState.seekPosition;e.getTransition()&&e.setState(void 0),this.handleRemoteReady()}),(e=>{const t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:t,thrown:e})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const t=this.videoState.getState(),s=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(s)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(r)};`}),i===exports.PlaybackState.STOPPED)return void(t!==ye.STOPPED&&(this.videoState.startTransitionTo(ye.STOPPED),this.stop()));if(s)return;const o=r?.to;if(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==ye.STOPPED)this.seek(o);else switch(i){case exports.PlaybackState.PLAYING:switch(t){case ye.PLAYING:break;case ye.PAUSED:case ye.READY:this.videoState.startTransitionTo(ye.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ye.STOPPED:this.videoState.startTransitionTo(ye.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case ye.PLAYING:this.videoState.startTransitionTo(ye.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ye.PAUSED:break;case ye.READY:this.videoState.startTransitionTo(ye.PAUSED),this.videoState.setState(ye.PAUSED);break;case ye.STOPPED:this.videoState.startTransitionTo(ye.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}}}var Ee;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Ee||(Ee={}));class Pe{subscription=new e.Subscription;videoState=new z(Ee.STOPPED);video;trackUrls={};params;textTracksManager=new E;constructor(e){this.params=e,this.video=P(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([e,t],s)=>{const i=s.toString(10);this.trackUrls[i]={track:{quality:e,id:i},url:t}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:e})=>e))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=N(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,s.isLooped,i)),this.subscription.add(y(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Ee.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ee.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ee.READY&&this.videoState.setState(Ee.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&e.isNonNullable(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===Ee.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(s.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>s.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();e.assertNonNullable(t,'MpegProvider: track is not selected');const{url:s}=this.trackUrls[t];e.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(j(s))}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(Ee.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==Ee.STOPPED&&(this.videoState.startTransitionTo(Ee.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(Ee.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===Ee.STOPPED)return this.videoState.startTransitionTo(Ee.READY),void this.prepare();if(a){const{currentTime:e}=this.video;return this.prepare(),void(r||this.params.desiredState.seekPosition.startTransitionTo(e))}const o=r?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&this.seek(o),t){case Ee.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ee.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()));case Ee.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ee.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ee.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class ke{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,a,r){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(e.assertNonNullable(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((e=>e.split(':').map((e=>e.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(e){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(e)}`,e),e}},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 e;this._failoverIndex>=this._failoverHosts.length?(e=this._url,this._failoverIndex=0):(e=this._url.replace((e=>{const t=document.createElement('a');return t.href=e,t.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',e,!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 $e{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(e){if('QuotaExceededError'!==e.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',e),e;{this._isFull=!0;const e=this._sourceBuffer.buffered;let t=0;for(let s=0,i=e.length;s<i;s++)t+=e.end(s)-e.start(s);t&&(this._maxBufferDuration=Math.round(t))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,a,r,o){this.abort((()=>{let n=0;const d=Date.now();let u=0,h=0,c=0;const l=e=>{i($e._str2ua(e.substr(n))),n=e.length};this._lastXhr=new ke(e.baseURL+'&bytes='+t+'-'+s,e.failoverHosts,(e=>{this._lastXhr=void 0,l(e);const t=Date.now()-d;this._params.onBandwidthChange({size:e.length,duration:t,speed:8*e.length/(t/1e3)}),this._onDashCallback('loading',{size:e.length,done:!0}),a?.()}),(e=>{if(e.length-n>o&&l(e),0===h)return void(h=Date.now());c=e.length-u;const t=Date.now()-h;c>=102400&&t>=1e3&&(this._params.onBandwidthChange({size:c,duration:t,speed:8*c/(t/1e3)}),c=0,u=e.length,h=Date.now()),this._onDashCallback('loading',{size:e.length,done:!1})}),r,((e,t,s)=>this._params.onError(e,t,s)))}))}abort(e){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(),e?.()}))}))}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(e){throw this._params.onError('SourceBuffer','Source Buffer update error',e),e}};return this._sourceBuffer.addEventListener('updateend',t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener('updateend',e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=$e._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class we{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=(e,t)=>{const s=e?parseFloat(e.replace(',','.')):NaN;return(isNaN(s)?0:s)*t},s=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(e),i='-'===s?.[1]?-1:1;t(s?.[2],i),t(s?.[3],i),t(s?.[4],i),t(s?.[5],i);return 3600*t(s?.[6],i)+60*t(s?.[7],i)+t(s?.[8],i)}getRepresentations(){return this._representations}attachSource(e,t){new ke(e,t,(s=>{this.attachManifest(s,t,(e=>{const t=document.createElement('a');return t.href=e,t.origin})(e))}),void 0,(e=>{this._params.onResponseHeaders(e)}),((e,t,s)=>this._params.onError(e,t,s)))}attachManifest(e,t,s){const i=(new DOMParser).parseFromString(e,'text/xml').documentElement,a=(e,t)=>{const s=e.attributes.getNamedItem(t);return s?s.value:null};this._duration=this._parseDurationFromISO8601(String(a(i,'mediaPresentationDuration')));const r=[],o=[];Array.prototype.forEach.call(i.getElementsByTagName('Representation'),(e=>{const i=e.getElementsByTagName('SegmentBase')[0],n=i&&a(i,'indexRange').split('-'),d=i&&i.getElementsByTagName('Initialization')[0],u=d&&a(d,'range').split('-');if(!u||!n){const t=e.parentElement;if('text'===t?.getAttribute('contentType')){const i=e.getAttribute('id')??void 0,a=(s?s+'/':'')+e.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=t.getAttribute('lang')??void 0;a&&o.push({id:i,url:a,language:r})}return}const h=Number(e.attributes.getNamedItem('bandwidth')?.value),c=(s?s+'/':'')+e.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=e.attributes.getNamedItem('frameRate')?.value??void 0;l=p?he(p):void 0,r.push({width:Number(e.attributes.getNamedItem('width')?.value),height:Number(e.attributes.getNamedItem('height')?.value),bandwidth:h,baseURL:c,failoverHosts:t,indexFrom:Number(n[0]),indexTo:Number(n[1]),initFrom:Number(u[0]),initTo:Number(u[1]),codecs:e.attributes.getNamedItem('codecs')?.value??void 0,mimeType:e.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*h/8,bufferLength:.1,name:e.attributes.getNamedItem('okQuality')?.value??void 0,id:e.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,o.forEach((({id:e,language:t,url:s})=>{const i=document.createElement('track');i.setAttribute('src',s),e&&i.setAttribute('id',e),t&&i.setAttribute('srclang',t),this._video.appendChild(i)})),this._representations.sort(((e,t)=>t.bandwidth-e.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(e,t){if(e===this._currentRepresentation)return void(t&&t());if(e.refs)return void this._stream.abort((()=>{this._stream.append(e.initMessage,t)}));const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,(s=>{let i=e.initTo-e.initFrom+1;if(!s.byteLength)return void this._params.onError('EmptyResponse','Empty response');e.initMessage=new Uint8Array(s.buffer,0,i);const a=new DataView(s.buffer);i+=12;const r=a.getUint32(i+4,!1);i+=8;let o=a.getUint32(i,!1),n=a.getUint32(i+4,!1)+(e.indexTo+1);i+=8;const d=a.getUint16(i+2,!1);i+=4,e.refs=[];for(let t=0;t<d;t+=1){const t=n+(2147483647&a.getUint32(i,!1)),s=o+a.getUint32(i+4,!1);i+=12,e.refs.push({fromTime:o/r,toTime:s/r,fromOffset:n,toOffset:t-1}),n=t,o=s}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)}),void 0,(e=>{this._params.onResponseHeaders(e),this._params.onIdxRequestPing(Date.now()-s)}),e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const s=new t;let i,a;const r=()=>{const t=this._findRef(this._video.currentTime);if(!t||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 e=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),e)}const s=this._appendVector[String(t.fromTime)];let r;s!==i&&(i=s,this._params.onRepresentationPlay(s));if(this._findRef(t.toTime)){const t=this._buffer.getByTime(this._video.currentTime);if(!t)return void this._onDashCallback('buffering');r=t.end-this._video.currentTime,r<e.bufferLength&&(this._onDashCallback('buffering'),a!==t.end&&(a=t.end,window.setTimeout((()=>{try{const e=this._buffer.getNextWithGap(t);e&&(this._video.currentTime=e.start)}catch(e){throw this._params.onError('GapSyncError',`Seek Error ${String(e)}`,e),e}}),1e3*r)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(e){throw this._params.onError('LoopError',`Dash Loop exception ${String(e)}`,e),e}o()}),250)},n=()=>{if(!this._stream)try{const t=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new $e({mediaSource:s,sourceBuffer:t,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(e){throw this._params.onError('DashSourceOpen',`Source open exception ${String(e)}`,e),e}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener('sourceopen',n),s.removeEventListener('webkitsourceopen',n)};s.addEventListener('sourceopen',n,!1),s.addEventListener('webkitsourceopen',n,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener('waiting',(()=>{const e=this._video&&this._video.played.length;e&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(e-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(e,t,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,(()=>{this._currentRepresentation=e;const i=this._findRef(t);if(i){if(s){this._isLastRef(i)&&t>=i.toTime&&(t=i.fromTime);const e=this._findRef(this._video.currentTime),s=Math.abs(this._video.currentTime-t),a=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||i===e||s<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?t:i.fromTime}this._appendVector[String(i.fromTime)]=e,this._stream.load(e,i.fromOffset,i.toOffset,((e,t)=>this._stream.append(e,t)),(()=>{this._lastLoadOffset=i.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(e=>this._params.onResponseHeaders(e)),e.bufferSize)}}))}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i)return void(this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime));const a=.1;if(i.toTime<s.end+a){const t=this._findRef(i.toTime);t&&t.toTime<s.end+a?(this._buffer.smartRemove(i.fromTime-a,t.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,t.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,i.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t=!1){this._stream&&this._buffer.getByTime(e)&&!t?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!e.isNullable(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&0===t.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let i=0;i<t.length;i++){const a=t[i];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const s=t[t.length-1];if(e>s.toTime)return s}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(10*i)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Ae;!function(e){e.STOPPED='stopped',e.MANIFEST_LOADED='manifest-loaded',e.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',e.METADATA_LOADED='metadata-loaded',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Ae||(Ae={}));const Ne=[Ae.PAUSED,Ae.PLAYING];class xe{videoState=new z(Ae.STOPPED);subscription=new e.Subscription;video;buffer;dash;representations$=new e.ValueSubject([]);currentRepresentation$=new e.ValueSubject(void 0);params;textTracksManager=new E;elementSize$=new e.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new e.Subject,responseHeaders$:new e.Subject,manifestReady$:new e.Subject,representationPlay$:new e.Subject,error$:new e.Subject};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=P(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(j(this.params.source.url)),this.buffer=new $(this.video),this.dash=new we({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:e=>this.dashLiteEvents.idxRequestPing$.next(e),onResponseHeaders:e=>this.dashLiteEvents.responseHeaders$.next(e),onManifestReady:e=>this.dashLiteEvents.manifestReady$.next(e),onRepresentationPlay:e=>this.dashLiteEvents.representationPlay$.next(e),onBandwidthChange:e=>this.params.dependencies.throughputEstimator.addRawSpeed(e.size,e.duration),onError:(e,t,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:t,thrown:s})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3}}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},a=()=>{const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.autoVideoTrackSwitching.getTransition();return t?t.to:e},r=N(this.video),o=(e,t)=>this.subscription.add(e.subscribe(t,i));o(r.timeUpdate$,t.position$),o(r.durationChange$,t.duration$),o(r.ended$,t.endedEvent$),o(r.error$,t.error$),o(r.isBuffering$,t.isBuffering$),o(r.firstFrame$,t.firstFrameEvent$),this.subscription.add(r.seeking$.subscribe((()=>{e.isNullable(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===Ae.PLAYING||this.videoState.getState()===Ae.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(v(this.video,s.isLooped,i)),this.subscription.add(y(this.video,s.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,s,t),o(Y(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ae.READY&&this.videoState.setState(Ae.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ae.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Ae.PLAYING),D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Ae.METADATA_LOADED)}),i)).add(r.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(e.map((({id:e,message:t,thrown:s})=>({id:`DashLite_${e}`,message:t,thrown:s})))).subscribe(this.params.output.error$)).add(e.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.output.element$,this.elementSize$,e.fromEvent(this.video,'progress')).pipe(e.map((()=>{const t=this.currentRepresentation$.getValue(),s=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),r=this.params.desiredState.videoTrack.getState(),o=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),n=this.elementSize$.getValue(),d=a();let u;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&e.isNonNullable(r))u=r;else{const e=G(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);u=q(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:i,currentRepresentation:t})?.id}return e.isNonNullable(u)?s.find((({track:e})=>e.id===u))?.representation:void 0})),e.filterChanged()).subscribe(this.currentRepresentation$,i)).add(e.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(e.filter((e=>e.to===Ae.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(Ae.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(e.filter(e.isNonNullable),e.filterChanged(((e,t)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?e.height<=t.height:e===t))).subscribe((e=>{const t=G(this.video.buffered,1e3*this.video.currentTime),s=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||s<=.5||!a())&&(this.dash.setQualityByRepresentation(e,!0),this.params.output.hostname$.next(j(e.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((e=>{const{type:t,reused:s}=W(e);this.params.output.httpConnectionType$.next(t),this.params.output.httpConnectionReused$.next(s)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(e.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((e=>this.params.dependencies.throughputEstimator.addRawRtt(e)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(e.filter(e.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(e.merge(s.playbackState.stateChangeStarted$,s.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const 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 e.assertNever(t)}}handleManifestReady=e=>{const t=[];for(const s of e){const e=s.name??s.id??s.height.toString(10),i=L(s),a=s.bandwidth/1e3,r={width:s.width,height:s.height},o=s.fps;if(!i)continue;const n={id:e,quality:i,bitrate:a,size:r,fps:o};t.push({track:n,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map((({track:e})=>e))),this.videoState.setState(Ae.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find((({representation:t})=>t===e))?.track;if(t){this.params.output.currentVideoTrack$.next(t);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return e.assertNonNullable(t,'Can\'t select representation. something went wrong'),t};seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e)}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(Ae.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),s=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(s)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(r)};`}),i===exports.PlaybackState.STOPPED)return void(t!==Ae.STOPPED&&(this.videoState.startTransitionTo(Ae.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(Ae.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(s)return;const o=r?.to;switch(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&Ne.includes(t)&&this.seek(o),t){case Ae.STOPPED:return this.videoState.startTransitionTo(Ae.MANIFEST_LOADED),void this.prepare();case Ae.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Ae.INITIAL_REPRESENTATION_SELECTED);case Ae.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Ae.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Ae.METADATA_LOADED:return this.videoState.startTransitionTo(Ae.READY),void this.dash.seek(o??0);case Ae.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Ae.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()));case Ae.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ae.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ae.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}var De=e=>{let t,s=!1,i=!1;e.on('playbackTimeUpdated',(({timeToEnd:e})=>{i=e<=3,s&&i&&t?.()})),e.extend('MediaSourceController',(function(){const{parent:e}=this,a=e.signalEndOfStream;return{signalEndOfStream:e=>{s=!0,t=()=>a(e),s&&i&&t?.()}}}),!0)},_e=e=>{e.extend('HTTPLoader',(function(){const{parent:e}=this,t=e.load;return{load:e=>{if(e.request&&e.request.range){const[t,s]=e.request.range.split('-').map((e=>parseInt(e,10))),i=new URL(e.request.url,location.href);i.searchParams.append('bytes',`${t}-${s}`),e.request.url=i.toString(),e.request.range=void 0}t(e)}}}),!0)};const Re=e=>e.range?e.range.split('-').map((e=>parseInt(e,10))):[NaN,NaN];class Ie{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,r]=Re(i.request);if(a>=s.from&&r<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map((({request:e})=>e)));this.activeRequests.set(e,s)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:e}of this.activeRequests.values())e.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(Re),i=s[0][0];let a=s[0][1];for(let e=1;e<s.length&&a<this.params.minDataSize;e++){const t=s[e][1];t-i<=2*this.params.minDataSize&&(a=Math.max(a,t))}a=0===i?Math.max(a,i+this.params.minInitSize):Math.max(a,i+this.params.minDataSize);const r=new URL(e,location.href);r.searchParams.append('bytes',`${i}-${a}`);const o=r.toString(),n=new AbortController,d=n.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:n};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=e=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:e}),e};return fetch(o,{signal:d}).then((e=>{if(!e.ok||!e.body)return void this.onBigRequestError(u);const[t,s]=e.body.tee();this.params.onDownloadStream?.(s);const i=t.getReader(),a=parseInt(e.headers.get('Content-Length')??'',10);u.data=new ArrayBuffer(a);const r=new Uint8Array(u.data),o=async({done:e,value:t})=>{e?this.onBigRequestProgress(u):t&&(r.set(t,u.loaded),u.loaded+=t.byteLength,this.onBigRequestProgress(u),await(i?.read().then(o,Ie.suppressStreamErrors).catch(h)))};i?.read().then(o,Ie.suppressStreamErrors).catch(h)}),Ie.suppressAbort).catch((e=>this.onBigRequestError(u,e))),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a}){if(!this.activeRequests.has(e)||!a)return;const r=this.dashJsRequestQueue.get(e)??[];for(const o of r){const{request:r}=o,[n,d]=Re(r),u=n>=t&&d<=t+i,h=t>=n&&t+i<d,c=a.slice(n-t,Math.min(d-t+1,i));(u||h)&&(r.requestStartDate=r.requestStartDate??new Date,r.firstByteDate=r.firstByteDate??new Date,r.bytesLoaded=c.byteLength,r.bytesTotal=s-t),u?(r.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter((e=>e!==o))),o.success?.(c,'',e),this.dashMetrics?.addHttpRequest(r,e,200,{},[])):h&&o.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:i}),!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const e of a){const[a,r]=Re(e.request);(a>=t&&a<s||r>t&&r<=s)&&e?.error?.(e.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const e of i){const[i,a]=Re(e.request);(i>=t&&i<s||a>t&&a<=s)&&e?.abort?.(e.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e}static suppressStreamErrors(){}}class Ce{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return'download'!==e.action||'text'===e.mediaType||!e.range||'arraybuffer'!==e.responseType}load(e){const{request:t}=e;if(Ce.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:t}=e;Ce.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Le=(e,t)=>{const s=new Ie(t);return e.extend('SchemeLoaderFactory',(function(){const{parent:e}=this,t=e.getLoader;return{getLoader:e=>((e,t)=>s=>({create:i=>{const a=e(s).create(i);return new Ce(a,t,i)}}))(t(e),s)}}),!0),()=>s.destroy()};var Oe=t=>{const s=new e.ValueSubject(1/0),i=new e.Subject;let a=NaN,r=!1;return t.extend('XHRLoader',(function(){const{parent:t}=this,o=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const o=t.onload,n=t.progress;t.onload=function(...t){return(t=>{if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const i=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),a=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*i??NaN;e.isNonNullable(a)&&!isNaN(a)&&s.next(a)})(this),o(...t)},t.progress=function(...e){return this.readyState>=2&&!r&&(r=!0,i.next(Date.now()-a)),n(...e)},a=Date.now(),r=!1}return o(t)}}}),!0),{playbackDuration$:s,ping$:i}};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(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}const Me={};var Be;!function(e){e.DOWNLOADING_LIB='downloading_lib',e.STOPPED='stopped',e.STREAM_INITIALIZED='stream_initialized',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Be||(Be={}));const Ue=(t,s)=>new e.Observable((e=>{const i=t=>e.next(t);return t.on(s,i),()=>t.off(s,i)}));class Fe{subscription=new e.Subscription;videoState=new z(Be.DOWNLOADING_LIB);video;player;params;textTracksManager=new E;videoTracks=[];frameRatesByFrameHeight={};isLive$=new e.ValueSubject(void 0);maxSeekBackTime$=new e.ValueSubject(1/0);availableFrom$=new e.ValueSubject(void 0);elementSize$=new e.ValueSubject(void 0);liveOffset=new Ve;destroyBigRequest;constructor(e){this.video=P(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(j(this.params.source.url)),this.loadDashJs()}loadDashJs(){let e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${t?.toString?.()}`,thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(Me.MediaPlayer=t.MediaPlayer,Me.Debug=t.Debug,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(Me.MediaPlayer,'dashjs not loaded'),e.assertNonNullable(Me.Debug,'dashjs not loaded'),this.player=Me.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((e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?he(e.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Le(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:e=>this.params.output.error$.next(e),onDownloadStream:e=>this.params.dependencies.throughputEstimator.trackStream(e)}):this.params.tuning.stripRangeHeader&&_e(this.player),De(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Be.STOPPED)}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(e,t)=>this.subscription.add(e.subscribe(t,i));a(Y(this.video),this.elementSize$),a(Ue(this.player,'error').pipe(e.map((e=>({id:`DashJS#${'object'==typeof e.error?e.error.code:e.error}`,message:'object'==typeof e.error?e.error.message:void 0})))),t.error$),a(Ue(this.player,'playbackError').pipe(e.map((e=>({id:'DashJSPlayback',message:e.error})))),t.error$);const r=Ue(this.player,'qualityChangeRendered').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({newQuality:e})=>this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track)));r.pipe(e.filter(e.isNonNullable)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(e.filter((({to:e})=>e===Be.STREAM_INITIALIZED)),e.once()).subscribe((()=>{this.subscription.add(g(s.videoTrack,(()=>{const e=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track?.id}),(t=>{if(e.isNullable(t))return;const s=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(e.map((e=>e?.id))),onError:i}))}),i)),this.subscription.add(g(s.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(e=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:e}}}})),{onError:i})),a(Ue(this.player,'bufferStateChanged').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({state:e})=>'bufferStalled'===e))),t.isBuffering$),a(Ue(this.player,'fragmentLoadingStarted').pipe(e.map((e=>j(e.request.url)))),t.hostname$),a(Ue(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:s,availableFrom:i}}})=>{this.isLive$.next(s),this.availableFrom$.next(i.getTime()),s||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const e of this.player.getBitrateInfoListFor('video')){const t=e.qualityIndex.toString(10),s=L(e),i=e.bitrate/1e3,o={width:e.width,height:e.height},n=this.frameRatesByFrameHeight[e.height];if(s){const d={id:t,quality:s,bitrate:i,size:o,fps:n};this.videoTracks.push({track:d,bitrateInfo:e}),e.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(Be.STREAM_INITIALIZED),this.videoState.startTransitionTo(Be.READY)})),a(Ue(this.player,'fragmentLoadingCompleted'),(({request:e})=>{if(!e.requestEndDate||!e.firstByteDate||!e.bytesLoaded)return;const t=e.requestEndDate.getTime()-e.firstByteDate.getTime(),s=e.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(s,t)})),a(e.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const e=this.params.dependencies.throughputEstimator.throughput$.getValue(),t=q(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:e,tuning:this.params.tuning.autoTrackSelection}),s=this.videoTracks.find((({track:e})=>e===t));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),a(e.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(e.filter(e.isNonNullable))}).pipe(e.filter((({isLive:e})=>e)),e.map((({maxSeekBackTime:e})=>He(e)))),this.params.output.duration$);const o=Ue(this.player,'playbackTimeUpdated').pipe(e.map((({time:e})=>e??0)));a(e.combine({availableFrom:this.availableFrom$.pipe(e.filter(e.isNonNullable)),currentTime:o}),(({availableFrom:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t))),a(o.pipe(e.filter((()=>!1===this.isLive$.getValue()))),t.position$),a(Ue(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Ue(this.player,'playbackEnded'),t.endedEvent$),a(Ue(this.player,'playbackProgress').pipe(e.map((()=>w(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Ue(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Be.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)})),a(Ue(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Be.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Ue(this.player,'playbackPaused'),(()=>{this.videoState.setState(Be.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)})),a(Ue(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===Be.READY&&this.videoState.setState(Be.READY)})),a(this.isLive$,t.isLive$),a(Y(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(e.merge(s.playbackState.stateChangeStarted$,s.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:d}=Oe(this.player);a(n,this.maxSeekBackTime$),a(d.pipe(e.once()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(e.combine({isLive:this.isLive$,isShort:t.duration$.pipe(e.map((e=>e<60)))}),(({isLive:e,isShort:t})=>{const s=!e&&t;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:s}}})})),a(o.pipe(e.filter((e=>e>this.params.tuning.insufficientBufferRuleMargin)),e.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,s,t),this.subscription.add(Ue(this.player,'manifestLoaded').pipe(e.once()).subscribe((()=>{const s=Date.now();this.subscription.add(Ue(this.player,'playbackPlaying').pipe(e.once()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-s)),i))}),i)),this.subscription.add(v(this.video,s.isLooped,i));const{volumeState$:u}=N(this.video);this.subscription.add(y(this.video,s.volume,u,i)),this.subscription.add(u.subscribe(t.volume$,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Be.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Be.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-Math.round(1e3*e),s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(He(s));const i=ve(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ge.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e)}play(){this.videoState.startTransitionTo(Be.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Be.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),s=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===Be.DOWNLOADING_LIB||t===Be.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==Be.STOPPED&&s!==exports.PlaybackState.STOPPED&&(r?this.seek(o+He(this.liveOffset.getTotalPausedTime())):this.seek(o)),s){case exports.PlaybackState.STOPPED:switch(t){case Be.STOPPED:break;case Be.PLAYING:case Be.PAUSED:case Be.READY:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case Be.PLAYING:break;case Be.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(He(this.liveOffset.getTotalOffset()))):this.seek(He(this.liveOffset.getTotalOffset()))),this.play();break;case Be.READY:this.play();break;case Be.STOPPED:this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case Be.PLAYING:this.pause(),this.liveOffset.pause();break;case Be.PAUSED:break;case Be.READY:this.videoState.setState(Be.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Be.STOPPED:this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(e){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}const He=e=>-e/1e3;function qe(){return e.now()}function Ge(e){return qe()-e}function je(e){const t=e.split('/'),s=t.slice(0,t.length-1).join('/'),i=/^([a-z]+:)?\/\//i;return{resolve:(e,t,a=!1)=>{(e=>i.test(e))(e)||(e.startsWith('/')||(e='/'+e),e=s+e);let r=e.indexOf('?')>-1?'&':'?';return a&&(e+=r+'lowLat=1',r='&'),t&&(e+=r+'_rnd='+Math.floor(999999999*Math.random())),e}}}function Ye(t,s,i,a){const r=window.XMLHttpRequest;let o,n,d,u,h,c=!1,l=0,p=!1,m='arraybuffer',S=7e3,b=2e3,f=()=>{if(c)return;e.assertNonNullable(u);const t=Ge(u);let s;if(t<b)return s=b-t,void setTimeout(f,s);b*=2,b>S&&(b=S),n&&n.abort(),n=new r,v()};const g=()=>{if(!c){if(--l>=0)return f(),void(a&&a());c=!0,h&&h(),i&&i()}},v=()=>{u=qe(),n=new r,n.open('get',t);let i,a=0,l=0;const S=()=>(e.assertNonNullable(u),Math.max(u,Math.max(i||0,l||0)));if(o&&n.addEventListener('progress',(e=>{const t=qe();o.updateChunk&&e.loaded>a&&(o.updateChunk(S(),e.loaded-a),a=e.loaded,i=t)})),d&&(n.timeout=d,n.addEventListener('timeout',(()=>g()))),n.addEventListener('load',(()=>{if(c)return;e.assertNonNullable(n);const t=n.status;if(t>=200&&t<300){if(n.response.byteLength&&o){const e=n.response.byteLength-a;e&&o.updateChunk&&o.updateChunk(S(),e)}h&&h(),n&&s(n.response)}else g()})),n.addEventListener('error',(()=>{g()})),p){const t=()=>{e.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(l=qe(),n.removeEventListener('readystatechange',t))};n.addEventListener('readystatechange',t)}return n.responseType=m,n.send(),y},y={withBitrateReporting:e=>(o=e,y),withParallel:e=>(p=e,y),withJSONResponse:()=>(m='json',y),withRetryCount:e=>(l=e,y),withRetryInterval:(t,s)=>(e.isNonNullable(t)&&(b=t),e.isNonNullable(s)&&(S=s),y),withTimeout:e=>(d=e,y),withFinally:e=>(h=e,y),send:v,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return y}class ze{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<.1*this.currentRate?t=.8:e<.5*this.currentRate?t=.5:e<.7*this.currentRate&&(t=.3)),e=Math.max(1,Math.min(e,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end&&(this._doMergeIntervals(e,t),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let s=0,i=0;for(;this.intervals.length>0;){const e=this.intervals[0];if(e.end<=t)s+=e.end-e.start,i+=e.bytes,this.intervals.splice(0,1);else{if(e.start>=t)break;{const a=t-e.start,r=e.end-e.start;s+=a;const o=e.bytes*a/r;i+=o,e.start=t,e.bytes-=o}}}if(i>0&&s>0){const a=8*i/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>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 Qe{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:'warn'}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=qe(),i=s=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=s,e._errorCB?e._errorCB(s):(this.limitCompleteCount(),this.completeRequests[t]=e)};e._request=Ye(t,(i=>{e._complete=1,e._responseData=i,e._downloadTime=qe()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(i,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)}),(()=>i('error')),(()=>{e._retry=1,e._retryCB&&e._retryCB()})),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{e._finallyCB&&e._finallyCB()})),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=qe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=qe();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(s>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),s),!1)}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(!e)return;this.activeRequests[e]||this.completeRequests[e]||(this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e))}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach((e=>{e&&e._request&&e._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,i){const a={};return a.send=()=>{const r=this.activeRequests[e]||this.completeRequests[e];if(r)r._cb=t,r._errorCB=s,r._retryCB=i,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(e),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${e}`);else{const t=this.pendingQueue.indexOf(e);-1!==t&&this.pendingQueue.splice(t,1),this.logger(`Request not prefetched, starting new request, url=${e}${-1===t?'':'; removed pending'}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=e=>(a._finallyCB=e,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}class We{paused=!1;autoQuality=!0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ze(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=je(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e)return void this._switchToQuality(t)}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=je(e),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return 0!==s&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:'buffering',isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener('error',(s=>{this.destroyed||(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),e.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),e.pause(),this.videoPlayStarted=!1}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),e.addEventListener('playing',(()=>{t('playing')})),e.addEventListener('stalled',(()=>this._fixupStall())),e.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let i;0!==s&&(i=t.buffered.start(s-1),t.currentTime<i&&(e('Fixup stall'),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,a;const r=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let t=0;t<this.manifest.length;++t)a=this.manifest[t],a.bitrate<e&&r>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a);return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||e.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,s){const{logger:i,videoElement:a,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{e.assertNonNullable(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],s()})),this.videoPlayStarted=!1,a.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const o=()=>{!function(e,t,s){const i=(...a)=>{s.apply(null,a),e.removeEventListener(t,i)};e.addEventListener(t,i)}(a,'progress',(()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),r({name:'playing'})):o()}))};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qe(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(e,(()=>this._switchToQuality(e)))}_representation(t){const{logger:s,videoElement:i,playerCallback:a}=this.params;let r=!1,o=null,n=null,d=null,u=null,h=!1;const c=()=>{const e=r&&(!h||h===this.rep);return e||s('Not running!'),e},l=(e,t,s)=>{d&&d.abort(),d=Ye(this.urlResolver.resolve(e,!1),t,s,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{d=null})).send()},p=(t,s,i)=>{e.assertNonNullable(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),s,i,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=e=>{const t=i.playbackRate;i.playbackRate!==e&&(s(`Playback rate switch: ${t}=>${e}`),i.playbackRate=e)},S=e=>{this.lowLatency=e,s(`lowLatency changed to ${e}`),b()},b=()=>{if(this.lowLatency){let e=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const t=qe()-6e4;let i=0;for(let s=0;s<this.bufferStates.length;s++){const a=this.bufferStates[s];e=Math.min(e,a.buf),a.ts<t&&i++}this.bufferStates.splice(0,i),s(`update playback rate; minBuffer=${e} drop=${i} jitter=${this.sourceJitter}`);let a=e-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},f=t=>{let i;const r=()=>i&&i.start?i.start.length:0,o=e=>i.start[e]/1e3,n=e=>i.dur[e]/1e3,d=e=>i.fragIndex+e,h=(e,t)=>({chunkIdx:d(e),startTS:o(e),dur:n(e),discontinuity:t}),l=()=>{let e=0;if(i&&i.dur){let t=Math.max(this.sourceJitter,1);for(this.lowLatency||(t+=2),e=i.dur.length-1;e>=0&&(t-=i.dur[e]/1e3,!(t<=0));--e);}return h(e,!0)},p=(e,t,s)=>{u&&u.abort(),u=Ye(this.urlResolver.resolve(e,!0,this.lowLatency),t,s,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(s,n)=>{p(t,(t=>{if(!c())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let e=0;e<i.dur.length;++e)u+=i.dur[e];u>0&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,s((t=>{const s=r();if(!(s<=0)){if(e.isNonNullable(t))for(let e=0;e<s;e++)if(o(e)>t)return h(e);return l()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:e=>{const t=r(),a=e?e.chunkIdx+1:0,o=a-i.fragIndex;if(!(t<=0)){if(!e||o<0||o-t>10)return s(`Resync: offset=${o} bChunks=${t} chunk=`+JSON.stringify(e)),l();if(!(o>=t))return h(a-i.fragIndex,!1)}}}},g=()=>{r=!1,n&&n.abort(),d&&d.abort(),u&&u.abort(),e.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:s=>{const{videoElement:i,logger:a}=this.params;let n,d,h,m,S,v,y,T=f(t.jidxUrl),E=0;const P=()=>{S&&(clearTimeout(S),S=void 0);const e=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=E+e,s=qe(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=qe(),k(),P())}))};i>0?S=window.setTimeout((()=>{this.paused?P():a()}),i):a()},k=()=>{let e;for(;e=T.nextChunk(m);)m=e,x(e);const s=T.nextChunk(h);if(s){if(h&&s.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?P():(g(),this._initPlayerWith(t)));N(s)}else P()},$=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&$(e,t)}),s)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const d=qe(),u=i.currentTime;!this.paused&&i.buffered.length>1&&v===u&&d-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),v!==u&&(v=u,y=d);const h=this._getBufferSizeSec();if(h>30)a(`Buffered ${h} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(e),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),t&&t()}catch(e){if('QuotaExceededError'!==e.name)throw e;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(s=this.sourceBuffer.buffered.start(0),r=u,r-s>4&&this.sourceBuffer.remove(s,r-3)),n(1e3)}}},w=()=>{d&&n&&(a([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),$(d,(function(){d=null,k()})))},A=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),N=e=>{c()&&p(A(e),((t,s)=>{if(c()){if(s/=1e3,d=t,h=e,o=e.startTS,s){const t=Math.min(10,e.dur/s);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*t:t}w()}}),(()=>this._handleNetworkError()))},x=t=>{c()&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(t),!1)))},D=e=>{c()&&(t.cachedHeader=e,$(e,(()=>{n=!0,w()})))};r=!0,T.seek((t=>{c()&&(E=qe(),t?(m=t,!e.isNullable(s)||t.startTS>s?N(t):(h=t,k())):P())}),s),t.cachedHeader?D(t.cachedHeader):l(t.headerUrl,D,(()=>this._handleNetworkError()))},stop:g,getTimestampSec:()=>o},h}_switchToQuality(t){const{logger:s,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),e.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),s(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,e.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return e.isNonNullable(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=t=>{if(!this.autoQuality)return;let s,i,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&t<this.bitrate&&(i=this._getBufferSizeSec(),a=t/this.bitrate,i>10&&a>.8||i>15&&a>.5||i>20&&a>.3)?e(`Not switching: buffer=${Math.floor(i)}; bitrate=${this.bitrate}; newRate=${Math.floor(t)}`):(s=this._selectQuality(t),s?this._switchToQuality(s):e(`Could not find quality by bitrate ${t}`))},i=(()=>({updateChunk:(e,s)=>{const i=qe();if(this.chunkRateEstimator.addInterval(e,i,s)){const a=this.chunkRateEstimator.getBitRate();return t({name:'bandwidth',size:s,duration:i-e,speed:a}),!0}},get:()=>{const e=this.chunkRateEstimator.getBitRate();return e?.85*e:0}}))();let a,r=-1/0,o=!0;const n=()=>{let e=i.get();if(e&&a&&this.autoQuality){if(o&&e>a&&Ge(r)<3e4)return;s(e)}o=this.autoQuality};return{updateChunk:(e,t)=>{const s=i.updateChunk(e,t);return s&&n(),s},notifySwitch:e=>{const t=qe();e<a&&(r=t),a=e}}}_fetchManifest(e,t,s){this.manifestRequest=Ye(this.urlResolver.resolve(e,!0),t,s,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(e){const{videoElement:t}=this.params;f(t).then((t=>{t||e?.()}))}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params;this.manifest=(e=>{const t=[];return e?.length?(e.forEach(((e,s)=>{e.video&&i.canPlayType(e.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(e.codecs)&&(e.index=s,t.push(e))})),t.sort((function(e,t){return e.video&&t.video?t.video.height-e.video.height:t.bitrate-e.bitrate})),t):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:'manifest',manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(e,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))}),(()=>this._refetchManifest(e)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var Je;!function(e){e.STOPPED='stopped',e.MANIFEST_READY='manifest_ready',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Je||(Je={}));const Ke=[Je.PAUSED,Je.PLAYING,Je.READY],Xe=[Je.PAUSED,Je.PLAYING,Je.READY];class Ze{subscription=new e.Subscription;video;videoState=new z(Je.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new E;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new Ve;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const s=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=P(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(j(this.params.source.url)),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=N(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Je.READY&&this.videoState.setState(Je.READY)}),s)).add(i.pause$.subscribe((()=>{this.videoState.setState(Je.PAUSED)}),s)).add(i.playing$.subscribe((()=>{this.videoState.setState(Je.PLAYING)}),s)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map(et)).subscribe(this.params.output.duration$)).add(e.combine({zeroTime:this.zeroTime$.pipe(e.filter(e.isNonNullable)),position:i.timeUpdate$}).subscribe((({zeroTime:e,position:t})=>this.params.output.liveTime$.next(e+1e3*t)),s)).add(v(this.video,this.params.desiredState.isLooped,s)).add(y(this.video,this.params.desiredState.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(this.params.output.volume$,s)).add(A(this.video).subscribe(this.params.output.firstBytesEvent$)).add(k(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Je.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Je.MANIFEST_READY:case Je.READY:break;case Je.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Je.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return e.assertNever(t.to)}}),s)).add(e.merge(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekPosition.stateChangeStarted$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new We({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:e=>{this.params.dependencies.logger.log({message:String(e),component:'LiveDashPlayer'})}});return e.pause(),e}prepare(){const t=this.representations$.getValue(),s=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&&e.isNonNullable(s)?s:q(t.map((({track:e})=>e)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection})?.id,r=t.find((({track:e})=>e.id===a))?.representation;e.assertNonNullable(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 s=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;e.assertNonNullable(s),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-Math.round(1e3*e),s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(et(s)),this.dash.reinit(ve(this.params.source.url,s)),this.params.output.seekedEvent$.next()}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,s=[];for(const t of e){const e=t.name??t.index.toString(10),i=L(t.video),a=t.bitrate/1e3,r={...t.video};if(!i)continue;const o={id:e,quality:i,bitrate:a,size:r};s.push({track:o,representation:t})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map((({track:e})=>e))),this.videoState.getTransition()?.to===Je.MANIFEST_READY&&this.videoState.setState(Je.MANIFEST_READY);break}case'qualitySwitch':{const s=t.quality,i=this.representations$.getValue().find((({representation:e})=>e===s))?.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),e.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:s}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,s);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),s=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(s)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(r)};`}),i===exports.PlaybackState.STOPPED)return void(t!==Je.STOPPED&&(this.videoState.startTransitionTo(Je.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Je.STOPPED)));if(s)return;if(Xe.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;e.isNonNullable(t)&&this.setVideoTrack(t);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}const o=r?.to;if(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&Ke.includes(t))this.seek(o+et(this.liveOffset.getTotalPausedTime()));else switch(t){case Je.STOPPED:return this.videoState.startTransitionTo(Je.MANIFEST_READY),void this.dash.attachSource(ve(this.params.source.url));case Je.MANIFEST_READY:this.videoState.startTransitionTo(Je.READY),this.prepare();break;case Je.READY:return void(i===exports.PlaybackState.PAUSED?this.videoState.setState(Je.PAUSED):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Je.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Je.PAUSED)}))));case Je.PLAYING:return void(i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Je.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Je.PAUSED:return void(i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Je.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(Je.PAUSED)})),this.params.output.position$.next(et(this.liveOffset.getTotalOffset()))):this.seek(et(this.liveOffset.getTotalOffset()))));default:return e.assertNever(t)}}}const et=e=>-e/1e3;var tt=e=>{switch(e){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}};const st=e=>{let t=null;if(e.QUALITY&&(t=tt(e.QUALITY)),!t&&e.RESOLUTION){const[s,i]=e.RESOLUTION.split('x').map((e=>parseInt(e,10)));t=L({width:s,height:i})}return t??null},it=async(e,t=e)=>{const s=await fetch(e),i=(await s.text()).split('\n'),a=[];for(let e=0;e<i.length;e++){const s=i[e].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const r=Object.fromEntries(s[1].split(',').map((e=>e.split('=')))),o=r.QUALITY??`stream-${r.BANDWIDTH}`,n=st(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 u=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let h;if(r.RESOLUTION){const[e,t]=r.RESOLUTION.split('x').map((e=>parseInt(e,10)));e&&t&&(h={width:e,height:t})}const c=new URL(i[++e],t).toString();n&&a.push({id:o,quality:n,url:c,bandwidth:d,size:h,fps:u})}return a};var at;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(at||(at={}));class rt{subscription=new e.Subscription;videoState=new z(at.STOPPED);video;params;textTracksManager=new E;manifests$=new e.ValueSubject([]);constructor(e){this.params=e,this.video=P(e.container),this.params.output.element$.next(this.video);const t={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(j(this.params.source.url)),it(this.params.source.url).then((e=>{this.manifests$.next([t,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=N(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,s.isLooped,i)),this.subscription.add(y(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(at.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(at.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===at.READY&&this.videoState.setState(at.READY),this.videoState.getState()===at.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(j(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===at.CHANGING_MANIFEST&&this.videoState.setState(s.to),t&&e.isNonNullable(t.to)&&this.seek(t.to)}),i))),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekPosition.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();e.isNullable(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(at.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==at.STOPPED&&(this.videoState.startTransitionTo(at.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(at.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===at.STOPPED)return this.videoState.startTransitionTo(at.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(at.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:s}=this.video;return this.prepare(),void(o&&!e.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(s))}const n=o?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(n)&&this.seek(n),t){case at.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(at.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(at.PLAYING),this.playIfAllowed()));case at.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(at.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case at.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(at.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case at.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}var ot;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(ot||(ot={}));class nt{subscription=new e.Subscription;videoState=new z(ot.STOPPED);video;params;textTracksManager=new E;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new Ve;manifestStartTime$=new e.ValueSubject(void 0);constructor(t){this.params=t,this.video=P(t.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),it(ve(this.params.source.url)).then((e=>{this.manifests$.next([s,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(j(this.params.source.url)),this.maxSeekBackTime$=new e.ValueSubject(t.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=N(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,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(s.isLooped.stateChangeStarted$.subscribe((()=>s.isLooped.setState(!1)),i)),this.subscription.add(y(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ot.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ot.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ot.READY&&this.videoState.setState(ot.READY),this.videoState.getState()===ot.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map(dt)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(j(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===ot.CHANGING_MANIFEST&&this.videoState.setState(s.to),t&&e.isNonNullable(t.to)&&this.seek(t.to)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const e=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(e||void 0)}),i)),this.subscription.add(e.combine({startTime:this.manifestStartTime$.pipe(e.filter(e.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t)),i)),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(e.isNullable(t))return;const s=ve(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',s),this.video.load(),(async e=>{const t=await fetch(e,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0})(s).then((t=>{e.isNullable(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(ot.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next();const t=-Math.round(1e3*e),s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(dt(s)),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==ot.STOPPED&&(this.videoState.startTransitionTo(ot.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(ot.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===ot.STOPPED)return this.videoState.startTransitionTo(ot.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(ot.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const s=dt(this.liveOffset.getTotalOffset());return this.prepare(),void(o&&!e.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(s))}const n=o?.to;if(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(n))return this.videoState.startTransitionTo(ot.READY),this.seek(n+dt(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case ot.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(ot.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ot.PLAYING),this.playIfAllowed()));case ot.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ot.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ot.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ot.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(dt(this.liveOffset.getTotalOffset()))):this.seek(dt(this.liveOffset.getTotalOffset()))):i?.to===exports.PlaybackState.PAUSED&&(D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case ot.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}const dt=e=>-e/1e3,ut={};var ht;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ht||(ht={}));const ct=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class lt{subscription=new e.Subscription;videoState=new z(ht.INITIALIZING);video;params;hls;textTracksManager=new E;trackLevels=new Map;constructor(e){this.video=P(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(j(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 e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('hls.js'))})).then((t=>{e||(ut.Hls=t.default,ut.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(ut.Hls,'hls.js not loaded'),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ht.STOPPED)}subscribe(){e.assertNonNullable(ut.Events,'hls.js not loaded');const{desiredState:t,output:s}=this.params,i=e=>{s.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:e})},a=N(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,s.position$),r(a.durationChange$,s.duration$),r(a.ended$,s.endedEvent$),r(a.error$,s.error$),r(a.isBuffering$,s.isBuffering$),r(a.currentBuffer$,s.currentBuffer$),r(a.firstBytes$,s.firstBytesEvent$),r(a.firstFrame$,s.firstFrameEvent$),r(a.seeked$,s.seekedEvent$),this.subscription.add(v(this.video,t.isLooped,i)),this.subscription.add(y(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.hls,ut.Events.ERROR).subscribe((e=>{e.fatal&&s.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),message:`HlsJs fatal ${e.type} ${e.details}, ${e.err?.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ht.PLAYING),D(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ht.PAUSED),D(t.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ht.READY&&this.videoState.setState(ht.READY),this.videoState.getState()===ht.PLAYING&&this.playIfAllowed()}),i)),r(ct(this.hls,ut.Events.MANIFEST_PARSED).pipe(e.map((({levels:e})=>e.reduce(((e,t)=>{const s=t.name||t.height.toString(10),{width:i,height:a}=t,r=tt(t.attrs.QUALITY??'')??L({width:i,height:a});if(!r)return e;const o=t.attrs['FRAME-RATE']?parseFloat(t.attrs['FRAME-RATE']):void 0,n={id:s.toString(),quality:r,bitrate:t.bitrate/1e3,size:{width:i,height:a},fps:o};return this.trackLevels.set(s,{track:n,level:t}),e.push(n),e}),[])))),s.availableVideoTracks$),r(ct(this.hls,ut.Events.LEVEL_LOADING).pipe(e.map((({url:e})=>j(e)))),s.hostname$),this.subscription.add(g(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(e=>{this.hls.nextLevel=e?-1:this.hls.currentLevel,this.hls.loadLevel=e?-1:this.hls.loadLevel}),{onError:i}));const o=e=>Array.from(this.trackLevels.values()).find((({level:t})=>t===e))?.track,n=ct(this.hls,ut.Events.LEVEL_SWITCHED).pipe(e.map((({level:e})=>o(this.hls.levels[e]))));n.pipe(e.filter(e.isNonNullable)).subscribe(s.currentVideoTrack$,i),this.subscription.add(g(t.videoTrack,(()=>o(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(e.isNullable(t))return;const s=this.trackLevels.get(t)?.level;if(!s)return;const i=this.hls.levels.indexOf(s),a=this.hls.currentLevel,r=this.hls.levels[a];!r||s.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:n.pipe(e.map((e=>e?.id))),onError:i})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,s);const d=e.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(t===ht.INITIALIZING)return;const r=a?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(r)&&this.seek(r),s){case exports.PlaybackState.STOPPED:switch(t){case ht.STOPPED:break;case ht.READY:case ht.PLAYING:case ht.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case ht.PLAYING:break;case ht.STOPPED:this.prepare();break;case ht.READY:case ht.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case ht.PAUSED:break;case ht.STOPPED:this.prepare();break;case ht.READY:this.videoState.setState(ht.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case ht.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(ht.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ht.PLAYING);await f(this.video)||(this.videoState.setState(ht.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ht.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e}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(ht.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class pt{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const mt=(()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)})(),St=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),bt=document.createElement('video'),ft={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(bt.canPlayType?.('application/x-mpegurl')||bt.canPlayType?.('vnd.apple.mpegURL'))},gt={mp4:Boolean(bt.canPlayType?.('video/mp4')),webm:Boolean(bt.canPlayType?.('video/webm'))},vt={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"'))},yt=(vt.h264||vt.h265)&&vt.aac,Tt=!mt,Et=St||mt,Pt=!ft.hls||!Et,kt=3e4,$t=18e4,wt=3,At=100,Nt={cacheDuration:12e4},xt={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Dt={maxPausedTime:3e4},_t={maxPausedTime:3e4};class Rt{current$=new e.ValueSubject({type:void 0});providerError$=new e.Subject;noAvailableProvidersError$=new e.Subject;providerOutput={position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),volume$:new e.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new e.ValueSubject(void 0),availableVideoTracks$:new e.ValueSubject([]),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),error$:new e.Subject,willSeekEvent$:new e.Subject,seekedEvent$:new e.Subject,endedEvent$:new e.Subject,firstBytesEvent$:new e.Subject,firstFrameEvent$:new e.Subject,isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),element$:new e.ValueSubject(void 0)};subscription=new e.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.screenFormatsPriority.filter((e=>!s.includes(e))),...t.screenFormatsPriority.filter((e=>s.includes(e)))]:t.screenFormatsPriority;this.screenFormatsIterator=new pt(i.filter((s=>e.isNonNullable(t.sources[s]))).filter((t=>{switch(t){case exports.VideoFormat.DASH:return ft.mse&&gt.mp4&&yt&&Tt;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return ft.mse&&gt.mp4&&yt;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return ft.mse&&gt.webm&&vt.vp9&&vt.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return ft.mse&&gt.mp4&&yt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return ft.hls&&gt.mp4&&Et;case exports.VideoFormat.HLS_JS:return ft.mse&&gt.mp4&&yt&&Pt;case exports.VideoFormat.MPEG:return gt.mp4;default:return e.assertNever(t)}}))),this.chromecastFormatsIterator=new pt(t.chromecastFormatsPriority.filter((s=>e.isNonNullable(t.sources[s]))))}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(),s=this.chooseFormat(t);if(e.isNullable(s))return void this.handleNoFormatsError(t);const i=this.createProvider(t,s);this.current$.next({type:s,provider:i,destination:t})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;e.assertNonNullable(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const s=this.params.desiredState.seekPosition,i=s.getTransition();i?e.isNonNullable(i.from)&&s.startTransitionTo(i.from):s.startTransitionTo(this.providerOutput.position$.getValue()),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,s){switch(this.log({message:`createProvider: ${t}:${s}`}),t){case o.SCREEN:return this.createScreenProvider(s);case o.CHROMECAST:return this.createChromecastProvider(s);default:return e.assertNever(t)}}createScreenProvider(t){const{sources:s,container:i,desiredState:a}=this.params,r=this.providerOutput;switch(t){case exports.VideoFormat.DASH:{const o=s[t];return e.assertNonNullable(o),new xe({container:i,source:o,desiredState:a,output:r,config:Nt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const o=s[t];return e.assertNonNullable(o),new fe({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];return e.assertNonNullable(o),new Fe({container:i,source:o,desiredState:a,output:r,format:t,config:_t,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];return e.assertNonNullable(o),new rt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const o=s[t];return e.assertNonNullable(o),new nt({container:i,source:o,desiredState:a,output:r,config:Dt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=s[t];return e.assertNonNullable(o),new lt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const o=s[t];return e.assertNonNullable(o),new Pe({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const o=s[t];return e.assertNonNullable(o),new Ze({container:i,source:o,desiredState:a,output:r,config:xt,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return e.assertNever(t)}}createChromecastProvider(t){const{sources:s,container:i,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return e.assertNonNullable(n),new Te({connection:n,meta:r,container:i,source:s,format:t,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?o.CHROMECAST:o.SCREEN}chooseFormat(t){switch(t){case o.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case o.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return e.assertNever(t)}}skipFormat(t){switch(t){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return e.assertNever(t)}}handleNoFormatsError(t){switch(t){case o.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case o.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return e.assertNever(t)}}initProviderErrorHandling(){let t=[],s=0;const i=new e.Subscription;var a;return i.add(e.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:kt,position$:this.providerOutput.position$,providerChanged$:this.current$},new e.Observable((t=>{const s=new e.Subscription,i=e.timeout(a.maxTransitionInterval),r=new e.ValueSubject(void 0);e.merge(a.desiredPlaybackState$.stateChangeStarted$.pipe(e.mapTo(i)),a.desiredPlaybackState$.stateChangeEnded$.pipe(e.mapTo(void 0)),a.providerChanged$.pipe(e.map((()=>r.getValue())))).subscribe(r);const o=new e.Subscription;return s.add(o),s.add(r.subscribe((e=>{o.unsubscribe(),e&&o.add(e.subscribe(t))}))),s}))).pipe(e.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),i.add(this.providerError$.pipe(e.throttle(At,{leading:!1,trailing:!0})).subscribe((()=>{const i=Date.now();this.current$.getValue().destination===o.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):e.isNonNullable(t[s])&&i<t[s]+$t?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%wt}))),i}}const It=(e,t,s)=>s*t+(1-s)*e;class Ct{prevReported=void 0;slow;fast;smoothed;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(t){this.params=t,this.slow=this.fast=this.smoothed=this.prevReported=t.initial,this.smoothed$=new e.ValueSubject(t.initial),this.debounced$=new e.ValueSubject(t.initial);const s=t.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new F(`raw_${s}`),this.smoothedSeries$=new F(`smoothed_${s}`),this.reportedSeries$=new F(`reported_${s}`)}next(t){this.slow=It(this.slow,t,this.params.emaAlphaSlow),this.fast=It(this.fast,t,this.params.emaAlphaFast);const s=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=s(this.slow,this.fast),this.smoothed$.next(this.smoothed),(e.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed)),this.rawSeries$.next(t),this.smoothedSeries$.next(this.smoothed)}}var Lt;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(Lt||(Lt={}));const Ot=new Map;let Vt=Lt.RUNTIME;const Mt=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Mt,'test'),localStorage.removeItem(Mt),Vt=Lt.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;try{sessionStorage.getItem(Mt),Vt=Lt.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;Vt=Lt.RUNTIME}}})();const Bt=(t,s)=>{switch(Vt){case Lt.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Lt.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Lt.RUNTIME:return void Ot.set(t,s);default:e.assertNever(Vt)}},Ut=window.navigator.connection,Ft=()=>{const t=Ut?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},Ht=()=>{const t=Ut?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},qt=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class Gt{throughput;rtt;subscription=new e.Subscription;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=Gt.load('one_video_throughput')||(t.useBrowserEstimation?Ft():void 0)||5e3,i=Gt.load('one_video_rtt')??(t.useBrowserEstimation?Ht():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(qt(s,i,t.rttPenaltyRequestSize)),this.throughput=new Ct({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new Ct({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=Ft();t&&this.throughput.next(t);const s=Ht();e.isNonNullable(s)&&this.rtt.next(s)};Ut&&'onchange'in Ut&&this.subscription.add(e.fromEvent(Ut,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{Bt('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{Bt('one_video_rtt',e.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(e.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(e.map((({throughput:e,rtt:s})=>qt(e,s,t.rttPenaltyRequestSize))),e.filter((e=>{const s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(e-s)/s>=t.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let s=0,i=e.now();const a=new e.Subscription;switch(this.subscription.add(a),t.readyState){case 4:break;case 3:case 2:a.add(e.fromEvent(t,'progress').pipe(e.once()).subscribe((t=>{s=t.loaded,i=e.now()})));break;case 1:case 0:a.add(e.fromEvent(t,'loadstart').subscribe((()=>{s=0,i=e.now()})))}a.add(e.fromEvent(t,'loadend').subscribe((r=>{if(200===t.status){const t=r.loaded,a=e.now(),o=t-s,n=a-i;this.addRawSpeed(o,n)}a.unsubscribe()})))}trackStream(t){const s=t.getReader();if(!s)return void t.cancel('Could not get reader');let i=0;const a=e.now();let r=0,o=e.now();const n=e=>{s.releaseLock(),t.cancel(`Throughput Estimator error: ${e}`).catch((()=>{}))},d=async({done:t,value:u})=>{t?this.addRawSpeed(i,e.now()-a):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&e.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,e.now()-o),r=0,o=e.now()),await(s?.read().then(d,n)))};s?.read().then(d,n)}addRawSpeed(e,t){if(Gt.sanityCheck(e,t)){const s=8*e/t;this.throughput.next(s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=8*e/t;return!(!s||!isFinite(s))&&(!(s>1e6)&&(!(s<30)&&(!(e<10240)&&!(t<=20))))}static load(t){const s=(t=>{switch(Vt){case Lt.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Lt.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Lt.RUNTIME:return Ot.get(t);default:e.assertNever(Vt)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const jt=(t=(e=>e))=>({playbackState:s,seekPosition:i,playbackAbort$:a,position$:r})=>new e.Observable((o=>{let n;const d=s.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),u=s.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),h=i.stateChangeEnded$.pipe(e.filter((t=>e.isNonNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),c=i.stateChangeEnded$.pipe(e.filter((t=>e.isNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),l=e.merge(d,c).pipe(e.map((()=>t(r.getValue())))),p=e.merge(u,h,a).pipe(e.map((()=>t(r.getValue()))));return(new e.Subscription).add(l.subscribe((e=>{n=t(e)}))).add(p.subscribe((s=>{if(e.isNullable(n))return;const i={start:n,end:t(s)};n=void 0,o.next(i)})))})),Yt=jt((e=>e)),zt=jt((e=>Math.round(1e3*e)+Date.now())),Qt={[o.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return e.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return e.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return e.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return e.ValueSubject}}),exports.Player=class{subscription=new e.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new e.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekPosition:new z(void 0),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),isLooped:new z(!1),externalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({})};info={playbackState$:new e.ValueSubject(exports.PlaybackState.STOPPED),position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),muted$:new e.ValueSubject(!1),volume$:new e.ValueSubject(1),availableQualities$:new e.ValueSubject([]),availableQualitiesFps$:new e.ValueSubject({}),currentQuality$:new e.ValueSubject(void 0),isAutoQualityEnabled$:new e.ValueSubject(!0),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),isStalled$:new e.ValueSubject(!1),isEnded$:new e.ValueSubject(!1),isLooped$:new e.ValueSubject(!1),isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),currentFormat$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),throughputEstimation$:new e.ValueSubject(void 0),rttEstimation$:new e.ValueSubject(void 0),videoBitrate$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),chromecastState$:new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new e.ValueSubject(void 0),intrinsicVideoSize$:new e.ValueSubject(void 0)};events={started$:new e.Subject,startAttempt$:new e.Subject,willPause$:new e.Subject,willResume$:new e.Subject,willDestruct$:new e.Subject,watchCoverageRecord$:new e.Subject,watchCoverageLive$:new e.Subject,managedError$:new e.Subject,fatalError$:new e.Subject,ended$:new e.Subject,seeked$:new e.Subject,willSeek$:new e.Subject,firstBytes$:new e.Subject,firstFrame$:new e.Subject,log$:new e.Subject};experimental={element$:new e.ValueSubject(void 0),enableDebugTelemetry$:new e.ValueSubject(!1),dumpTelemetry:B};constructor(e={}){if(this.initLogs(),this.tuning=(e=>{const t={};for(const s of Object.keys(h)){const i=h[s],a=e[s];Array.isArray(i)&&Array.isArray(a)?t[s]=a:t[s]='object'==typeof i&&'object'==typeof a?{...i,...a}:a??i}return t})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,t,s)=>{const i=Reflect.get(e,t,s);return'function'!=typeof i?i:(...s)=>{try{return i.apply(e,s)}catch(e){const i=s.map((e=>JSON.stringify(e,((e,t)=>{const s=typeof t;return['number','string','boolean'].includes(s)?t:null===t?null:`<${s}>`})))),a=`Player.${String(t)}`,r=`Exception calling ${a} (${i.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:e}),e}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const s='string'==typeof t.container?document.getElementById(t.container):t.container;return e.assertNonNullable(s,`Wrong container or containerId {${t.container}}`),s})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new Rt({screenFormatsPriority:[...Qt[o.SCREEN].live,...Qt[o.SCREEN].vod],chromecastFormatsPriority:[...Qt[o.CHROMECAST].live,...Qt[o.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 e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekPosition.startTransitionTo(e),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e),this}setVolume(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(t){e.assertNonNullable(this.providerContainer);const s=this.providerContainer.providerOutput.availableVideoTracks$.getValue();s.length||(this.explicitInitialQuality=t);const i=s.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map((e=>({type:'external',...e})))),this}selectTextTrack(e){return(void 0===e||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((t=>t.id===e)))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){e.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(e.isNullable(t))return this.info.position$.getValue();const s=this.desiredState.seekPosition.getTransition(),i=s?.to??s?.from;return e.isNonNullable(i)?i:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(e.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(e.map((e=>e.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isAutoQualityEnabled$));const t=new e.Subscription;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING||e.to===exports.PlaybackState.PAUSED)),e.debounce(0),e.once()).subscribe((e=>{const t=e.to===exports.PlaybackState.PLAYING,s=this.info.muted$.getValue(),i=t?s?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(i)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING)),e.debounce(0)).subscribe((()=>{if(!this.isPlaybackStarted){const e=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(e)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(t){this.subscription.add(t.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition()?.to;e.isNonNullable(t)&&(this.desiredState.seekPosition.setState(t),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(t.providerOutput.seekedEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition();e.isNonNullable(t?.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(t.current$.pipe(e.map((e=>e.type))).subscribe(this.info.currentFormat$)).add(t.current$.pipe(e.map((e=>e.destination)),e.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(t.providerOutput.availableVideoTracks$.pipe(e.map((e=>e.map((({quality:e})=>e)).sort(((e,t)=>O(e)?1:O(t)?-1:R(t,e)?1:-1))))).subscribe(this.info.availableQualities$)).add(t.providerOutput.availableVideoTracks$.subscribe((e=>{const t={};for(const s of e)s.fps&&(t[s.quality]=s.fps);this.info.availableQualitiesFps$.next(t)}))).add(t.providerOutput.currentVideoTrack$.subscribe((e=>{this.info.currentQuality$.next(e?.quality),this.info.videoBitrate$.next(e?.bitrate);const s=t.providerOutput.element$.getValue();s&&this.info.intrinsicVideoSize$.next({width:s.videoWidth,height:s.videoHeight})}))).add(t.providerOutput.hostname$.pipe(e.filterChanged()).subscribe(this.info.hostname$)).add(t.providerOutput.httpConnectionType$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionType$)).add(t.providerOutput.httpConnectionReused$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(t.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(t.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(t.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(t.providerOutput.duration$.subscribe(this.info.duration$)).add(t.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(t.providerOutput.isLive$.subscribe(this.info.isLive$)).add(t.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.muted)),e.filterChanged()).subscribe(this.info.muted$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.volume)),e.filterChanged()).subscribe(this.info.volume$)).add((({seekPosition:t,position$:s})=>e.merge(t.stateChangeStarted$.pipe(e.map((e=>e.to)),e.filter(e.isNonNullable)),s.pipe(e.filter((()=>e.isNullable(t.getState())&&e.isNullable(t.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:t.providerOutput.position$}).subscribe(this.info.position$)).add(e.merge(t.providerOutput.endedEvent$.pipe(e.mapTo(!0)),t.providerOutput.seekedEvent$.pipe(e.mapTo(!1))).pipe(e.filterChanged()).subscribe(this.info.isEnded$)).add(t.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(t.providerError$.subscribe(this.events.managedError$)).add(t.noAvailableProvidersError$.pipe(e.map((e=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(t.providerOutput.element$.subscribe(this.experimental.element$)).add(t.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(t.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const s=new e.ValueSubject(!1);this.subscription.add(t.providerOutput.seekedEvent$.subscribe((()=>s.next(!1)))).add(t.providerOutput.willSeekEvent$.subscribe((()=>s.next(!0))));const i=new e.ValueSubject(!0);this.subscription.add(t.current$.subscribe((()=>i.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((({to:e})=>e===exports.PlaybackState.PLAYING)),e.once()).subscribe((()=>i.next(!1))));let a=0;const r=e.merge(t.providerOutput.isBuffering$,s,i).pipe(e.map((()=>{const e=t.providerOutput.isBuffering$.getValue(),a=s.getValue()||i.getValue();return e&&!a})),e.filterChanged());this.subscription.add(r.subscribe((e=>{e?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new e.Subscription;this.subscription.add(o);const n=e.merge(e.fromEvent(window,'beforeunload'),this.events.willDestruct$,t.current$.pipe(e.filter((e=>Boolean(e?.provider)))));t.providerOutput.isLive$.pipe(e.filterChanged()).subscribe((t=>{switch(e.assertNonNullable(this.providerContainer),o.unsubscribe(),t){case!0:o.add(zt({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(Yt({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(e.map((e=>e?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const s=new e.Subscription;this.subscription.add(s),this.subscription.add(t.current$.pipe(e.filterChanged(((e,t)=>e.provider===t.provider))).subscribe((()=>{s.unsubscribe(),s.add(t.providerOutput.availableVideoTracks$.pipe(e.filter((e=>e.length>0)),e.once()).subscribe((e=>{this.setStartingVideoTrack(e)})))})))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find((({quality:e})=>e===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),t||(t=q(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(e.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'end'}))))).pipe(e.map((e=>({component:'desiredState',message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;e.assertNonNullable(this.providerContainer),e.assertNonNullable(t),M={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{V=e})),this.providerContainer.current$.subscribe((({type:e})=>U('provider',e))),t.duration$.subscribe((e=>U('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>U('tracks',e))),this.events.fatalError$.subscribe(new F('fatalError')),this.events.managedError$.subscribe(new F('managedError')),t.position$.subscribe(new F('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new F('quality')),t.currentBuffer$.subscribe(new F('buffer')),t.isBuffering$.subscribe(new F('isBuffering'))].forEach((e=>this.subscription.add(e))),U('codecs',Object.keys(vt).filter((e=>vt[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.42-beta.0';
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-core",
3
- "version": "2.0.41",
3
+ "version": "2.0.42-beta.0",
4
4
  "author": "vk.com",
5
5
  "description": "Videoplayer core library based on the vk.com platform",
6
6
  "homepage": "https://vk.com",
7
7
  "license": "GPL-3.0",
8
- "main": "index.cjs.js",
9
- "module": "index.esm.js",
8
+ "main": "esnext.cjs.js",
9
+ "module": "esnextesm.js",
10
10
  "types": "index.d.ts",
11
11
  "files": [
12
12
  "index.cjs.js",