@vkontakte/videoplayer-core 2.0.44 → 2.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.44
3
- * Thu, 17 Mar 2022 14:35:49 GMT
4
- * https://st.mycdn.me/static/playersdk/2-0-44/doc/
2
+ * @vkontakte/videoplayer-core v2.0.45
3
+ * Tue, 22 Mar 2022 14:34:17 GMT
4
+ * https://st.mycdn.me/static/playersdk/2-0-45/doc/
5
5
  */
6
- 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var e=require('@vkontakte/videoplayer-shared/esnext.cjs.js');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},$=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 k{_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'}}))),n=s('timeupdate',(()=>t.currentTime)),d=new e.Subject;let u;return n.subscribe((s=>{t.loop&&e.isNonNullable(u)&&e.isNonNullable(s)&&u>=t.duration-.3&&s<=.3&&d.next(u),u=s})),{playing$:s('playing'),pause$:s('pause'),canplay$:s('canplay'),ended$:s('ended'),looped$:d,error$:o,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:n,durationChange$:s('durationchange',(()=>t.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:r,firstBytes$:A(t),firstFrame$:$(t)}};var x,_=(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 D={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:426,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:852,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},R=(e,t)=>D[e].height>D[t].height,I=(e,t)=>D[e].height<D[t].height,C=Object.keys(D).sort(((e,t)=>I(e,t)?-1:1)),L=({width:e,height:t},s=0)=>{const i=Math.min(e,t),a=Math.max(e,t);return C.find((e=>{const t=D[e];return t.width*(1+s)>=a&&t.height*(1+s)>=i}))},O=e=>e===exports.VideoQuality.INVARIANT;let V=!1,B={};const M=e=>{e(B)},F=(e,t)=>{V&&(B.meta=B.meta??{},B.meta[e]=t)};class U{name;constructor(e){this.name=e}next(e){if(!V)return;B.series=B.series??{};const t=B.series[this.name]??[];t.push([Date.now(),e]),B.series[this.name]=t}}const H=new U('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 j=(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)},G=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={};function W(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function J(e,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,'value'in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function K(e,t,s){return t&&J(e.prototype,t),s&&J(e,s),e}function X(e){return(X=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function Z(e,t){return(Z=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function ee(e){if(void 0===e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return e}function te(e,t){return!t||'object'!=typeof t&&'function'!=typeof t?ee(e):t}function se(e){var t=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,i=X(e);if(t){var a=X(this).constructor;s=Reflect.construct(i,arguments,a)}else s=i.apply(this,arguments);return te(this,s)}}function ie(e,t,s){return(ie='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,s){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=X(e)););return e}(e,t);if(i){var a=Object.getOwnPropertyDescriptor(i,t);return a.get?a.get.call(s):a.value}})(e,t,s||e)}Object.defineProperty(Q,'__esModule',{value:!0});var ae=function(){function e(){W(this,e),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return K(e,[{key:'addEventListener',value:function(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}},{key:'removeEventListener',value:function(e,t){if(e in this.listeners)for(var s=this.listeners[e],i=0,a=s.length;i<a;i++)if(s[i].callback===t)return void s.splice(i,1)}},{key:'dispatchEvent',value:function(e){if(e.type in this.listeners){for(var t=this.listeners[e.type].slice(),s=0,i=t.length;s<i;s++){var a=t[s];try{a.callback.call(this,e)}catch(e){Promise.resolve().then((function(){throw e}))}a.options&&a.options.once&&this.removeEventListener(e.type,a.callback)}return!e.defaultPrevented}}}]),e}(),re=function(e){!function(e,t){if('function'!=typeof t&&null!==t)throw new TypeError('Super expression must either be null or a function');e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Z(e,t)}(s,ae);var t=se(s);function s(){var e;return W(this,s),(e=t.call(this)).listeners||ae.call(ee(e)),Object.defineProperty(ee(e),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(ee(e),'onabort',{value:null,writable:!0,configurable:!0}),e}return K(s,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(e){'abort'===e.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,e)),ie(X(s.prototype),'dispatchEvent',this).call(this,e)}}]),s}(),oe=function(){function e(){W(this,e),Object.defineProperty(this,'signal',{value:new re,writable:!0,configurable:!0})}return K(e,[{key:'abort',value:function(){var e;try{e=new Event('abort')}catch(t){'undefined'!=typeof document?document.createEvent?(e=document.createEvent('Event')).initEvent('abort',!1,!1):(e=document.createEventObject()).type='abort':e={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(e)}},{key:'toString',value:function(){return'[object AbortController]'}}]),e}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(oe.prototype[Symbol.toStringTag]='AbortController',re.prototype[Symbol.toStringTag]='AbortSignal');var ne=Q.AbortController=oe;Q.AbortSignal=re;var de,ue=Q.abortableFetch=function(e){'function'==typeof e&&(e={fetch:e});var t,s=e,i=s.fetch,a=s.Request,r=void 0===a?i.Request:a,o=s.AbortController,n=s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,d=void 0!==n&&n;if(!((t={fetch:i,Request:r,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:d}).__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),1):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController))return{fetch:i,Request:u};var u=r;(u&&!u.prototype.hasOwnProperty('signal')||d)&&((u=function(e,t){var s;t&&t.signal&&(s=t.signal,delete t.signal);var i=new r(e,t);return s&&Object.defineProperty(i,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),i}).prototype=r.prototype);var h=i;return{fetch:function(e,t){var s=u&&u.prototype.isPrototypeOf(e)?e.signal:t?t.signal:void 0;if(s){var i;try{i=new DOMException('Aborted','AbortError')}catch(e){(i=new Error('Aborted')).name='AbortError'}if(s.aborted)return Promise.reject(i);var a=new Promise((function(e,t){s.addEventListener('abort',(function(){return t(i)}),{once:!0})}));return t&&t.signal&&delete t.signal,Promise.race([a,h(e,t)])}return h(e,t)},Request:u}},he=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'}(de||(de={}));class ce{throughputEstimator;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new ne;subscription=new e.Subscription;constructor({throughputEstimator:e}={}){this.throughputEstimator=e}onHeadersReceived(e){const{type:t,reused:s}=he(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchManifest(e){const t=await ue(fetch).fetch(e,{signal:this.abortAllController.signal}).catch(le);return t?(this.onHeadersReceived(t.headers),t.text()):null}async fetchRange(t,s,i,{method:a=de.HEADER,onProgress:r,signal:o}={}){let n=t;const d=new Headers;switch(a){case de.HEADER:d.append('Range',`${s}-${i}`);break;case de.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 ne;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 ue(fetch).fetch(n,{headers:d,signal:u}).catch(le);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,le(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:de.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:de.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 le=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e};var pe,me;!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'}(pe||(pe={})),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'}(me||(me={}));const Se={[pe.EBML]:{type:me.Master},[pe.EBMLVersion]:{type:me.UnsignedInteger},[pe.EBMLReadVersion]:{type:me.UnsignedInteger},[pe.EBMLMaxIDLength]:{type:me.UnsignedInteger},[pe.EBMLMaxSizeLength]:{type:me.UnsignedInteger},[pe.DocType]:{type:me.String},[pe.DocTypeVersion]:{type:me.UnsignedInteger},[pe.DocTypeReadVersion]:{type:me.UnsignedInteger},[pe.Void]:{type:me.Binary},[pe.Segment]:{type:me.Master},[pe.SeekHead]:{type:me.Master},[pe.Seek]:{type:me.Master},[pe.SeekID]:{type:me.Binary},[pe.SeekPosition]:{type:me.UnsignedInteger},[pe.Info]:{type:me.Master},[pe.TimestampScale]:{type:me.UnsignedInteger},[pe.Duration]:{type:me.Float},[pe.Tracks]:{type:me.Master},[pe.Chapters]:{type:me.Master},[pe.Cluster]:{type:me.Master},[pe.Attachments]:{type:me.Master},[pe.Tags]:{type:me.Master},[pe.Cues]:{type:me.Master},[pe.CuePoint]:{type:me.Master},[pe.CueTime]:{type:me.UnsignedInteger},[pe.CueTrackPositions]:{type:me.Master},[pe.CueTrack]:{type:me.UnsignedInteger},[pe.CueClusterPosition]:{type:me.UnsignedInteger},[pe.CueRelativePosition]:{type:me.UnsignedInteger},[pe.CueDuration]:{type:me.UnsignedInteger},[pe.CueBlockNumber]:{type:me.UnsignedInteger},[pe.CueCodecState]:{type:me.UnsignedInteger},[pe.CueReference]:{type:me.Master},[pe.CueRefTime]:{type:me.UnsignedInteger}},be=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=fe(e,s),a=i in Se,r=a?Se[i].type:me.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))+fe(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}},fe=(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},ge=(t,s)=>{switch(s){case me.SignedInteger:return t.getInt8(0);case me.UnsignedInteger:return fe(t);case me.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case me.String:return new TextDecoder('ascii').decode(t);case me.UTF8:return new TextDecoder('utf-8').decode(t);case me.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case me.Master:case me.Binary:return t;default:e.assertNever(s)}},ve=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=be(i);if(!t(a))return;a.type===me.Master&&ve(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},ye=[pe.Info,pe.SeekHead,pe.Tracks,pe.Chapters,pe.Cluster,pe.Cues,pe.Attachments,pe.Tags],Te={validateData:e=>{if(e.getUint32(0)!==pe.EBML)return!1;let t,s,i;const a=be(e);return ve(a.value,(({tag:e,type:a,value:r})=>(e===pe.EBMLReadVersion?t=ge(r,a):e===pe.DocType?s=ge(r,a):e===pe.DocTypeReadVersion&&(i=ge(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 ve(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===pe.SeekID){const e=ge(c,t);n=fe(e)}else e!==pe.SeekPosition&&(n=void 0);return e===pe.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===pe.Info?d=!0:e===pe.SeekHead?u=!0:e===pe.TimestampScale?a=ge(c,t):e===pe.Duration?r=ge(c,t):e===pe.SeekPosition&&n===pe.Cues?o=ge(c,t):d&&u&&ye.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 ve(t,(({tag:e,type:t,value:s})=>{switch(e){case pe.Cues:i=!0;break;case pe.CuePoint:n&&r(n)&&o.push(n),n={};break;case pe.CueTime:n&&(n.time=ge(s,t));break;case pe.CueTrackPositions:break;case pe.CueClusterPosition:n&&(n.position=ge(s,t));break;default:i&&ye.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}}}))}},Ee=new TextDecoder('ascii'),Pe={validateData:e=>'ftyp'===Ee.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=Ee.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 $e{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 ne;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=Pe;break;case b.WEBM:this.containerParser=Te;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 ne,this.abortBuffer(),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=j(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&&j(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.abortBuffer(),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:de.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.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return await $e.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 $e.waitForBufferUpdate(this.sourceBuffer),!0}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(e){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:e})}}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 ke=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)},we=['timeupdate','progress','play','seeked','stalled'];var Ae,Ne;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(Ae||(Ae={}));class xe{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new z(Ae.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 ce({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(Ae.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?ke(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],$=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[k,w]=$.split('-').map((e=>parseInt(e,10))),A={from:k,to:w},N=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[x,_]=N?N.split('-').map((e=>parseInt(e,10))):[],D=N?{from:x,to:_}: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:D,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(Ae.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(Ae.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 $e(p.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new $e(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(Ae.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...we.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(Ae.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'}(Ne||(Ne={}));const _e=({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}},De=(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 Re{subscription=new e.Subscription;videoState=new z(Ne.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(G(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new xe({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.looped$,t.loopedEvent$),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(Ne.PLAYING),_(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(Ne.PAUSED),_(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Ne.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===Ae.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Ne.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===Ae.NONE||!this.videoTracks.length)return;const a=t===Ae.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=j(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=De(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=De(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),e);this.player.switchRepresentation(p.VIDEO,e.id),t&&this.player.switchRepresentation(p.AUDIO,t.id)}}}),a)),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$,a)),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=_e(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!==Ne.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(r),s!==exports.PlaybackState.STOPPED){if(t===Ne.STOPPED)return this.videoState.startTransitionTo(Ne.READY),void this.prepare();switch(t){case Ne.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ne.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()));case Ne.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ne.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ne.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==Ne.STOPPED&&(this.videoState.startTransitionTo(Ne.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(Ne.STOPPED),_(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(Ne.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Ie;!function(e){e[e.OFFSET_P=0]='OFFSET_P',e[e.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Ie||(Ie={}));var Ce=(t,s=0,i=Ie.OFFSET_P)=>{switch(i){case Ie.OFFSET_P:return t.replace('_offset_p',0===s?'':'_'+s.toFixed(0));case Ie.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 Le;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Le||(Le={}));class Oe{subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new z(Le.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(),_(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(Le.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Le.PLAYING),_(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!==Le.PAUSED&&e!==Le.PLAYING||(this.videoState.setState(Le.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==Le.PLAYING&&e!==Le.PAUSED||(this.videoState.setState(Le.PLAYING),_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===Le.READY&&this.videoState.setState(Le.READY)}handleRemoteStop(){this.videoState.getState()!==Le.STOPPED&&this.videoState.setState(Le.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=Ce(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!==Le.STOPPED&&(this.videoState.startTransitionTo(Le.STOPPED),this.stop()));if(s)return;const o=r?.to;if(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==Le.STOPPED)this.seek(o);else switch(i){case exports.PlaybackState.PLAYING:switch(t){case Le.PLAYING:break;case Le.PAUSED:case Le.READY:this.videoState.startTransitionTo(Le.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Le.STOPPED:this.videoState.startTransitionTo(Le.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case Le.PLAYING:this.videoState.startTransitionTo(Le.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Le.PAUSED:break;case Le.READY:this.videoState.startTransitionTo(Le.PAUSED),this.videoState.setState(Le.PAUSED);break;case Le.STOPPED:this.videoState.startTransitionTo(Le.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}}}var Ve;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Ve||(Ve={}));class Be{subscription=new e.Subscription;videoState=new z(Ve.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.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,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(Ve.PLAYING),_(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ve.PAUSED),_(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ve.READY&&this.videoState.setState(Ve.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()===Ve.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(G(s))}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(Ve.PAUSED),_(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!==Ve.STOPPED&&(this.videoState.startTransitionTo(Ve.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ve.STOPPED),_(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===Ve.STOPPED)return this.videoState.startTransitionTo(Ve.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 Ve.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ve.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ve.PLAYING),this.playIfAllowed()));case Ve.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ve.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ve.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ve.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class Me{_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 Fe{_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(Fe._str2ua(e.substr(n))),n=e.length};this._lastXhr=new Me(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=Fe._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 Ue{_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 Me(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?ke(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 Fe({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 He;!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'}(He||(He={}));const qe=[He.PAUSED,He.PLAYING];class je{videoState=new z(He.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(G(this.params.source.url)),this.buffer=new k(this.video),this.dash=new Ue({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.looped$,t.loopedEvent$),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()===He.PLAYING||this.videoState.getState()===He.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===He.READY&&this.videoState.setState(He.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(He.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(He.PLAYING),_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(He.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=j(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===He.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(He.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=j(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(G(e.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((e=>{const{type:t,reused:s}=he(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(He.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(He.PAUSED),_(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!==He.STOPPED&&(this.videoState.startTransitionTo(He.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(He.STOPPED),_(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(s)return;const o=r?.to;switch(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&qe.includes(t)&&this.seek(o),t){case He.STOPPED:return this.videoState.startTransitionTo(He.MANIFEST_LOADED),void this.prepare();case He.MANIFEST_LOADED:return void this.videoState.startTransitionTo(He.INITIAL_REPRESENTATION_SELECTED);case He.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(He.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case He.METADATA_LOADED:return this.videoState.startTransitionTo(He.READY),void this.dash.seek(o??0);case He.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(He.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(He.PLAYING),this.playIfAllowed()));case He.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(He.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case He.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(He.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}var Ge=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)},Ye=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 ze=e=>e.range?e.range.split('-').map((e=>parseInt(e,10))):[NaN,NaN];class Qe{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]=ze(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(ze),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 ne,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 ue(fetch).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,Qe.suppressStreamErrors).catch(h)))};i?.read().then(o,Qe.suppressStreamErrors).catch(h)}),Qe.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]=ze(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]=ze(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]=ze(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 We{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(We.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;We.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Je=(e,t)=>{const s=new Qe(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 We(a,t,i)}}))(t(e),s)}}),!0),()=>s.destroy()};var Ke=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 Xe{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 Ze={};var et;!function(e){e.DOWNLOADING_LIB='downloading_lib',e.STOPPED='stopped',e.STREAM_INITIALIZED='stream_initialized',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(et||(et={}));const tt=(t,s)=>new e.Observable((e=>{const i=t=>e.next(t);return t.on(s,i),()=>t.off(s,i)}));class st{subscription=new e.Subscription;videoState=new z(et.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 Xe;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(G(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||(Ze.MediaPlayer=t.MediaPlayer,Ze.Debug=t.Debug,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(Ze.MediaPlayer,'dashjs not loaded'),e.assertNonNullable(Ze.Debug,'dashjs not loaded'),this.player=Ze.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?ke(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=Je(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&&Ye(this.player),Ge(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(et.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(tt(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(tt(this.player,'playbackError').pipe(e.map((e=>({id:'DashJSPlayback',message:e.error})))),t.error$);const r=tt(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===et.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(tt(this.player,'bufferStateChanged').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({state:e})=>'bufferStalled'===e))),t.isBuffering$),a(tt(this.player,'fragmentLoadingStarted').pipe(e.map((e=>G(e.request.url)))),t.hostname$),a(tt(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(et.STREAM_INITIALIZED),this.videoState.startTransitionTo(et.READY)})),a(tt(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})=>it(e)))),this.params.output.duration$);const o=tt(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(tt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(tt(this.player,'playbackEnded'),t.endedEvent$),a(tt(this.player,'playbackProgress').pipe(e.map((()=>w(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(tt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(et.PLAYING),_(s.playbackState,exports.PlaybackState.PLAYING)})),a(tt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(et.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(tt(this.player,'playbackPaused'),(()=>{this.videoState.setState(et.PAUSED),_(s.playbackState,exports.PlaybackState.PAUSED)})),a(tt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===et.READY&&this.videoState.setState(et.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}=Ke(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(tt(this.player,'manifestLoaded').pipe(e.once()).subscribe((()=>{const s=Date.now();this.subscription.add(tt(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,looped$:h}=N(this.video);this.subscription.add(y(this.video,s.volume,u,i)),this.subscription.add(u.subscribe(t.volume$,i)),this.subscription.add(h.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(et.STOPPED),_(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(et.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(it(s));const i=Ce(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ie.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e)}play(){this.videoState.startTransitionTo(et.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(et.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===et.DOWNLOADING_LIB||t===et.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==et.STOPPED&&s!==exports.PlaybackState.STOPPED&&(r?this.seek(o+it(this.liveOffset.getTotalPausedTime())):this.seek(o)),s){case exports.PlaybackState.STOPPED:switch(t){case et.STOPPED:break;case et.PLAYING:case et.PAUSED:case et.READY:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case et.PLAYING:break;case et.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(it(this.liveOffset.getTotalOffset()))):this.seek(it(this.liveOffset.getTotalOffset()))),this.play();break;case et.READY:this.play();break;case et.STOPPED:this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case et.PLAYING:this.pause(),this.liveOffset.pause();break;case et.PAUSED:break;case et.READY:this.videoState.setState(et.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case et.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 it=e=>-e/1e3;function at(){return e.now()}function rt(e){return at()-e}function ot(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 nt(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=rt(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=at(),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=at();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=at(),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 dt{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 ut{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=at(),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=nt(t,(i=>{e._complete=1,e._responseData=i,e._downloadTime=at()-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=at()}_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=at();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 ht{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 dt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ot(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=ot(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 ut(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=nt(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=at()-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=nt(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=at(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=at(),$(),P())}))};i>0?S=window.setTimeout((()=>{this.paused?P():a()}),i):a()},$=()=>{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()},k=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&k(e,t)}),s)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const d=at(),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)]),k(d,(function(){d=null,$()})))},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)))},_=e=>{c()&&(t.cachedHeader=e,k(e,(()=>{n=!0,w()})))};r=!0,T.seek((t=>{c()&&(E=at(),t?(m=t,!e.isNullable(s)||t.startTS>s?N(t):(h=t,$())):P())}),s),t.cachedHeader?_(t.cachedHeader):l(t.headerUrl,_,(()=>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=at();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&&rt(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=at();e<a&&(r=t),a=e}}}_fetchManifest(e,t,s){this.manifestRequest=nt(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 ct;!function(e){e.STOPPED='stopped',e.MANIFEST_READY='manifest_ready',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ct||(ct={}));const lt=[ct.PAUSED,ct.PLAYING,ct.READY],pt=[ct.PAUSED,ct.PLAYING,ct.READY];class mt{subscription=new e.Subscription;video;videoState=new z(ct.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new E;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new Xe;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(G(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===ct.READY&&this.videoState.setState(ct.READY)}),s)).add(i.pause$.subscribe((()=>{this.videoState.setState(ct.PAUSED)}),s)).add(i.playing$.subscribe((()=>{this.videoState.setState(ct.PLAYING)}),s)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map(St)).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($(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case ct.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case ct.MANIFEST_READY:case ct.READY:break;case ct.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case ct.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 ht({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(St(s)),this.dash.reinit(Ce(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===ct.MANIFEST_READY&&this.videoState.setState(ct.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!==ct.STOPPED&&(this.videoState.startTransitionTo(ct.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(ct.STOPPED)));if(s)return;if(pt.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)&&lt.includes(t))this.seek(o+St(this.liveOffset.getTotalPausedTime()));else switch(t){case ct.STOPPED:return this.videoState.startTransitionTo(ct.MANIFEST_READY),void this.dash.attachSource(Ce(this.params.source.url));case ct.MANIFEST_READY:this.videoState.startTransitionTo(ct.READY),this.prepare();break;case ct.READY:return void(i===exports.PlaybackState.PAUSED?this.videoState.setState(ct.PAUSED):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ct.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(ct.PAUSED)}))));case ct.PLAYING:return void(i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(ct.PAUSED),this.liveOffset.pause(),this.dash.pause()));case ct.PAUSED:return void(i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ct.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(ct.PAUSED)})),this.params.output.position$.next(St(this.liveOffset.getTotalOffset()))):this.seek(St(this.liveOffset.getTotalOffset()))));default:return e.assertNever(t)}}}const St=e=>-e/1e3;var bt=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 ft=e=>{let t=null;if(e.QUALITY&&(t=bt(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},gt=async(e,t=e)=>{const s=await ue(fetch).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=ft(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 vt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(vt||(vt={}));class yt{subscription=new e.Subscription;videoState=new z(vt.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(G(this.params.source.url)),gt(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.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,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(vt.PLAYING),_(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(vt.PAUSED),_(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===vt.READY&&this.videoState.setState(vt.READY),this.videoState.getState()===vt.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(G(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===vt.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(vt.PAUSED),_(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!==vt.STOPPED&&(this.videoState.startTransitionTo(vt.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(vt.STOPPED),_(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===vt.STOPPED)return this.videoState.startTransitionTo(vt.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(vt.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 vt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(vt.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()));case vt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(vt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case vt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case vt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}var Tt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(Tt||(Tt={}));class Et{subscription=new e.Subscription;videoState=new z(Tt.STOPPED);video;params;textTracksManager=new E;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new Xe;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]),gt(Ce(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(G(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(Tt.PLAYING),_(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Tt.PAUSED),_(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Tt.READY&&this.videoState.setState(Tt.READY),this.videoState.getState()===Tt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map(Pt)).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(G(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===Tt.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=Ce(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',s),this.video.load(),(async e=>{const t=await ue(fetch).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(Tt.PAUSED),this.liveOffset.pause(),_(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(Pt(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!==Tt.STOPPED&&(this.videoState.startTransitionTo(Tt.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(Tt.STOPPED),_(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===Tt.STOPPED)return this.videoState.startTransitionTo(Tt.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Tt.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const s=Pt(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(Tt.READY),this.seek(n+Pt(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case Tt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Tt.PAUSED),this.liveOffset.pause(),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tt.PLAYING),this.playIfAllowed()));case Tt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Tt.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&_(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Tt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Tt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Pt(this.liveOffset.getTotalOffset()))):this.seek(Pt(this.liveOffset.getTotalOffset()))):i?.to===exports.PlaybackState.PAUSED&&(_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Tt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}const Pt=e=>-e/1e3,$t={};var kt;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(kt||(kt={}));const wt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class At{subscription=new e.Subscription;videoState=new z(kt.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(G(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||($t.Hls=t.default,$t.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable($t.Hls,'hls.js not loaded'),this.hls=new $t.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(kt.STOPPED)}subscribe(){e.assertNonNullable($t.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.looped$,s.loopedEvent$),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(wt(this.hls,$t.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(kt.PLAYING),_(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(kt.PAUSED),_(t.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===kt.READY&&this.videoState.setState(kt.READY),this.videoState.getState()===kt.PLAYING&&this.playIfAllowed()}),i)),r(wt(this.hls,$t.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=bt(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(wt(this.hls,$t.Events.LEVEL_LOADING).pipe(e.map((({url:e})=>G(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=wt(this.hls,$t.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===kt.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 kt.STOPPED:break;case kt.READY:case kt.PLAYING:case kt.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case kt.PLAYING:break;case kt.STOPPED:this.prepare();break;case kt.READY:case kt.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case kt.PAUSED:break;case kt.STOPPED:this.prepare();break;case kt.READY:this.videoState.setState(kt.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case kt.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(kt.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(kt.PLAYING);await f(this.video)||(this.videoState.setState(kt.PAUSED),_(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(kt.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(kt.STOPPED),_(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class Nt{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 xt=(()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)})(),_t=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Dt=document.createElement('video'),Rt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Dt.canPlayType?.('application/x-mpegurl')||Dt.canPlayType?.('vnd.apple.mpegURL'))},It={mp4:Boolean(Dt.canPlayType?.('video/mp4')),webm:Boolean(Dt.canPlayType?.('video/webm'))},Ct={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"'))},Lt=(Ct.h264||Ct.h265)&&Ct.aac,Ot=!xt,Vt=_t||xt,Bt=!Rt.hls||!Vt,Mt=3e4,Ft=18e4,Ut=3,Ht=100,qt={cacheDuration:12e4},jt={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Gt={maxPausedTime:3e4},Yt={maxPausedTime:3e4};class zt{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,loopedEvent$: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 Nt(i.filter((s=>e.isNonNullable(t.sources[s]))).filter((t=>{switch(t){case exports.VideoFormat.DASH:return Rt.mse&&It.mp4&&Lt&&Ot;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return Rt.mse&&It.mp4&&Lt;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return Rt.mse&&It.webm&&Ct.vp9&&Ct.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return Rt.mse&&It.mp4&&Lt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return Rt.hls&&It.mp4&&Vt;case exports.VideoFormat.HLS_JS:return Rt.mse&&It.mp4&&Lt&&Bt;case exports.VideoFormat.MPEG:return It.mp4;default:return e.assertNever(t)}}))),this.chromecastFormatsIterator=new Nt(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);let i;try{i=this.createProvider(t,s)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:e})}i?this.current$.next({type:s,provider:i,destination:t}):this.switchToNextProvider()}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 je({container:i,source:o,desiredState:a,output:r,config:qt,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 Re({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 st({container:i,source:o,desiredState:a,output:r,format:t,config:Yt,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 yt({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 Et({container:i,source:o,desiredState:a,output:r,config:Gt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=s[t];return e.assertNonNullable(o),new At({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 Be({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 mt({container:i,source:o,desiredState:a,output:r,config:jt,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 Oe({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:Mt,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(Ht,{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]+Ft?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%Ut}))),i}}const Qt=(e,t,s)=>s*t+(1-s)*e;class Wt{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 U(`raw_${s}`),this.smoothedSeries$=new U(`smoothed_${s}`),this.reportedSeries$=new U(`reported_${s}`)}next(t){this.slow=Qt(this.slow,t,this.params.emaAlphaSlow),this.fast=Qt(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 Jt;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(Jt||(Jt={}));const Kt=new Map;let Xt=Jt.RUNTIME;const Zt=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Zt,'test'),localStorage.removeItem(Zt),Xt=Jt.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;try{sessionStorage.getItem(Zt),Xt=Jt.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;Xt=Jt.RUNTIME}}})();const es=(t,s)=>{switch(Xt){case Jt.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Jt.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Jt.RUNTIME:return void Kt.set(t,s);default:e.assertNever(Xt)}},ts=window.navigator.connection,ss=()=>{const t=ts?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},is=()=>{const t=ts?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},as=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class rs{throughput;rtt;subscription=new e.Subscription;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=rs.load('one_video_throughput')||(t.useBrowserEstimation?ss():void 0)||5e3,i=rs.load('one_video_rtt')??(t.useBrowserEstimation?is():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(as(s,i,t.rttPenaltyRequestSize)),this.throughput=new Wt({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new Wt({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=ss();t&&this.throughput.next(t);const s=is();e.isNonNullable(s)&&this.rtt.next(s)};ts&&'onchange'in ts&&this.subscription.add(e.fromEvent(ts,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{es('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{es('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})=>as(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(rs.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(Xt){case Jt.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Jt.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Jt.RUNTIME:return Kt.get(t);default:e.assertNever(Xt)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const os=(t=(e=>e))=>({playbackState:s,seekPosition:i,playbackAbort$:a,looped$:r,position$:o})=>new e.Observable((n=>{let d;const u=s.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),h=s.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),c=i.stateChangeEnded$.pipe(e.filter((t=>e.isNonNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),l=i.stateChangeEnded$.pipe(e.filter((t=>e.isNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),p=e.merge(u,l).pipe(e.map((()=>t(o.getValue())))),m=e.merge(e.merge(h,c,a).pipe(e.map((()=>t(o.getValue())))),r.pipe(e.map(t)));return(new e.Subscription).add(p.subscribe((e=>{d=t(e)}))).add(m.subscribe((s=>{const i=t(s);if(e.isNullable(d)||d===i)return;const a={start:d,end:i};d=void 0,n.next(a)})))})),ns=os((e=>e)),ds=os((e=>Math.round(1e3*e)+Date.now())),us={[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,looped$: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:M};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 rs(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 zt({screenFormatsPriority:[...us[o.SCREEN].live,...us[o.SCREEN].vod],chromecastFormatsPriority:[...us[o.CHROMECAST].live,...us[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.providerOutput.loopedEvent$.subscribe(this.events.looped$)).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(ds({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(ns({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(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),B={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{V=e})),this.providerContainer.current$.subscribe((({type:e})=>F('provider',e))),t.duration$.subscribe((e=>F('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>F('tracks',e))),this.events.fatalError$.subscribe(new U('fatalError')),this.events.managedError$.subscribe(new U('managedError')),t.position$.subscribe(new U('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new U('quality')),t.currentBuffer$.subscribe(new U('buffer')),t.isBuffering$.subscribe(new U('isBuffering'))].forEach((e=>this.subscription.add(e))),F('codecs',Object.keys(Ct).filter((e=>Ct[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.44';
6
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var e=require('@vkontakte/videoplayer-shared/esnext.cjs.js');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'}}))),n=s('timeupdate',(()=>t.currentTime)),d=new e.Subject;let u;return n.subscribe((s=>{t.loop&&e.isNonNullable(u)&&e.isNonNullable(s)&&u>=t.duration-.3&&s<=.3&&d.next(u),u=s})),{playing$:s('playing'),pause$:s('pause'),canplay$:s('canplay'),ended$:s('ended'),looped$:d,error$:o,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:n,durationChange$:s('durationchange',(()=>t.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:r,firstBytes$:A(t),firstFrame$:k(t)}};var x;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';var _=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}},D=(e,t,s=!1)=>{const i=e.getTransition();!s&&i&&i.to!==t||e.setState(t)};const R={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:854,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},I=(e,t)=>R[e].height>R[t].height,C=(e,t)=>R[e].height>=R[t].height,L=(e,t)=>R[e].height<R[t].height,O=(e,t)=>R[e].height<=R[t].height,V=Object.keys(R).sort(((e,t)=>L(e,t)?-1:1)),M=({width:e,height:t})=>{const s=Math.min(e,t),i=Math.max(e,t);return V.find((e=>{const t=R[e];return t.width>=i&&t.height>=s}))},B=e=>e===exports.VideoQuality.INVARIANT;let F=!1,U={};const H=e=>{e(U)},q=(e,t)=>{F&&(U.meta=U.meta??{},U.meta[e]=t)};class j{name;constructor(e){this.name=e}next(e){if(!F)return;U.series=U.series??{};const t=U.series[this.name]??[];t.push([Date.now(),e]),U.series[this.name]=t}}const G=new j('best_bitrate'),Y=(t,{container:s,throughput:i,tuning:a,limits:r,forwardBufferHealth:o,currentRepresentation:n})=>{const d=a.usePixelRatio?window.devicePixelRatio??1:1,u=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*d*a.containerSizeFactor,height:s.height*d*a.containerSizeFactor},h=u&&M(u),c=t.filter((e=>!B(e.quality))).sort(((e,t)=>I(e.quality,t.quality)?-1:1)),l=c.at(-1)?.quality,p=c.at(0)?.quality,m=e.isNullable(r)||e.isNonNullable(r.min)&&e.isNonNullable(r.max)&&L(r.max,r.min)||e.isNonNullable(r.min)&&p&&I(r.min,p)||e.isNonNullable(r.max)&&l&&L(r.max,l),S=c.filter((t=>{const s=!h||L(t.quality,h),d=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i>=t.bitrate*(u=o??.5,c=a.bitrateFactorAtEmptyBuffer,l=a.bitrateFactorAtFullBuffer,(c-l)*Math.pow(2,-10*u)+l);var u,c,l;const p=!a.lazyQualitySwitch||!n||(o??.5)>=.5||(t.size?.height||0)<=(n?.height||0),S=m||(e.isNullable(r.max)||O(t.quality,r.max))&&(e.isNullable(r.min)||C(t.quality,r.min));return s&&d&&p&&S}))[0];return S&&S.bitrate&&G.next(S.bitrate),S??c[Math.ceil((c.length-1)/2)]??t[0]};var Q=(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)},z=e=>new URL(e).hostname;const W=(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 J{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 K={};function X(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function Z(e,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,'value'in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function ee(e,t,s){return t&&Z(e.prototype,t),s&&Z(e,s),e}function te(e){return(te=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function se(e,t){return(se=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function ie(e){if(void 0===e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return e}function ae(e,t){return!t||'object'!=typeof t&&'function'!=typeof t?ie(e):t}function re(e){var t=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,i=te(e);if(t){var a=te(this).constructor;s=Reflect.construct(i,arguments,a)}else s=i.apply(this,arguments);return ae(this,s)}}function oe(e,t,s){return(oe='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,s){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=te(e)););return e}(e,t);if(i){var a=Object.getOwnPropertyDescriptor(i,t);return a.get?a.get.call(s):a.value}})(e,t,s||e)}Object.defineProperty(K,'__esModule',{value:!0});var ne=function(){function e(){X(this,e),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return ee(e,[{key:'addEventListener',value:function(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}},{key:'removeEventListener',value:function(e,t){if(e in this.listeners)for(var s=this.listeners[e],i=0,a=s.length;i<a;i++)if(s[i].callback===t)return void s.splice(i,1)}},{key:'dispatchEvent',value:function(e){if(e.type in this.listeners){for(var t=this.listeners[e.type].slice(),s=0,i=t.length;s<i;s++){var a=t[s];try{a.callback.call(this,e)}catch(e){Promise.resolve().then((function(){throw e}))}a.options&&a.options.once&&this.removeEventListener(e.type,a.callback)}return!e.defaultPrevented}}}]),e}(),de=function(e){!function(e,t){if('function'!=typeof t&&null!==t)throw new TypeError('Super expression must either be null or a function');e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&se(e,t)}(s,ne);var t=re(s);function s(){var e;return X(this,s),(e=t.call(this)).listeners||ne.call(ie(e)),Object.defineProperty(ie(e),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(ie(e),'onabort',{value:null,writable:!0,configurable:!0}),e}return ee(s,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(e){'abort'===e.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,e)),oe(te(s.prototype),'dispatchEvent',this).call(this,e)}}]),s}(),ue=function(){function e(){X(this,e),Object.defineProperty(this,'signal',{value:new de,writable:!0,configurable:!0})}return ee(e,[{key:'abort',value:function(){var e;try{e=new Event('abort')}catch(t){'undefined'!=typeof document?document.createEvent?(e=document.createEvent('Event')).initEvent('abort',!1,!1):(e=document.createEventObject()).type='abort':e={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(e)}},{key:'toString',value:function(){return'[object AbortController]'}}]),e}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(ue.prototype[Symbol.toStringTag]='AbortController',de.prototype[Symbol.toStringTag]='AbortSignal');var he=K.AbortController=ue;K.AbortSignal=de;var ce,le=K.abortableFetch=function(e){'function'==typeof e&&(e={fetch:e});var t,s=e,i=s.fetch,a=s.Request,r=void 0===a?i.Request:a,o=s.AbortController,n=s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,d=void 0!==n&&n;if(!((t={fetch:i,Request:r,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:d}).__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),1):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController))return{fetch:i,Request:u};var u=r;(u&&!u.prototype.hasOwnProperty('signal')||d)&&((u=function(e,t){var s;t&&t.signal&&(s=t.signal,delete t.signal);var i=new r(e,t);return s&&Object.defineProperty(i,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),i}).prototype=r.prototype);var h=i;return{fetch:function(e,t){var s=u&&u.prototype.isPrototypeOf(e)?e.signal:t?t.signal:void 0;if(s){var i;try{i=new DOMException('Aborted','AbortError')}catch(e){(i=new Error('Aborted')).name='AbortError'}if(s.aborted)return Promise.reject(i);var a=new Promise((function(e,t){s.addEventListener('abort',(function(){return t(i)}),{once:!0})}));return t&&t.signal&&delete t.signal,Promise.race([a,h(e,t)])}return h(e,t)},Request:u}},pe=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'}(ce||(ce={}));class me{throughputEstimator;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new he;subscription=new e.Subscription;constructor({throughputEstimator:e}={}){this.throughputEstimator=e}onHeadersReceived(e){const{type:t,reused:s}=pe(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchManifest(e){const t=await le(fetch).fetch(e,{signal:this.abortAllController.signal}).catch(Se);return t?(this.onHeadersReceived(t.headers),t.text()):null}async fetchRange(t,s,i,{method:a=ce.HEADER,onProgress:r,signal:o}={}){let n=t;const d=new Headers;switch(a){case ce.HEADER:d.append('Range',`${s}-${i}`);break;case ce.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 he;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 le(fetch).fetch(n,{headers:d,signal:u}).catch(Se);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,Se(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:ce.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:ce.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 Se=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e};var be,fe;!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'}(be||(be={})),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'}(fe||(fe={}));const ge={[be.EBML]:{type:fe.Master},[be.EBMLVersion]:{type:fe.UnsignedInteger},[be.EBMLReadVersion]:{type:fe.UnsignedInteger},[be.EBMLMaxIDLength]:{type:fe.UnsignedInteger},[be.EBMLMaxSizeLength]:{type:fe.UnsignedInteger},[be.DocType]:{type:fe.String},[be.DocTypeVersion]:{type:fe.UnsignedInteger},[be.DocTypeReadVersion]:{type:fe.UnsignedInteger},[be.Void]:{type:fe.Binary},[be.Segment]:{type:fe.Master},[be.SeekHead]:{type:fe.Master},[be.Seek]:{type:fe.Master},[be.SeekID]:{type:fe.Binary},[be.SeekPosition]:{type:fe.UnsignedInteger},[be.Info]:{type:fe.Master},[be.TimestampScale]:{type:fe.UnsignedInteger},[be.Duration]:{type:fe.Float},[be.Tracks]:{type:fe.Master},[be.Chapters]:{type:fe.Master},[be.Cluster]:{type:fe.Master},[be.Attachments]:{type:fe.Master},[be.Tags]:{type:fe.Master},[be.Cues]:{type:fe.Master},[be.CuePoint]:{type:fe.Master},[be.CueTime]:{type:fe.UnsignedInteger},[be.CueTrackPositions]:{type:fe.Master},[be.CueTrack]:{type:fe.UnsignedInteger},[be.CueClusterPosition]:{type:fe.UnsignedInteger},[be.CueRelativePosition]:{type:fe.UnsignedInteger},[be.CueDuration]:{type:fe.UnsignedInteger},[be.CueBlockNumber]:{type:fe.UnsignedInteger},[be.CueCodecState]:{type:fe.UnsignedInteger},[be.CueReference]:{type:fe.Master},[be.CueRefTime]:{type:fe.UnsignedInteger}},ve=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=ye(e,s),a=i in ge,r=a?ge[i].type:fe.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))+ye(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}},ye=(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},Te=(t,s)=>{switch(s){case fe.SignedInteger:return t.getInt8(0);case fe.UnsignedInteger:return ye(t);case fe.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case fe.String:return new TextDecoder('ascii').decode(t);case fe.UTF8:return new TextDecoder('utf-8').decode(t);case fe.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case fe.Master:case fe.Binary:return t;default:e.assertNever(s)}},Ee=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=ve(i);if(!t(a))return;a.type===fe.Master&&Ee(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},Pe=[be.Info,be.SeekHead,be.Tracks,be.Chapters,be.Cluster,be.Cues,be.Attachments,be.Tags],ke={validateData:e=>{if(e.getUint32(0)!==be.EBML)return!1;let t,s,i;const a=ve(e);return Ee(a.value,(({tag:e,type:a,value:r})=>(e===be.EBMLReadVersion?t=Te(r,a):e===be.DocType?s=Te(r,a):e===be.DocTypeReadVersion&&(i=Te(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 Ee(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===be.SeekID){const e=Te(c,t);n=ye(e)}else e!==be.SeekPosition&&(n=void 0);return e===be.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===be.Info?d=!0:e===be.SeekHead?u=!0:e===be.TimestampScale?a=Te(c,t):e===be.Duration?r=Te(c,t):e===be.SeekPosition&&n===be.Cues?o=Te(c,t):d&&u&&Pe.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 Ee(t,(({tag:e,type:t,value:s})=>{switch(e){case be.Cues:i=!0;break;case be.CuePoint:n&&r(n)&&o.push(n),n={};break;case be.CueTime:n&&(n.time=Te(s,t));break;case be.CueTrackPositions:break;case be.CueClusterPosition:n&&(n.position=Te(s,t));break;default:i&&Pe.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}}}))}},$e=new TextDecoder('ascii'),we={validateData:e=>'ftyp'===$e.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=$e.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 Ae{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 he;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=we;break;case b.WEBM:this.containerParser=ke;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 he,this.abortBuffer(),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=Q(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&&Q(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.abortBuffer(),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:ce.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.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return await Ae.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 Ae.waitForBufferUpdate(this.sourceBuffer),!0}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(e){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:e})}}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 Ne=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)},xe=['timeupdate','progress','play','seeked','stalled'];var _e,De;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(_e||(_e={}));class Re{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new J(_e.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 me({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(_e.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=h.getAttribute('quality')??void 0,y=g?Ne(g):void 0,T=`${h.getAttribute('id')??(r++).toString(10)}@${'video'===l?`${b}p`:'audio'===l?`${f}Kbps`:c}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',P=new URL(E,t).toString(),k=[...o,...d,...m],$=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[w,A]=$.split('-').map((e=>parseInt(e,10))),N={from:w,to:A},x=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[_,D]=x?x.split('-').map((e=>parseInt(e,10))):[],R=x?{from:_,to:D}:void 0;if(!l||!u)continue;const I={video:p.VIDEO,audio:p.AUDIO,text:p.TEXT}[l];I&&s[I].push({id:T,kind:I,profiles:k,initRange:N,indexRange:R,bitrate:f,mime:u,codecs:c,width:S,height:b,fps:y,quality:v,url:P})}}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(_e.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(_e.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 Ae(p.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new Ae(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(_e.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...xe.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(_e.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'}(De||(De={}));const Ie=({id:e,width:t,height:s,bitrate:i,fps:a,quality:r})=>{const o=(r?_(r):void 0)??M({width:t,height:s});return o&&{id:e,quality:o,bitrate:i,size:{width:t,height:s},fps:a}},Ce=(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 Le{subscription=new e.Subscription;videoState=new J(De.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(z(this.params.source.url)),this.params.output.isLive$.next(!1),this.player=new Re({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.looped$,t.loopedEvent$),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(W(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(De.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(De.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===De.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===_e.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(De.READY)}))),this.subscription.add(e.merge(this.player.state$.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,s.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,e.fromEvent(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),i=this.player.state$.getTransition();if(t===_e.NONE||!this.videoTracks.length)return;const a=t===_e.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=Q(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=Y(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState(),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=Ce(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=Ce(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),e);this.player.switchRepresentation(p.VIDEO,e.id),t&&this.player.switchRepresentation(p.AUDIO,t.id)}}}),a)),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$,a)),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=Ie(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!==De.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(r),s!==exports.PlaybackState.STOPPED){if(t===De.STOPPED)return this.videoState.startTransitionTo(De.READY),void this.prepare();switch(t){case De.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(De.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(De.PLAYING),this.playIfAllowed()));case De.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(De.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case De.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(De.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==De.STOPPED&&(this.videoState.startTransitionTo(De.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(De.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(De.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Oe;!function(e){e[e.OFFSET_P=0]='OFFSET_P',e[e.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Oe||(Oe={}));var Ve=(t,s=0,i=Oe.OFFSET_P)=>{switch(i){case Oe.OFFSET_P:return t.replace('_offset_p',0===s?'':'_'+s.toFixed(0));case Oe.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 Me;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Me||(Me={}));class Be{subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new J(Me.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(Me.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Me.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!==Me.PAUSED&&e!==Me.PLAYING||(this.videoState.setState(Me.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==Me.PLAYING&&e!==Me.PAUSED||(this.videoState.setState(Me.PLAYING),D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===Me.READY&&this.videoState.setState(Me.READY)}handleRemoteStop(){this.videoState.getState()!==Me.STOPPED&&this.videoState.setState(Me.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:L(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!==Me.STOPPED&&(this.videoState.startTransitionTo(Me.STOPPED),this.stop()));if(s)return;const o=r?.to;if(a?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==Me.STOPPED)this.seek(o);else switch(i){case exports.PlaybackState.PLAYING:switch(t){case Me.PLAYING:break;case Me.PAUSED:case Me.READY:this.videoState.startTransitionTo(Me.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Me.STOPPED:this.videoState.startTransitionTo(Me.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case Me.PLAYING:this.videoState.startTransitionTo(Me.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Me.PAUSED:break;case Me.READY:this.videoState.startTransitionTo(Me.PAUSED),this.videoState.setState(Me.PAUSED);break;case Me.STOPPED:this.videoState.startTransitionTo(Me.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}}}var Fe;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Fe||(Fe={}));class Ue{subscription=new e.Subscription;videoState=new J(Fe.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.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,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(Fe.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Fe.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Fe.READY&&this.videoState.setState(Fe.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()===Fe.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(z(s))}playIfAllowed(){f(this.video).then((e=>{e||(this.videoState.setState(Fe.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!==Fe.STOPPED&&(this.videoState.startTransitionTo(Fe.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Fe.STOPPED),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===Fe.STOPPED)return this.videoState.startTransitionTo(Fe.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 Fe.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Fe.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Fe.PLAYING),this.playIfAllowed()));case Fe.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Fe.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Fe.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Fe.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class He{_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 qe{_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(qe._str2ua(e.substr(n))),n=e.length};this._lastXhr=new He(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=qe._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 je{_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 He(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?Ne(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 qe({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 Ge;!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'}(Ge||(Ge={}));const Ye=[Ge.PAUSED,Ge.PLAYING];class Qe{videoState=new J(Ge.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(z(this.params.source.url)),this.buffer=new $(this.video),this.dash=new je({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.looped$,t.loopedEvent$),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()===Ge.PLAYING||this.videoState.getState()===Ge.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(W(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ge.READY&&this.videoState.setState(Ge.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ge.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Ge.PLAYING),D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Ge.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.desiredState.autoVideoTrackLimits.stateChangeEnded$,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=Q(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);u=Y(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),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===Ge.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(Ge.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=Q(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(z(e.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((e=>{const{type:t,reused:s}=pe(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=(s.name&&_(s.name))??M(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(Ge.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(Ge.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!==Ge.STOPPED&&(this.videoState.startTransitionTo(Ge.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(Ge.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)&&Ye.includes(t)&&this.seek(o),t){case Ge.STOPPED:return this.videoState.startTransitionTo(Ge.MANIFEST_LOADED),void this.prepare();case Ge.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Ge.INITIAL_REPRESENTATION_SELECTED);case Ge.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Ge.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Ge.METADATA_LOADED:return this.videoState.startTransitionTo(Ge.READY),void this.dash.seek(o??0);case Ge.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Ge.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ge.PLAYING),this.playIfAllowed()));case Ge.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ge.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ge.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ge.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}var ze=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)},We=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 Je=e=>e.range?e.range.split('-').map((e=>parseInt(e,10))):[NaN,NaN];class Ke{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]=Je(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(Je),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 he,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 le(fetch).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,Ke.suppressStreamErrors).catch(h)))};i?.read().then(o,Ke.suppressStreamErrors).catch(h)}),Ke.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]=Je(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]=Je(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]=Je(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 Xe{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(Xe.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;Xe.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ze=(e,t)=>{const s=new Ke(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 Xe(a,t,i)}}))(t(e),s)}}),!0),()=>s.destroy()};var et=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 tt{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 st={};var it;!function(e){e.DOWNLOADING_LIB='downloading_lib',e.STOPPED='stopped',e.STREAM_INITIALIZED='stream_initialized',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(it||(it={}));const at=(t,s)=>new e.Observable((e=>{const i=t=>e.next(t);return t.on(s,i),()=>t.off(s,i)}));class rt{subscription=new e.Subscription;videoState=new J(it.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 tt;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(z(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||(st.MediaPlayer=t.MediaPlayer,st.Debug=t.Debug,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(st.MediaPlayer,'dashjs not loaded'),e.assertNonNullable(st.Debug,'dashjs not loaded'),this.player=st.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?Ne(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=Ze(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&&We(this.player),ze(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(it.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(W(this.video),this.elementSize$),a(at(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(at(this.player,'playbackError').pipe(e.map((e=>({id:'DashJSPlayback',message:e.error})))),t.error$);const r=at(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===it.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(at(this.player,'bufferStateChanged').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({state:e})=>'bufferStalled'===e))),t.isBuffering$),a(at(this.player,'fragmentLoadingStarted').pipe(e.map((e=>z(e.request.url)))),t.hostname$),a(at(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=M(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(it.STREAM_INITIALIZED),this.videoState.startTransitionTo(it.READY)})),a(at(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$,s.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const e=this.params.dependencies.throughputEstimator.throughput$.getValue(),t=Y(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:e,tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState()}),i=this.videoTracks.find((({track:e})=>e===t));i?.bitrateInfo&&this.player.setQualityFor('video',i?.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})=>ot(e)))),this.params.output.duration$);const o=at(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(at(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(at(this.player,'playbackEnded'),t.endedEvent$),a(at(this.player,'playbackProgress').pipe(e.map((()=>w(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(at(this.player,'playbackPlaying'),(()=>{this.videoState.setState(it.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)})),a(at(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(it.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(at(this.player,'playbackPaused'),(()=>{this.videoState.setState(it.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)})),a(at(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===it.READY&&this.videoState.setState(it.READY)})),a(this.isLive$,t.isLive$),a(W(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}=et(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(at(this.player,'manifestLoaded').pipe(e.once()).subscribe((()=>{const s=Date.now();this.subscription.add(at(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,looped$:h}=N(this.video);this.subscription.add(y(this.video,s.volume,u,i)),this.subscription.add(u.subscribe(t.volume$,i)),this.subscription.add(h.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(it.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(it.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(ot(s));const i=Ve(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Oe.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e)}play(){this.videoState.startTransitionTo(it.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(it.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===it.DOWNLOADING_LIB||t===it.STREAM_INITIALIZED)return;const o=a?.to;switch(i?.to!==exports.PlaybackState.PAUSED&&e.isNonNullable(o)&&t!==it.STOPPED&&s!==exports.PlaybackState.STOPPED&&(r?this.seek(o+ot(this.liveOffset.getTotalPausedTime())):this.seek(o)),s){case exports.PlaybackState.STOPPED:switch(t){case it.STOPPED:break;case it.PLAYING:case it.PAUSED:case it.READY:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case it.PLAYING:break;case it.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(ot(this.liveOffset.getTotalOffset()))):this.seek(ot(this.liveOffset.getTotalOffset()))),this.play();break;case it.READY:this.play();break;case it.STOPPED:this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case it.PLAYING:this.pause(),this.liveOffset.pause();break;case it.PAUSED:break;case it.READY:this.videoState.setState(it.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case it.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 ot=e=>-e/1e3;function nt(){return e.now()}function dt(e){return nt()-e}function ut(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 ht(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=dt(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=nt(),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=nt();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=nt(),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 ct{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 lt{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=nt(),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=ht(t,(i=>{e._complete=1,e._responseData=i,e._downloadTime=nt()-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=nt()}_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=nt();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 pt{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ct(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ut(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=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=ut(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],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(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 lt(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=ht(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=nt()-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=ht(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=nt(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=nt(),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=nt(),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)))},_=e=>{c()&&(t.cachedHeader=e,$(e,(()=>{n=!0,w()})))};r=!0,T.seek((t=>{c()&&(E=nt(),t?(m=t,!e.isNullable(s)||t.startTS>s?N(t):(h=t,k())):P())}),s),t.cachedHeader?_(t.cachedHeader):l(t.headerUrl,_,(()=>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=nt();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&&dt(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=nt();e<a&&(r=t),a=e}}}_fetchManifest(e,t,s){this.manifestRequest=ht(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 mt;!function(e){e.STOPPED='stopped',e.MANIFEST_READY='manifest_ready',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(mt||(mt={}));const St=[mt.PAUSED,mt.PLAYING,mt.READY],bt=[mt.PAUSED,mt.PLAYING,mt.READY];class ft{subscription=new e.Subscription;video;videoState=new J(mt.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new E;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new tt;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(z(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===mt.READY&&this.videoState.setState(mt.READY)}),s)).add(i.pause$.subscribe((()=>{this.videoState.setState(mt.PAUSED)}),s)).add(i.playing$.subscribe((()=>{this.videoState.setState(mt.PLAYING)}),s)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map(gt)).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.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:e}})=>{const t=e&&R[e].height;this.dash.setMaxAutoQuality(t)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case mt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case mt.MANIFEST_READY:case mt.READY:break;case mt.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case mt.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 pt({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:Y(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,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.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(gt(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=_(t.name)??M(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===mt.MANIFEST_READY&&this.videoState.setState(mt.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!==mt.STOPPED&&(this.videoState.startTransitionTo(mt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(mt.STOPPED)));if(s)return;if(bt.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)&&St.includes(t))this.seek(o+gt(this.liveOffset.getTotalPausedTime()));else switch(t){case mt.STOPPED:return this.videoState.startTransitionTo(mt.MANIFEST_READY),void this.dash.attachSource(Ve(this.params.source.url));case mt.MANIFEST_READY:this.videoState.startTransitionTo(mt.READY),this.prepare();break;case mt.READY:return void(i===exports.PlaybackState.PAUSED?this.videoState.setState(mt.PAUSED):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(mt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(mt.PAUSED)}))));case mt.PLAYING:return void(i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(mt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case mt.PAUSED:return void(i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(mt.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(mt.PAUSED)})),this.params.output.position$.next(gt(this.liveOffset.getTotalOffset()))):this.seek(gt(this.liveOffset.getTotalOffset()))));default:return e.assertNever(t)}}}const gt=e=>-e/1e3,vt=e=>{let t=null;if(e.QUALITY&&(t=_(e.QUALITY)),!t&&e.RESOLUTION){const[s,i]=e.RESOLUTION.split('x').map((e=>parseInt(e,10)));t=M({width:s,height:i})}return t??null},yt=async(e,t=e)=>{const s=await le(fetch).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=vt(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 Tt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(Tt||(Tt={}));class Et{subscription=new e.Subscription;videoState=new J(Tt.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(z(this.params.source.url)),yt(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.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(v(this.video,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(Tt.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Tt.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Tt.READY&&this.videoState.setState(Tt.READY),this.videoState.getState()===Tt.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(z(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===Tt.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(Tt.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!==Tt.STOPPED&&(this.videoState.startTransitionTo(Tt.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(Tt.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===Tt.STOPPED)return this.videoState.startTransitionTo(Tt.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Tt.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 Tt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Tt.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tt.PLAYING),this.playIfAllowed()));case Tt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Tt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Tt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Tt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Tt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}var Pt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(Pt||(Pt={}));class kt{subscription=new e.Subscription;videoState=new J(Pt.STOPPED);video;params;textTracksManager=new E;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new tt;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]),yt(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(z(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(Pt.PLAYING),D(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pt.PAUSED),D(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Pt.READY&&this.videoState.setState(Pt.READY),this.videoState.getState()===Pt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map($t)).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(z(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===Pt.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 le(fetch).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(Pt.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($t(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!==Pt.STOPPED&&(this.videoState.startTransitionTo(Pt.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(Pt.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(t===Pt.STOPPED)return this.videoState.startTransitionTo(Pt.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Pt.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const s=$t(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(Pt.READY),this.seek(n+$t(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case Pt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Pt.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pt.PLAYING),this.playIfAllowed()));case Pt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pt.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&D(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next($t(this.liveOffset.getTotalOffset()))):this.seek($t(this.liveOffset.getTotalOffset()))):i?.to===exports.PlaybackState.PAUSED&&(D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Pt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}const $t=e=>-e/1e3,wt={};var At;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(At||(At={}));const Nt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class xt{subscription=new e.Subscription;videoState=new J(At.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(z(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||(wt.Hls=t.default,wt.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(wt.Hls,'hls.js not loaded'),this.hls=new wt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(At.STOPPED)}subscribe(){e.assertNonNullable(wt.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.looped$,s.loopedEvent$),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(Nt(this.hls,wt.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(At.PLAYING),D(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(At.PAUSED),D(t.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)),r(Nt(this.hls,wt.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=_(t.attrs.QUALITY??'')??M({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(Nt(this.hls,wt.Events.LEVEL_LOADING).pipe(e.map((({url:e})=>z(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;r(t.autoVideoTrackLimits.stateChangeEnded$,(({to:e})=>{if(e.max){let t=-1;for(const{track:s,level:i}of this.trackLevels.values())!B(s.quality)&&O(s.quality,e.max)&&(t=Math.max(t,this.hls.levels.indexOf(i)));this.hls.autoLevelCapping=t}else this.hls.autoLevelCapping=-1;if(e.min){let t=1/0;for(const{track:s,level:i}of this.trackLevels.values())!B(s.quality)&&C(s.quality,e.min)&&(t=Math.min(t,i.bitrate));this.hls.config.minAutoBitrate=isFinite(t)?t:0}else this.hls.config.minAutoBitrate=0}));const n=Nt(this.hls,wt.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===At.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 At.STOPPED:break;case At.READY:case At.PLAYING:case At.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case At.PLAYING:break;case At.STOPPED:this.prepare();break;case At.READY:case At.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case At.PAUSED:break;case At.STOPPED:this.prepare();break;case At.READY:this.videoState.setState(At.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case At.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(At.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(At.PLAYING);await f(this.video)||(this.videoState.setState(At.PAUSED),D(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(At.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(At.STOPPED),D(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class _t{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 Dt=(()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)})(),Rt=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),It=document.createElement('video'),Ct={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(It.canPlayType?.('application/x-mpegurl')||It.canPlayType?.('vnd.apple.mpegURL'))},Lt={mp4:Boolean(It.canPlayType?.('video/mp4')),webm:Boolean(It.canPlayType?.('video/webm'))},Ot={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"'))},Vt=(Ot.h264||Ot.h265)&&Ot.aac,Mt=!Dt,Bt=Rt||Dt,Ft=!Ct.hls||!Bt,Ut=3e4,Ht=18e4,qt=3,jt=100,Gt={cacheDuration:12e4},Yt={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Qt={maxPausedTime:3e4},zt={maxPausedTime:3e4};class Wt{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,loopedEvent$: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 _t(i.filter((s=>e.isNonNullable(t.sources[s]))).filter((t=>{switch(t){case exports.VideoFormat.DASH:return Ct.mse&&Lt.mp4&&Vt&&Mt;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return Ct.mse&&Lt.mp4&&Vt;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return Ct.mse&&Lt.webm&&Ot.vp9&&Ot.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return Ct.mse&&Lt.mp4&&Vt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return Ct.hls&&Lt.mp4&&Bt;case exports.VideoFormat.HLS_JS:return Ct.mse&&Lt.mp4&&Vt&&Ft;case exports.VideoFormat.MPEG:return Lt.mp4;default:return e.assertNever(t)}}))),this.chromecastFormatsIterator=new _t(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);let i;try{i=this.createProvider(t,s)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:e})}i?this.current$.next({type:s,provider:i,destination:t}):this.switchToNextProvider()}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 Qe({container:i,source:o,desiredState:a,output:r,config:Gt,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 Le({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 rt({container:i,source:o,desiredState:a,output:r,format:t,config:zt,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 Et({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 kt({container:i,source:o,desiredState:a,output:r,config:Qt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=s[t];return e.assertNonNullable(o),new xt({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 Ue({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 ft({container:i,source:o,desiredState:a,output:r,config:Yt,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 Be({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:Ut,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(jt,{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]+Ht?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%qt}))),i}}const Jt=(e,t,s)=>s*t+(1-s)*e;class Kt{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 j(`raw_${s}`),this.smoothedSeries$=new j(`smoothed_${s}`),this.reportedSeries$=new j(`reported_${s}`)}next(t){this.slow=Jt(this.slow,t,this.params.emaAlphaSlow),this.fast=Jt(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 Xt;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(Xt||(Xt={}));const Zt=new Map;let es=Xt.RUNTIME;const ts=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(ts,'test'),localStorage.removeItem(ts),es=Xt.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;try{sessionStorage.getItem(ts),es=Xt.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException))throw e;es=Xt.RUNTIME}}})();const ss=(t,s)=>{switch(es){case Xt.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Xt.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Xt.RUNTIME:return void Zt.set(t,s);default:e.assertNever(es)}},is=window.navigator.connection,as=()=>{const t=is?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},rs=()=>{const t=is?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},os=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class ns{throughput;rtt;subscription=new e.Subscription;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=ns.load('one_video_throughput')||(t.useBrowserEstimation?as():void 0)||5e3,i=ns.load('one_video_rtt')??(t.useBrowserEstimation?rs():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(os(s,i,t.rttPenaltyRequestSize)),this.throughput=new Kt({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new Kt({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=as();t&&this.throughput.next(t);const s=rs();e.isNonNullable(s)&&this.rtt.next(s)};is&&'onchange'in is&&this.subscription.add(e.fromEvent(is,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{ss('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{ss('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})=>os(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(ns.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(es){case Xt.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Xt.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Xt.RUNTIME:return Zt.get(t);default:e.assertNever(es)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const ds=(t=(e=>e))=>({playbackState:s,seekPosition:i,playbackAbort$:a,looped$:r,position$:o})=>new e.Observable((n=>{let d;const u=s.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),h=s.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),c=i.stateChangeEnded$.pipe(e.filter((t=>e.isNonNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),l=i.stateChangeEnded$.pipe(e.filter((t=>e.isNullable(t.to)&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),p=e.merge(u,l).pipe(e.map((()=>t(o.getValue())))),m=e.merge(e.merge(h,c,a).pipe(e.map((()=>t(o.getValue())))),r.pipe(e.map(t)));return(new e.Subscription).add(p.subscribe((e=>{d=t(e)}))).add(m.subscribe((s=>{const i=t(s);if(e.isNullable(d)||d===i)return;const a={start:d,end:i};d=void 0,n.next(a)})))})),us=ds((e=>e)),hs=ds((e=>Math.round(1e3*e)+Date.now())),cs={[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 J(exports.PlaybackState.STOPPED),seekPosition:new J(void 0),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),externalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({})};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),autoQualityLimits$:new e.ValueSubject({}),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,looped$: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:H};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 ns(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 Wt({screenFormatsPriority:[...cs[o.SCREEN].live,...cs[o.SCREEN].vod],chromecastFormatsPriority:[...cs[o.CHROMECAST].live,...cs[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}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(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$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.autoQualityLimits$));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)=>B(e)?1:B(t)?-1:I(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.providerOutput.loopedEvent$.subscribe(this.events.looped$)).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(hs({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(us({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(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=Y(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),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),U={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{F=e})),this.providerContainer.current$.subscribe((({type:e})=>q('provider',e))),t.duration$.subscribe((e=>q('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>q('tracks',e))),this.events.fatalError$.subscribe(new j('fatalError')),this.events.managedError$.subscribe(new j('managedError')),t.position$.subscribe(new j('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new j('quality')),t.currentBuffer$.subscribe(new j('buffer')),t.isBuffering$.subscribe(new j('isBuffering'))].forEach((e=>this.subscription.add(e))),q('codecs',Object.keys(Ot).filter((e=>Ot[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.45';