function anonymous(module,exports,require ) { var e=require("buffer"),t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},s=t.parcelRequirec887_kd6oi;s.register("6JNQd",function(i,r){function n(e,t,s,i){Object.defineProperty(e,t,{get:s,set:i,enumerable:!0,configurable:!0})}var a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==t?t:{},o=a.parcelRequire94c2_uo2xw,l=o.register;l("jTOzh",function(e,t){n(e.exports,"DoppioWrapper",function(){return d});var s=o("bsvQL"),i=o("iRn4y"),r=o("hJ7nZ"),a=o("4gxuw"),l=o("giOKx");let u={[i.EPlaybackState.IDLE]:r.EPlaybackState.IDLE,[i.EPlaybackState.LOADING]:r.EPlaybackState.LOADING,[i.EPlaybackState.PAUSED]:r.EPlaybackState.PAUSED,[i.EPlaybackState.PLAYING]:r.EPlaybackState.PLAYING,[i.EPlaybackState.ERROR]:r.EPlaybackState.ERROR};class d extends a.AbstractWrapper{constructor(e){super(e),this._logLevels=[]}setStreamConfig(e){return e&&e.HLSStreamUrl?(this._lastKnownStreamConfig={hlsStreamUrl:e.HLSStreamUrl},this._playerInstance?.setUrl(e.HLSStreamUrl)):(this._lastKnownStreamConfig=null,this._playerInstance?.setUrl("")),this}setAbrResolutions(){return this}enableAbr(){return this._isAbrEnabled=!0,this._playerInstance?.enableABR(),this}setResolutionByName(e){return this._playerInstance?.setResolutionByName(e),this}setResolutionByBitrate(e){return this._playerInstance?.setResolutionByBitrate(e),this}setLoggerLevel(e){this._playerInstance?.setLoggerLevel(e),this._logLevels=e}disableAbr(){return this._isAbrEnabled=!1,this._playerInstance?.disableABR(),this}get version(){return this._playerInstance?.version}_attachEventListeners(){this._playerInstance&&(this._playerInstance.addEventListener(i.EEvent.DEBUGGER_CONNECTED,this._onDebuggerConnected),this._playerInstance.addEventListener(i.EEvent.PLAYBACK_STATE_CHANGED,this._onPlaybackStateChanged),this._playerInstance.addEventListener(i.EEvent.ERROR,this._onDoppioError),this._playerInstance.addEventListener(i.EEvent.VARIANTS_DETECTED,this._onResolutionsAvailable),this._playerInstance.addEventListener(i.EEvent.METRICS_AVAILABLE,this._onMetricsReported),this._playerInstance.addEventListener(i.EEvent.FRAG_LOADED,this._onPlaylistLoaded),this._playerInstance.addEventListener(i.EEvent.LEVEL_LOADED,this._onFragLoaded),this._playerInstance.addEventListener(i.EEvent.LIFECYCLE_EVENT,this._onLifecycleEventReported),this._playerInstance.addEventListener(i.EEvent.LIFECYCLE_ERROR,this._onLifecycleErrorReported),this._playerInstance.addEventListener(i.EEvent.LEVEL_SWITCHED_AUTO,this._onRenditionSwitchAuto),this._playerInstance.addEventListener(i.EEvent.RESOLUTION_CHANGED,this._onResolutionChanged),this._playerInstance.addEventListener(i.EEvent.RESOLUTION_NOT_FOUND,this._onResolutionNotFound),this._playerInstance.addEventListener(i.EEvent.FRAGMENT_FILTERED_OUT,this._onFragmentFilteredOut))}_detachEventListeners(){this._playerInstance&&(this._playerInstance.removeEventListener(i.EEvent.DEBUGGER_CONNECTED,this._onDebuggerConnected),this._playerInstance.removeEventListener(i.EEvent.PLAYBACK_STATE_CHANGED,this._onPlaybackStateChanged),this._playerInstance.removeEventListener(i.EEvent.ERROR,this._onDoppioError),this._playerInstance.removeEventListener(i.EEvent.VARIANTS_DETECTED,this._onResolutionsAvailable),this._playerInstance.removeEventListener(i.EEvent.METRICS_AVAILABLE,this._onMetricsReported),this._playerInstance.removeEventListener(i.EEvent.FRAG_LOADED,this._onPlaylistLoaded),this._playerInstance.removeEventListener(i.EEvent.LEVEL_LOADED,this._onFragLoaded),this._playerInstance.removeEventListener(i.EEvent.LIFECYCLE_EVENT,this._onLifecycleEventReported),this._playerInstance.removeEventListener(i.EEvent.LIFECYCLE_ERROR,this._onLifecycleErrorReported),this._playerInstance.removeEventListener(i.EEvent.RESOLUTION_CHANGED,this._onRenditionSwitchAuto),this._playerInstance.removeEventListener(i.EEvent.RESOLUTION_CHANGED,this._onResolutionChanged),this._playerInstance.removeEventListener(i.EEvent.RESOLUTION_NOT_FOUND,this._onResolutionNotFound),this._playerInstance.removeEventListener(i.EEvent.FRAGMENT_FILTERED_OUT,this._onFragmentFilteredOut))}_createPlayerInstance(){this._destroyPlayerInstance(),this._playerInstance=new i.DoppioPlayer,this._lastKnownConfig&&this._playerInstance.setConfig(this._lastKnownConfig),this._lastKnownStreamConfig&&this._playerInstance.setUrl(this._lastKnownStreamConfig.hlsStreamUrl),this._videoElement&&this._playerInstance.setVideoElement(this._videoElement),this._isAbrEnabled?this._playerInstance.enableABR():this._playerInstance.disableABR(),this._attachEventListeners(),this._playerInstance?.setLoggerLevel(this._logLevels)}_onDebuggerConnected({detail:{panelUrl:e}}){this._eventBusInstance.publish(l.EPlayersEvents.DEBUGGER_CONNECTED,{debuggerUrl:e})}_onPlaybackStateChanged({detail:{prevState:e,nextState:t}}){this._eventBusInstance.publish(l.EPlayersEvents.PLAYBACK_STATE_CHANGED,{nextState:u[t],prevState:u[e]})}_onDoppioError({detail:{error:e}}){this._eventBusInstance.publish(l.EPlayersEvents.ERROR,{error:e,playerType:r.EPlayerType.HLS})}_onResolutionsAvailable({detail:e}){this._eventBusInstance.publish(l.EPlayersEvents.RESOLUTIONS_AVAILABLE,{resolutions:e})}_onMetricsReported({detail:e}){this._metricsCollector?.registerMetrics({targetBuffer:e.targetBuffer})}_onFragLoaded(e){this._metricsCollector?.registerMetrics({chunkLoadDuration:e.detail.netStats.downloadDuration,chunkLoadTTFB:e.detail.netStats.ttfb})}_onPlaylistLoaded(e){this._metricsCollector?.registerMetrics({playlistLoadTTFB:e.detail.netStats.ttfb,playlistLoadDuration:e.detail.netStats.downloadDuration})}_onLifecycleEventReported({detail:{eventType:e}}){this._metricsCollector?.registerEvent(e,{})}_onRenditionSwitchAuto({detail:{nextResolution:e,prevResolution:t}}){this._metricsCollector?.registerEvent("RenditionSwitchedAuto",{prevResolution:t,nextResolution:e}),this._eventBusInstance.publish(l.EPlayersEvents.AUTO_RESOLUTION_SWITCHED,{name:e})}_onResolutionChanged({detail:{name:e}}){this._eventBusInstance.publish(l.EPlayersEvents.RESOLUTION_SWITCHED,{name:e})}_onLifecycleErrorReported({detail:{errorType:e,nativeError:t}}){this._metricsCollector?.registerEvent(e,{errorMessage:t?.message||""})}_onResolutionNotFound(){this._eventBusInstance.publish(l.EPlayersEvents.RESOLUTION_NOT_FOUND,{})}_onFragmentFilteredOut({detail:{reason:e,fragment:t}}){this._metricsCollector?.registerEvent("FragmentFilteredOut",{reason:e,fragmentName:t})}}(0,s.__decorate)([r.bind],d.prototype,"_onDebuggerConnected",null),(0,s.__decorate)([r.bind],d.prototype,"_onPlaybackStateChanged",null),(0,s.__decorate)([r.bind],d.prototype,"_onDoppioError",null),(0,s.__decorate)([r.bind],d.prototype,"_onResolutionsAvailable",null),(0,s.__decorate)([r.bind],d.prototype,"_onMetricsReported",null),(0,s.__decorate)([r.bind],d.prototype,"_onFragLoaded",null),(0,s.__decorate)([r.bind],d.prototype,"_onPlaylistLoaded",null),(0,s.__decorate)([r.bind],d.prototype,"_onLifecycleEventReported",null),(0,s.__decorate)([r.bind],d.prototype,"_onRenditionSwitchAuto",null),(0,s.__decorate)([r.bind],d.prototype,"_onResolutionChanged",null),(0,s.__decorate)([r.bind],d.prototype,"_onLifecycleErrorReported",null),(0,s.__decorate)([r.bind],d.prototype,"_onResolutionNotFound",null),(0,s.__decorate)([r.bind],d.prototype,"_onFragmentFilteredOut",null)}),l("iRn4y",function(t,s){function i(e,t,s,i){Object.defineProperty(e,t,{get:s,set:i,enumerable:!0,configurable:!0})}n(t.exports,"EEvent",function(){return sa}),n(t.exports,"EPlaybackState",function(){return sM}),n(t.exports,"DoppioPlayer",function(){return iN});var r,l,u,d,h,c,_,g,f,p,m,b,y,v,E,S,R,T,L,A,P,C,B,O,D,w,M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==a?a:{};function I(e){return e&&e.__esModule?e.default:e}var F={},N={},k=M.parcelRequire94c2_uo2xw;null==k&&((k=function(e){if(e in F)return F[e].exports;if(e in N){var t=N[e];delete N[e];var s={id:e,exports:{}};return F[e]=s,t.call(s.exports,s,s.exports),s.exports}var i=Error("Cannot find module '"+e+"'");throw i.code="MODULE_NOT_FOUND",i}).register=function(e,t){N[e]=t},M.parcelRequire94c2_uo2xw=k);var V=k.register;V("a8VW4",function(e,t){function s(e,t,s,i){var r,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,s,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(n<3?r(a):n>3?r(t,s,a):r(t,s))||a);return n>3&&a&&Object.defineProperty(t,s,a),a}i(e.exports,"__decorate",function(){return s}),"function"==typeof SuppressedError&&SuppressedError}),V("eQOGK",function(e,t){i(e.exports,"default",function(){return s});var s=function(e,t,s){if(!s||"function"!=typeof s.value)throw TypeError(`Only methods can be decorated with @bind. <${t}> is not a method!`);return{configurable:!0,get(){let e=s.value?.bind(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e}}}}),V("lYhjM",function(e,t){i(e.exports,"ELoadingState",function(){return r});var s,r=((s={}).UNKNOWN="unknown",s.LOADING="loading",s.LOADED="loaded",s.ABORTED="aborted",s.ERROR="error",s.DESTROYED="destroyed",s)}),V("gMZQX",function(e,t){i(e.exports,"ENetworkLoadFetchNetworkEvent",function(){return r});var s,r=((s={}).FETCH="fetch",s.ABORT="abort",s.DESTROY="destroy",s.DATA_READY="dataReady",s.STATS_READY="statsReady",s.CHANGE_STATE="changeState",s.ERROR="error",s.REDIRECT_DETECTED="redirectDetected",s)}),V("j9q3y",function(e,t){i(e.exports,"NetworkLoadFetch",function(){return a});var s=k("aoPbh"),r=k("lYhjM"),n=k("lR17I");let a=class{constructor(e){this.requestUrl="",this.realUrl="",this.mode="",this._dataChunks=[],this._receivedLength=0,this._abortController=new AbortController,this._startLoadTimestamp=0,this._isAborted=!1,this._config=e}abort(){this._isAborted=!0,this._abortController.abort()}async fetch(e,t){try{globalThis.performance&&globalThis.performance.clearResourceTimings&&globalThis.performance.clearResourceTimings(),this._config.onChangeState(r.ELoadingState.LOADING),this._startLoadTimestamp=Date.now(),this.requestUrl=e,this.mode=t,this._receivedLength=0;let i=new Request(this.requestUrl),n={signal:this._abortController.signal};this._config.requestCustomReferer&&(n.headers={"X-Referer":this._config.requestCustomReferer});let a=await fetch(i,n);this.realUrl=a.url;let o=a.body?.getReader();if(!o)throw Error();for(;;){let{done:e,value:t}=await o.read();if(e)break;this._dataChunks.push(t),this._receivedLength+=t.length}if(!a.ok&&(!a.status||a.status>399))throw this.error={status:a.status,statusText:a.statusText},Error();let l=(0,s.mergeUint8Arrays)(this._dataChunks).buffer;this._config.onDataReady("text"!==this.mode?l:new TextDecoder("utf-8").decode(l)),this._config.onStatsReady(this._getNetworkStats()),this.realUrl!==this.requestUrl&&this._config.onRedirectDetected(this.requestUrl,this.realUrl),this._config.onChangeState(r.ELoadingState.LOADED,{realUrl:a.url,status:a.status})}catch(e){if(this._isAborted){this._config.onStatsReady(this._getNetworkStats()),this._config.onChangeState(r.ELoadingState.ABORTED);return}this.error||(this.error={status:-1,statusText:e.toString()}),this._config.onError(this.error),this._config.onChangeState(r.ELoadingState.ERROR,{status:this.error.status})}}_getNetworkStats(){let e=Date.now()-this._startLoadTimestamp,t="text"===this.mode?"text":"binary";return(0,n.getNetworkStats)(this.requestUrl,e,this._receivedLength,t)}}}),V("aoPbh",function(e,t){i(e.exports,"mergeUint8Arrays",function(){return s});let s=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),s=0;return e.forEach(e=>{t.set(e,s),s+=e.length}),t}}),V("lR17I",function(e,t){i(e.exports,"getNetworkStats",function(){return r});let s=(e,t,s)=>{if(!globalThis.performance||!globalThis.performance.getEntriesByName)return null;let i=globalThis.performance.getEntriesByName(e)[0];if(!i)return null;let{connectStart:r,connectEnd:n,domainLookupEnd:a,duration:o,domainLookupStart:l,encodedBodySize:u,responseStart:d,requestStart:h}=i,c=(u||t)/1024;return globalThis.performance.clearResourceTimings(),{connectDuration:n-r,domainLookupDuration:a-l,sizeInKb:c,ttfb:d-h,downloadDuration:o,calculatedSpeed:c/(o/1e3)*8,type:s,url:e}},r=(e,t,i,r)=>s(e,i,r)||{connectDuration:0,domainLookupDuration:0,sizeInKb:i/1024,ttfb:0,url:e,downloadDuration:t,calculatedSpeed:i/1024/(t/1e3)*8,type:r}}),V("3264a",function(e,t){i(e.exports,"ECommand",function(){return r});var s,r=((s={}).CONNECT_TO_ROOM="connectToRoom",s.MODULES_INFO_AVAILABLE="modulesInfoAvailable",s.MODULE_LIFECYCLE_EVENT_AVAILABLE="moduleLifecycleEventAvailable",s.CLIENT_CONNECTED="clientConnected",s.CLIENT_INFO_AVAILABLE="clientInfoAvailable",s.CLIENT_DISCONNECTED="clientDisconnected",s)}),V("iVqGx",function(e,t){e.exports=o("lt6Wo").then(()=>k("8GHQT"))});var U=k("a8VW4");function x(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==M?M:void 0}"undefined"==typeof globalThis&&(globalThis=x());let q="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==M&&M;function G(e){try{new e("")}catch(e){return!1}return!0}"function"==typeof q.Event&&G(q.Event)||(q.Event=function(e,t){this.bubbles=!!t&&!!t.bubbles,this.cancelable=!!t&&!!t.cancelable,this.composed=!!t&&!!t.composed,this.type=e}),void 0!==q.EventTarget&&G(q.EventTarget)||(q.EventTarget=function(){function e(){this.__listeners=new Map}return e.prototype=Object.create(Object.prototype),e.prototype.addEventListener=function(e,t,s){if(arguments.length<2)throw TypeError(`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`);let i=this.__listeners,r=e.toString();i.has(r)||i.set(r,new Map);let n=i.get(r);n.has(t)||n.set(t,s)},e.prototype.removeEventListener=function(e,t,s){if(arguments.length<2)throw TypeError(`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`);let i=this.__listeners,r=e.toString();if(i.has(r)){let e=i.get(r);e.has(t)&&e.delete(t)}},e.prototype.dispatchEvent=function(e){if(!(e instanceof Event))throw TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");let t=e.type,s=this.__listeners.get(t);if(s)for(let[t,i]of s.entries()){try{"function"==typeof t?t.call(this,e):t&&"function"==typeof t.handleEvent&&t.handleEvent(e)}catch(e){setTimeout(()=>{throw e})}i&&i.once&&s.delete(t)}return!0},e}());let W=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;let s=this.listeners[e];for(let e=0,i=s.length;e{throw e})}i.options&&i.options.once&&this.removeEventListener(e.type,i.callback)}return!e.defaultPrevented}},H=class extends W{constructor(){super(),this.listeners||W.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){"abort"===e.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,e)),super.dispatchEvent(e)}},$=class{constructor(){Object.defineProperty(this,"signal",{value:new H,writable:!0,configurable:!0})}abort(e){let t=new Event("abort"),s=e;void 0===s&&((s=Error("This operation was aborted")).name="AbortError"),this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};("function"!=typeof(K="undefined"!=typeof self?self:M).Request||Object.prototype.hasOwnProperty.call(K.Request.prototype,"signal"))&&K.AbortController||("undefined"!=typeof Symbol&&Symbol.toStringTag&&($.prototype[Symbol.toStringTag]="AbortController",H.prototype[Symbol.toStringTag]="AbortSignal"),K.AbortController=$,K.AbortSignal=H);let j=x();"function"!=typeof j.queueMicrotask&&(j.queueMicrotask=function(e){Promise.resolve().then(e).catch(e=>setTimeout(()=>{throw e}))}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(...t){let s=isNaN(t[0])?1:Number(t[0]);return s?Array.prototype.reduce.call(this,function(t,i){return Array.isArray(i)?t.push(...e.call(i,s-1)):t.push(i),t},[]):Array.prototype.slice.call(this)},writable:!0}),Array.prototype.flatMap||Object.defineProperty(Array.prototype,"flatMap",{configurable:!0,value:function(...e){return this.map(...e).flat()},writable:!0});var K,Y,Q,X,z,J,Z,ee,et,es,ei,er,en,U=k("a8VW4"),ea="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==M?M:{};function eo(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==ea?ea:void 0}"undefined"==typeof globalThis&&(globalThis=eo());let el="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==ea&&ea;function eu(e){try{new e("")}catch(e){return!1}return!0}"function"==typeof el.Event&&eu(el.Event)||(el.Event=function(e,t){this.bubbles=!!t&&!!t.bubbles,this.cancelable=!!t&&!!t.cancelable,this.composed=!!t&&!!t.composed,this.type=e}),void 0!==el.EventTarget&&eu(el.EventTarget)||(el.EventTarget=function(){function e(){this.__listeners=new Map}return e.prototype=Object.create(Object.prototype),e.prototype.addEventListener=function(e,t,s){if(arguments.length<2)throw TypeError(`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`);let i=this.__listeners,r=e.toString();i.has(r)||i.set(r,new Map);let n=i.get(r);n.has(t)||n.set(t,s)},e.prototype.removeEventListener=function(e,t,s){if(arguments.length<2)throw TypeError(`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`);let i=this.__listeners,r=e.toString();if(i.has(r)){let e=i.get(r);e.has(t)&&e.delete(t)}},e.prototype.dispatchEvent=function(e){if(!(e instanceof Event))throw TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");let t=e.type,s=this.__listeners.get(t);if(s)for(let[t,i]of s.entries()){try{"function"==typeof t?t.call(this,e):t&&"function"==typeof t.handleEvent&&t.handleEvent(e)}catch(e){setTimeout(()=>{throw e})}i&&i.once&&s.delete(t)}return!0},e}());let ed=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;let s=this.listeners[e];for(let e=0,i=s.length;e{throw e})}i.options&&i.options.once&&this.removeEventListener(e.type,i.callback)}return!e.defaultPrevented}},eh=class extends ed{constructor(){super(),this.listeners||ed.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){"abort"===e.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ec=class{constructor(){Object.defineProperty(this,"signal",{value:new eh,writable:!0,configurable:!0})}abort(e){let t;t=new Event("abort");let s=e;void 0===s&&((s=Error("This operation was aborted")).name="AbortError"),this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};("function"!=typeof(r="undefined"!=typeof self?self:ea).Request||r.Request.prototype.hasOwnProperty("signal"))&&r.AbortController||("undefined"!=typeof Symbol&&Symbol.toStringTag&&(ec.prototype[Symbol.toStringTag]="AbortController",eh.prototype[Symbol.toStringTag]="AbortSignal"),r.AbortController=ec,r.AbortSignal=eh);let e_=eo();"function"!=typeof e_.queueMicrotask&&(e_.queueMicrotask=function(e){Promise.resolve().then(e).catch(e=>setTimeout(()=>{throw e}))}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){var t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,function(s,i){return Array.isArray(i)?s.push.apply(s,e.call(i,t-1)):s.push(i),s},[]):Array.prototype.slice.call(this)},writable:!0}),Array.prototype.flatMap||Object.defineProperty(Array.prototype,"flatMap",{configurable:!0,value:function(e){return Array.prototype.map.apply(this,arguments).flat()},writable:!0}),(l=Y||(Y={})).CLICK="videoElement.click",l.PLAYING="videoElement.playing",l.LOADING="videoElement.loading",l.PAUSE="videoElement.pause",l.VIDEO_PLAYBACK_STATE_CHANGE="videoElement.videoPlaybackStateChange",l.NATIVE_EVENT="videoElement.nativeEvent",l.UPDATE_PLAYER_RESOLUTION="videoElement.updatePlayerResolution",l.TIME_UPDATE="videoElement.timeUpdate";let eg=class{constructor(e=!0){this.appId=null,this._lastUid=-1,this._messages={},this._immediateExceptions=!1,this._allSubscribingMsg="*",this._immediateExceptions=e}setAppId(e){this.appId=e}getAppId(){return this.appId}publish(e,t){return this._publish(e,t,!1,this._immediateExceptions)}publishSync(e,t){return this._publish(e,t,!0,this._immediateExceptions)}subscribe(e,t){if("function"!=typeof t)return"";let s="uid_"+String(++this._lastUid);return this._messages[e]||(this._messages[e]={}),(this._messages[e]||{})[s]=t,s}toggleSubscriptionBulk(e){"subscribe"===e.action?Object.entries(e.callbacks).forEach(([e,t])=>{this.subscribe.call(this,e,t)}):Object.entries(e.callbacks).forEach(([e,t])=>{this.unsubscribe.call(this,t)})}subscribeAll(e){return this.subscribe(this._allSubscribingMsg,e)}subscribeOnce(e,t){let s=this.subscribe(e,(...e)=>{this.unsubscribe(s),t.apply(this,e)});return this}clearAllSubscriptions(){this._messages={}}clearSubscriptions(e){for(let t in this._messages)Object.prototype.hasOwnProperty.call(this._messages,t)&&0===t.indexOf(e)&&delete this._messages[t]}unsubscribe(e){let t="string"==typeof e&&(Object.prototype.hasOwnProperty.call(this._messages,e)||this._descendantTopicExists(e)),s=!t&&"string"==typeof e,i="function"==typeof e,r=!1;if(t){this.clearSubscriptions(e);return}for(let t in this._messages)if(Object.prototype.hasOwnProperty.call(this._messages,t)){let n=this._messages[t]||{};if(s&&n[e]){delete n[e],r=e;break}if(i)for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&n[t]===e&&(delete n[t],r=!0)}return r}_hasKeys(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}_throwException(e){return()=>{throw e}}_callSubscriberWithDelayedExceptions(e,t){try{e(t)}catch(e){setTimeout(this._throwException(e),0)}}_callSubscriberWithImmediateExceptions(e,t){e(t)}_deliverMessage(e,t,s,i){let r=this._messages[t]||{},n=i?this._callSubscriberWithImmediateExceptions:this._callSubscriberWithDelayedExceptions;if(Object.prototype.hasOwnProperty.call(this._messages,t))for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&n(r[e],s)}_createDeliveryFunction(e,t,s){return()=>{let i=String(e),r=i.lastIndexOf(".");for(this._deliverMessage(e,e,t,s);r>-1;)r=(i=i.substr(0,r)).lastIndexOf("."),this._deliverMessage(e,i,t,s);this._deliverMessage(e,this._allSubscribingMsg,t,s)}}_hasDirectSubscribersFor(e){let t=String(e);return!!(Object.prototype.hasOwnProperty.call(this._messages,t)&&this._hasKeys(this._messages[t]||{}))}_messageHasSubscribers(e){let t=String(e),s=this._hasDirectSubscribersFor(t)||this._hasDirectSubscribersFor(this._allSubscribingMsg),i=t.lastIndexOf(".");for(;!s&&-1!==i;)i=(t=t.substr(0,i)).lastIndexOf("."),s=this._hasDirectSubscribersFor(t);return s}_publish(e,t,s,i){let r="symbol"==typeof e?e.toString():e,n=this._createDeliveryFunction(r,t,i);return!!this._messageHasSubscribers(r)&&(s?n():setTimeout(n,0),!0)}_descendantTopicExists(e){for(let t in this._messages)if(Object.prototype.hasOwnProperty.call(this._messages,t)&&0===t.indexOf(e))return!0;return!1}};new eg,new eg;let ef=e=>`configProvider.configUpdated.${e}`,ep=e=>{let t={};return{configConsumerConstructor:class{constructor(s,i){this._onConfigUpdatedWithContext=this._onConfigUpdated.bind(this),this._configKey=s,this._eventBus=i||e;let r=ef(s);this._onConfigUpdatedListener=this._eventBus.subscribe(r,this._onConfigUpdatedWithContext),this.config=t[s]}destroy(){this._eventBus.unsubscribe(this._onConfigUpdatedListener)}_handleConfigUpdated(e,t){}_onConfigUpdated(e){t=e.newConfig;let s=e.newConfig[this._configKey];this.config=s,this._handleConfigUpdated(e.updatedValues,s)}},setConsumerConfig:e=>{t=e}}},em=e=>e instanceof Date,eb=e=>e instanceof Element||e instanceof Document,ey=e=>0===Object.keys(e).length,ev=e=>null!=e&&"object"==typeof e,eE=(e,...t)=>Object.prototype.hasOwnProperty.call(e,...t),eS=e=>ev(e)&&ey(e),eR=e=>t=>new Promise((s,i)=>{e(t,e=>{s(e)},e=>{i(e)})}),eT=(e,t)=>{if(e===t)return{};if(!ev(e)||!ev(t)||eb(e)||eb(t))return t;let s=Object.keys(e).reduce((e,s)=>(eE(t,s)||(e[s]=void 0),e),{});return em(e)||em(t)?e.valueOf()==t.valueOf()?{}:t:Object.keys(t).reduce((s,i)=>{if(!eE(e,i))return s[i]=t[i],s;let r=eT(e[i],t[i]);return eS(r)&&!em(r)&&(eS(e[i])||!eS(t[i]))||(s[i]=r),s},s)},eL=e=>{let t={...e},{configConsumerConstructor:s,setConsumerConfig:i}=ep(new eg);return i(e),{getConfigField:e=>t[e],setConfig:(e,s)=>{let r=Object.entries(e).reduce((e,[t,s])=>(e[t]={...e[t],...s},e),{...t}),n=eT(t,r);t=r,Object.entries(n).forEach(([e,t])=>{let i=ef(e);s.publish(i,{updatedValues:t,newConfig:r})}),i(t)},getConfig:()=>t,resetConfig:()=>{t={...e}},ConfigConsumer:s}};function eA(e,t,s){if(!s||"function"!=typeof s.value)throw TypeError(`Only methods can be decorated with @bind. <${t}> is not a method!`);return{configurable:!0,get(){let e=s.value?.bind(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e}}}function eP(e,t,s,i){var r,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,s,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(n<3?r(a):n>3?r(t,s,a):r(t,s))||a);return n>3&&a&&Object.defineProperty(t,s,a),a}(u=Q||(Q={})).HLS="hls",u.WEBRTC="webrtc",u.NATIVE="native",u.BROADCAST="broadcast",(d=X||(X={})).IDLE="idle",d.LOADING="loading",d.PAUSED="paused",d.PLAYING="playing",d.ERROR="error",(h=z||(z={})).WAITING="waiting",h.AUTO="auto",h.MANUAL="manual",(c=J||(J={})).BROADCAST_STATE_CHANGED="commonEvents.broadcastStateChanged",c.BROADCAST_REMOTE_STATS_AVAILABLE="commonEvents.broadcastRemoteStatsAvailable",c.PLAYING_STATE_CHANGED="commonEvents.playingStateChanged",c.COMMON_ERROR="commonEvents.commonError";let eC=new eg;(Z||(Z={})).LOG="logger.log";let eB=(e,t)=>(s,i)=>{eC.publish(Z.LOG,{domain:e,timestamp:performance.now(),level:t,message:s,payload:i})},eO=e=>{let t=`${e}{${(Math.random()+1).toString(36).substring(2,6)}}`;return{debug:eB(t,"debug"),verbose:eB(t,"verbose"),info:eB(t,"info"),warn:eB(t,"warn"),error:eB(t,"error"),fatal:eB(t,"fatal")}},eD=(...e)=>console.log(...e.filter(e=>void 0!==e)),ew={debug:(e,t)=>eD(`%c${e}`,"color: rgb(102, 102, 102)",t),verbose:(e,t)=>eD(`%c${e}`,"color: rgb(36, 114, 200)",t),info:(e,t)=>eD(`%c${e}`,"color: rgb(13, 188, 121)",t),warn:(e,t)=>eD(`%c${e}`,"color: rgb(229, 229, 16)",t),error:(e,t)=>eD(`%c${e}`,"color: rgb(241, 76, 76)",t),fatal:(e,t)=>eD(`%c${e}`,"background: rgb(241, 76, 76); color: #fff",t)},eM=[],eI=class{constructor(e=eM,t=[],s=[],i=!0){this._levels=e,this._enableErrorAutoLog=i,this._onLogMessageReceivedToken=eC.subscribe(Z.LOG,this._onMessageReceived),this._onErrorReceivedToken=eC.subscribe(J.COMMON_ERROR,this._onErrorReceived),this._ignoreDomains=s,this._additionalScopeSubscriptions=t.map(e=>eC.subscribe(e,t=>{this._onAdditionalScopeMessageReceived(e,t)}))}destroy(){eC.unsubscribe(this._onLogMessageReceivedToken),eC.unsubscribe(this._onErrorReceivedToken),this._additionalScopeSubscriptions.forEach(eC.unsubscribe)}_onMessageReceived(e){let{domain:t,timestamp:s,level:i,message:r,payload:n}=e;!this._levels.includes(i)||this._ignoreDomains.includes(t)||(ew[i]||ew.info)(`[${t}] ${i.toUpperCase()}:${r}@${s}`,n)}_onAdditionalScopeMessageReceived(e,t){(0,ew.verbose)(`[${e}] Event receiver with payload ${t} @ ${performance.now()}`)}_onErrorReceived({error:e}){this._enableErrorAutoLog&&eO("COMMON ERROR").error(`Error in ${e.domain}: ${e.message} ${e.info&&" ("+e.info+")"}`)}};eP([eA],eI.prototype,"_onMessageReceived",null),eP([eA],eI.prototype,"_onAdditionalScopeMessageReceived",null),eP([eA],eI.prototype,"_onErrorReceived",null);let eF={videoElementControllerConfig:{limitCheckingAutoplay:5,minimalPossibleVideoDimension:50,timeoutUpdateStatusPlaying:2e3,timeoutUpdateVideoDuration:500}},{ConfigConsumer:eN,setConfig:ek,resetConfig:eV}=eL(eF);(_=ee||(ee={})).NATIVE_EVENT="videoElementController.nativeEvent",_.CLICK="videoElementController.click",_.FORCE_PLAY_AFTER_PAUSE="videoElementController.forcePlayAfterPause",_.VIDEO_START="videoElementController.videoStart",_.VIDEO_PAUSE="videoElementController.videoPause",_.VIDEO_RESET="videoElementController.videoReset",_.PAUSED="videoElementController.paused",_.PLAYING="videoElementController.playing",_.LOADING="videoElementController.loading",_.LOADED="videoElementController.loaded",_.UPDATED="videoElementController.updated",_.DESTROY="videoElementController.destroy",_.STREAM_RESET="videoElementController.streamReset",_.CAN_PLAY="videoElementController.canPlay",_.REMOVE_MEDIA_STREAM="videoElementController.removeMediaStream",_.ERROR="videoElementController.error",_.ABORT="videoElementController.abort",_.STALLED="videoElementController.stalled",_.WAITING="videoElementController.waiting",_.UPDATE_PLAYER_RESOLUTION="videoElementController.updatePlayerResolution",_.RESET_CHECKING_AUTOPLAY_COUNT="videoElementController.resetCheckingAutoplayCount",_.CANCEL_RESET_STREAM="videoElementController.cancelResetStream",_.RESTART="videoElementController.restart",_.TIME_UPDATE_NATIVE="videoElementController.native",_.UPDATE_MEDIA_STREAM="videoElementController.updateMediaStream",_.VIDEO_ELEMENT_RECREATED="videoElementController.videoElementRecreated",_.VIDEO_PLAYBACK_STATE_CHANGED="videoElementController.videoPlaybackStateChanged",_.SET_VOLUME="videoElementController.setVolume";let eU=0,ex=class{constructor(e){this._config={},this._logger=eO("VideoElementController - AutoplayController"),this._eventsMap={[ee.CAN_PLAY]:this._checkAutoplayEnabled,[ee.DESTROY]:this.destroy,[ee.FORCE_PLAY_AFTER_PAUSE]:this._forcePlayAfterPause,[ee.RESET_CHECKING_AUTOPLAY_COUNT]:this._resetCheckingAutoplayCount},this._logger.info("Created"),this._logger.debug("Initial config",this._config),this._logger.debug("Initial state",this._state),this._state=e.state,this._eventBus=e.eventBus,this.init()}setConfig(e){this._logger.debug("Config update received, the new one:",e),this._config=e}destroy(){this._logger.info("Destroying"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}_handleConfigUpdated(){}_forcePlayAfterPause(e){if(void 0!==this._config.autoplay&&!this._config.autoplay){this._logger.verbose("Autoplay is disabled.");return}this._logger.verbose(`Trying to force video to play. Reason: ${e.reason}`);let t=this._state.getState();if(!t.startedPlaying||t.isPlaying||this._config.canBePaused){this._logger.verbose("Currently unable to autoplay the video");return}this._checkAutoplayEnabled()}_checkAutoplayEnabled(){if(this._logger.debug("Checking if autoplay is possible"),!this._state.getState().canPlay){this._logger.verbose("No canPlay event caught, skipping check");return}if(void 0!==this._config.autoplay&&!this._config.autoplay){this._logger.verbose("Autoplay is disabled.");return}if(eU>this._config.limitCheckingAutoplay){this._logger.verbose(`Unable to autoplay the video. The limit of autoplay checking (${this._config.limitCheckingAutoplay}) is exceeded`),this._eventBus.publish(ee.PAUSED,{});return}eU+=1,this._logger.verbose("Autoplay is used to play the video"),this._eventBus.publish(ee.VIDEO_START,{})}_resetCheckingAutoplayCount(){eU=0}};eP([eA],ex.prototype,"destroy",null),eP([eA],ex.prototype,"init",null),eP([eA],ex.prototype,"_forcePlayAfterPause",null),eP([eA],ex.prototype,"_checkAutoplayEnabled",null),eP([eA],ex.prototype,"_resetCheckingAutoplayCount",null);let eq=class extends EventTarget{constructor(){super()}emitEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}},eG=class extends eq{constructor(e){super(),this._eventsMap={[ee.PLAYING]:this._handlePlaying,[ee.LOADING]:this._handleLoading,[ee.VIDEO_PAUSE]:this._handlePause,[ee.CLICK]:this._handleClick,[ee.DESTROY]:this.destroy,[ee.NATIVE_EVENT]:this._handleNativeEvent,[ee.UPDATE_PLAYER_RESOLUTION]:this._handleUpdatePlayerResolution,[ee.VIDEO_PLAYBACK_STATE_CHANGED]:this._handleVideoPlaybackStateChange,[ee.TIME_UPDATE_NATIVE]:this._handleTimeUpdate},this._eventBus=e.eventBus,this.init()}destroy(){this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}init(){this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}_handlePlaying(e){this.emitEvent(Y.PLAYING,e)}_handleLoading(){this.emitEvent(Y.LOADING,{})}_handlePause(){this.emitEvent(Y.PAUSE,{})}_handleClick(e){this.emitEvent(Y.CLICK,{originalEvent:e.originalEvent})}_handleNativeEvent(e){this.emitEvent(Y.NATIVE_EVENT,e)}_handleUpdatePlayerResolution(e){this.emitEvent(Y.UPDATE_PLAYER_RESOLUTION,e)}_handleTimeUpdate(e){this.emitEvent(Y.TIME_UPDATE,e)}_handleVideoPlaybackStateChange(e){this.emitEvent(Y.VIDEO_PLAYBACK_STATE_CHANGE,{prevState:e.prevState,nextState:e.nextState})}};eP([eA],eG.prototype,"destroy",null),eP([eA],eG.prototype,"init",null),eP([eA],eG.prototype,"_handlePlaying",null),eP([eA],eG.prototype,"_handleLoading",null),eP([eA],eG.prototype,"_handlePause",null),eP([eA],eG.prototype,"_handleClick",null),eP([eA],eG.prototype,"_handleNativeEvent",null),eP([eA],eG.prototype,"_handleUpdatePlayerResolution",null),eP([eA],eG.prototype,"_handleTimeUpdate",null),eP([eA],eG.prototype,"_handleVideoPlaybackStateChange",null);var eW={};eW=function(e){var t={};function s(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t||4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(i,r,(function(t){return e[t]}).bind(null,r));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=90)}({17:function(e,t,s){t.__esModule=!0,t.default=void 0;var i=s(18),r=function(){function e(){}return e.getFirstMatch=function(e,t){var s=t.match(e);return s&&s.length>0&&s[1]||""},e.getSecondMatch=function(e,t){var s=t.match(e);return s&&s.length>1&&s[2]||""},e.matchAndReturnConst=function(e,t,s){if(e.test(t))return s},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0});if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0});if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,s,i){void 0===i&&(i=!1);var r=e.getVersionPrecision(t),n=e.getVersionPrecision(s),a=Math.max(r,n),o=0,l=e.map([t,s],function(t){var s=a-e.getVersionPrecision(t),i=t+Array(s+1).join(".0");return e.map(i.split("."),function(e){return Array(20-e.length).join("0")+e}).reverse()});for(i&&(o=a-Math.min(r,n)),a-=1;a>=o;){if(l[0][a]>l[1][a])return 1;if(l[0][a]===l[1][a]){if(a===o)return 0;a-=1}else if(l[0][a]1?i-1:0),n=1;n0){var a=Object.keys(s),l=o.default.find(a,function(e){return t.isOS(e)});if(l){var u=this.satisfies(s[l]);if(void 0!==u)return u}var d=o.default.find(a,function(e){return t.isPlatform(e)});if(d){var h=this.satisfies(s[d]);if(void 0!==h)return h}}if(n>0){var c=Object.keys(r),_=o.default.find(c,function(e){return t.isBrowser(e,!0)});if(void 0!==_)return this.compareVersion(r[_])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var s=this.getBrowserName().toLowerCase(),i=e.toLowerCase(),r=o.default.getBrowserTypeByAlias(i);return t&&r&&(i=r.toLowerCase()),i===s},t.compareVersion=function(e){var t=[0],s=e,i=!1,r=this.getBrowserVersion();if("string"==typeof r)return">"===e[0]||"<"===e[0]?(s=e.substr(1),"="===e[1]?(i=!0,s=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?s=e.substr(1):"~"===e[0]&&(i=!0,s=e.substr(1)),t.indexOf(o.default.compareVersions(r,s,i))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some(function(e){return t.is(e)})},e}();t.default=u,e.exports=t.default},92:function(e,t,s){t.__esModule=!0,t.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},n=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},s=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},s=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},s=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},s=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},s=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},s=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},s=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},s=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},s=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},s=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},s=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},s=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},s=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},s=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},s=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return s&&(t.version=s),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},s=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},s=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},s=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},s=r.default.getFirstMatch(n,e)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},s=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},s=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},s=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},s=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},s=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},s=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},s=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},s=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},s=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:function(e){var t=!e.test(/like android/i),s=e.test(/android/i);return t&&s},describe:function(e){var t={name:"Android Browser"},s=r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},s=r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},s=r.default.getFirstMatch(n,e);return s&&(t.version=s),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(t,e),version:r.default.getSecondMatch(t,e)}}}];t.default=a,e.exports=t.default},93:function(e,t,s){t.__esModule=!0,t.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},n=s(18),a=[{test:[/Roku\/DVP/],describe:function(e){var t=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:n.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),s=r.default.getWindowsVersionName(t);return{name:n.OS_MAP.Windows,version:t,versionName:s}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:n.OS_MAP.iOS},s=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return s&&(t.version=s),t}},{test:[/macintosh/i],describe:function(e){var t=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),s=r.default.getMacOSVersionName(t),i={name:n.OS_MAP.MacOS,version:t};return s&&(i.versionName=s),i}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:n.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),s=e.test(/android/i);return t&&s},describe:function(e){var t=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),s=r.default.getAndroidVersionName(t),i={name:n.OS_MAP.Android,version:t};return s&&(i.versionName=s),i}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),s={name:n.OS_MAP.WebOS};return t&&t.length&&(s.version=t),s}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=r.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||r.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||r.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:n.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:n.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:n.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.PlayStation4,version:t}}}];t.default=a,e.exports=t.default},94:function(e,t,s){t.__esModule=!0,t.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},n=s(18),a=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=r.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",s={type:n.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(s.model=t),s}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),s=e.test(/like (ipod|iphone)/i);return t&&!s},describe:function(e){var t=r.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:n.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:n.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:n.PLATFORMS_MAP.tv}}}];t.default=a,e.exports=t.default},95:function(e,t,s){t.__esModule=!0,t.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},n=s(18),a=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:n.ENGINE_MAP.Blink};var t=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:n.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:n.ENGINE_MAP.Trident},s=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:n.ENGINE_MAP.Presto},s=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:function(e){var t=e.test(/gecko/i),s=e.test(/like gecko/i);return t&&!s},describe:function(e){var t={name:n.ENGINE_MAP.Gecko},s=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:n.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:n.ENGINE_MAP.WebKit},s=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return s&&(t.version=s),t}}];t.default=a,e.exports=t.default}});let eH=globalThis?.navigator?.userAgent?((g=eW)&&g.__esModule?g.default:g).getParser(globalThis.navigator.userAgent):null,e$=e=>!!eH&&(eH.satisfies(e)||!1),ej={safari15OrHigher:e$({safari:">=15"}),firefox:e$({firefox:">0"}),safari:e$({safari:">0"}),chrome:e$({chrome:">0"}),edge:e$({edge:">0"})},eK=new WeakMap,eY={IDLE:1,LOADING:2},eQ=(e,t)=>{let s=0===e.readyState,i=e.networkState!==eY.LOADING&&e.networkState!==eY.IDLE;if(ej.firefox&&"play"===t&&s&&i)throw Error("Can not play audio")},eX=(e,t)=>e instanceof HTMLMediaElement?(eQ(e,t),"function"==typeof t)?t(e):e[t]():null,ez=(e,t)=>{let s=(eK.get(e)||Promise.resolve()).then(()=>{let s=eX(e,t);return s?.then?Promise.resolve(s):new Promise(e=>{setTimeout(()=>{e(s)},150)})}).then(()=>{eK.delete(e)}).catch(t=>{throw eK.delete(e),t});return eK.set(e,s),s},eJ=class{constructor(e){this._logger=eO("VideoElementController - PlaybackController"),this._eventsMap={[ee.VIDEO_START]:this._startVideo,[ee.VIDEO_PAUSE]:this._pauseVideo,[ee.VIDEO_RESET]:this._resetVideo,[ee.RESTART]:this._restart,[ee.DESTROY]:this._destroy},this._logger.info("Created"),this._logger.debug("Initial state",this._state),this._state=e.state,this._eventBus=e.eventBus,this.init()}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}_startVideo(){let e=this._state.getState().videoElement;if(this._logger.verbose("Starting the video"),e)return e.playbackRate||(e.playbackRate=1),this._logger.debug("Play call is added to the promises queue"),ez(e,"play").then(()=>{this._logger.debug("Play call resolved"),this._state.getState().canPlay&&this._eventBus.publish(ee.PLAYING,{})}).catch(e=>{this._state.setState({isAutoplayError:!0}),this._logger.error("An error occured when trying to play the video.",{error:e}),this._state.getState().canPlay&&this._eventBus.publish(ee.PAUSED,{})})}_pauseVideo(){this._logger.debug("Pausing the video");let e=this._state.getState().videoElement;if(e)return this._logger.debug("Pause call is added to the promises queue"),ez(e,"pause").then(()=>{this._logger.debug("Pause call resolved")}).catch(e=>{this._logger.warn("Could not pause video",e)})}_loadVideo(){this._logger.verbose("Loading the video");let e=this._state.getState().videoElement;if(e?.src&&e.src.startsWith("blob")){this._logger.debug("Stream seems to be blob. Skipping load");return}if(e)return this._logger.debug("Load call is added to the promises queue"),ez(e,"load").then(()=>{this._logger.debug("Load call resolved")}).catch(e=>{this._logger.warn("Could not load video",e)})}_resetVideo(){this._logger.verbose("Resetting the video"),this._state.getState().videoElement&&(this._eventBus.publish(ee.LOADING,{}),this._loadVideo())}async _restart(){this._logger.verbose("Restarting the video"),await this._pauseVideo(),this._startVideo()}_destroy(){this._logger.info("Destroying"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}};eP([eA],eJ.prototype,"init",null),eP([eA],eJ.prototype,"_startVideo",null),eP([eA],eJ.prototype,"_pauseVideo",null),eP([eA],eJ.prototype,"_loadVideo",null),eP([eA],eJ.prototype,"_resetVideo",null),eP([eA],eJ.prototype,"_restart",null),eP([eA],eJ.prototype,"_destroy",null);let eZ=(e,t)=>{if(!t||t<0)e.muted=!0,e.volume=0;else{let s=Math.min(t,1);isNaN(s)||(e.muted=!1,e.volume=s)}},e0=e=>{e&&e.parentNode&&e.parentNode.removeChild(e)},e1=` width: 100%;`,e2=class{constructor({className:e,state:t,eventBus:s}){this._logger=eO("VideoElementController - CanvasVideoRenderer"),this._knownVideoElementStyles="",this._eventsMap={[ee.PLAYING]:this.startAnimationFrame,[ee.LOADING]:this.cancelAnimationFrame,[ee.REMOVE_MEDIA_STREAM]:this.cancelAnimationFrame},this._applyStyles=()=>{let{canvasElement:e,videoElement:t}=this._getElements();e&&t&&(this._knownVideoElementStyles=t.style.cssText,e.style.cssText=e1,t.style.cssText=` ${e1} opacity: 0; position: absolute; left: 0; top: 0; `)},this._state=t,this._eventBus=s;let i=document.createElement("canvas");this._canvasContext=i.getContext("2d"),e&&(i.className=e),this.init(),this._state.setState({canvasElement:i}),this._applyStyles(),this._logger.verbose("Canvas renderer has been created")}startAnimationFrame(){let{canvasElement:e,videoElement:t}=this._getElements();if(this.cancelAnimationFrame(),!e||!t)return;let{width:s,height:i}=e.getBoundingClientRect(),{videoWidth:r,videoHeight:n}=t;if(s/i<1&&r/n>1){let a=Math.max(s,r),o=s/r*n;if(this._canvasContext){let t=devicePixelRatio;e.width=a*t,e.height=i*t,this._canvasContext.scale(t,t)}this._canvasContext?.drawImage(t,s>a?(s-a)/2:0,(i-o)/2,a,o)}else{let a=Math.max(i,n),o=i/n*r;if(this._canvasContext){let t=devicePixelRatio;e.width=s*t,e.height=a*t,this._canvasContext.scale(t,t)}this._canvasContext?.drawImage(t,(s-o)/2,i>a?(i-a)/2:0,o,a)}this._state.getState().isLoading||(this._canvasAnimationFrameId=requestAnimationFrame(this.startAnimationFrame))}getCanvasElement(){return this._getElements().canvasElement}destroy(){this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap});let{canvasElement:e,videoElement:t}=this._getElements();e&&e.parentNode&&e.parentNode.removeChild(e),t&&(t.style.cssText=this._knownVideoElementStyles,this._knownVideoElementStyles=""),this._state.setState({canvasElement:null}),this._logger.verbose("Canvas renderer was destroyed")}init(){this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}cancelAnimationFrame(){this._canvasAnimationFrameId&&(cancelAnimationFrame(this._canvasAnimationFrameId),this._canvasAnimationFrameId=null)}_getElements(){let{videoElement:e,canvasElement:t}=this._state.getState();return{videoElement:e,canvasElement:t}}};eP([eA],e2.prototype,"startAnimationFrame",null),eP([eA],e2.prototype,"destroy",null),eP([eA],e2.prototype,"init",null),eP([eA],e2.prototype,"cancelAnimationFrame",null),eP([eA],e2.prototype,"_getElements",null);let e3=class{constructor(e){this._canvasVideoRenderer=null,this._logger=eO("VideoElementController - RenderController"),this._config={},this._isLocalVideo=!1,this._eventsMap={[ee.SET_VOLUME]:this._setVolume,[ee.DESTROY]:this._destroy},this._state=e.state,this._eventBus=e.eventBus,this._logger.info("Created"),this._logger.debug("Initial config",this._config),this._logger.debug("Initial state",this._state),this.init()}setConfig(e){this._logger.debug("Config update received, the new one:",e),this._config=e,this.applyConfigToVideoElement()}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}getElements(){let{videoElement:e,canvasElement:t,ownContainer:s}=this._state.getState();return{videoElement:e,canvasElement:t,ownContainer:s}}getVideoElement(){return this.getElements().videoElement}getCanvasElement(){return this.getElements().canvasElement}renderVideoInto(e){let{ownContainer:t,videoElement:s}=this.getElements();this._logger.debug("renderVideoInto method was called");let i=!1;if(e&&s){let r=t||e;s.parentElement!==r&&(i=!0,r.appendChild(s));let n=this._canvasVideoRenderer?.getCanvasElement();this._canvasVideoRenderer&&n?.parentElement!==r&&(i=!0,r.appendChild(n),this._logger.info("Canvas element has been rendered to DOM")),r===t&&t.parentElement!==e&&(i=!0,e.appendChild(t)),i?this._logger.info("Video element has been rendered to DOM"):this._logger.verbose("Skipping video element render: video element is already mounted to the DOM.")}}setVideoElement(e,t){if(this._logger.debug("Video element updated",e),e===this.getVideoElement()){this._logger.verbose("Received video element is equal to the previous one. Skipping");return}this._isLocalVideo&&(this._logger.verbose("Removing video element and container from document"),e0(this.getElements().videoElement),e0(this.getElements().ownContainer)),this._state.setState({videoElement:e,ownContainer:t}),this.applyConfigToVideoElement()}applyConfigToVideoElement(){if(this._logger.debug("Applying config to the video element"),!this.getVideoElement()){this._logger.verbose("No video element known, could not apply config");return}let e=this.getVideoElement();if(!e)return;let{isNonAnonymous:t,isMuted:s,nativeControls:i,videoElementClassName:r,canvasElementClassName:n,shouldUseCanvas:a,rootElement:o,autoplay:l}=this._config;this._logger.verbose("Applied config",this._config),l&&(e.autoplay=!0),e.playsInline=!0,void 0!==i&&(e.controls=!!i),void 0!==s&&(e.muted=!!s),void 0!==t&&(t?e.removeAttribute("crossOrigin"):e.crossOrigin="anonymous"),r&&(e.className=r);let u=[this._state.getState().volume,this._config.volume].find(e=>void 0!==e);if(void 0!==u&&this._setVolume({volume:u}),a&&!this._canvasVideoRenderer&&(this._logger.verbose("Adding canvas as requested"),this._addCanvasVideoRenderer(),this._state.getState().isPlaying&&this._canvasVideoRenderer.startAnimationFrame()),!a&&this._canvasVideoRenderer){let e=this._state.getState().stream;this._logger.verbose("Removing canvas renderer"),e&&this._eventBus.publish(ee.UPDATE_MEDIA_STREAM,e),this._destroyCanvasRenderer()}let d=this.getCanvasElement();d&&(e.className="",n&&(d.className=n)),o&&this.renderVideoInto(o)}destroy(){if(this._logger.info("Destroying"),this._destroyCanvasRenderer(),this._isLocalVideo){this._logger.debug("Removing video element and container from document in destroy");let{videoElement:e,ownContainer:t}=this.getElements();e0(e),e0(t)}}createVideoElement(){let e,t;this._logger.info("Creating video element"),this._config.videoElement?(this._logger.debug("External video element passed from config - using existing one",this._config.videoElement),this._isLocalVideo=!1,e=this._config.videoElement):(this._isLocalVideo=!0,e=document.createElement("video"),t=document.createElement("div"),this._logger.debug("No external video element provided in config - created the new one",{videoElement:e,ownContainer:t}),t.style.position="relative"),this.setVideoElement(e,t),this._eventBus.publish(ee.VIDEO_ELEMENT_RECREATED,{videoElement:this.getVideoElement()})}_addCanvasVideoRenderer(){this._logger.debug("Adding canvas renderer"),this._canvasVideoRenderer||(this._canvasVideoRenderer=new e2({videoElement:this.getVideoElement(),className:this._config.videoElementClassName,state:this._state,eventBus:this._eventBus}))}_destroyCanvasRenderer(){this._logger.debug("Destroying canvas renderer"),this._canvasVideoRenderer&&(this._canvasVideoRenderer.destroy(),this._canvasVideoRenderer=null)}_setVolume({volume:e}){let t=this.getVideoElement();t&&(eZ(t,e),this._logger.verbose(`Video volume level has been set to ${e}`))}_destroy(){this._logger.info("Destroying"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}};eP([eA],e3.prototype,"getElements",null),eP([eA],e3.prototype,"getVideoElement",null),eP([eA],e3.prototype,"getCanvasElement",null),eP([eA],e3.prototype,"renderVideoInto",null),eP([eA],e3.prototype,"setVideoElement",null),eP([eA],e3.prototype,"applyConfigToVideoElement",null),eP([eA],e3.prototype,"createVideoElement",null),eP([eA],e3.prototype,"_addCanvasVideoRenderer",null),eP([eA],e3.prototype,"_destroyCanvasRenderer",null),eP([eA],e3.prototype,"_setVolume",null),eP([eA],e3.prototype,"_destroy",null);let e4=class{constructor(e){this._config={},this._logger=eO("VideoElementController - StateController"),this._eventsMap={[ee.PLAYING]:this._handlePlaying,[ee.LOADING]:this._handleLoading,[ee.VIDEO_PAUSE]:this._handlePause,[ee.CAN_PLAY]:this._handleCanPlay,[ee.PAUSED]:this._handlePaused,[ee.RESTART]:this._handleRestart,[ee.UPDATED]:this._handleUpdate,[ee.STALLED]:this._handleStalled,[ee.WAITING]:this._handleWaiting,[ee.UPDATE_PLAYER_RESOLUTION]:this._handleUpdatePlayerResolution,[ee.ERROR]:this._handleError,[ee.SET_VOLUME]:this._handleSetVolume,[ee.DESTROY]:this.destroy},this._logger.info("Created"),this._logger.verbose("Initial state",e.state),this._state=e.state,this._eventBus=e.eventBus,this.init()}setConfig(e){this._logger.debug("Config update received, the new one:",e),this._config=e}destroy(){this._logger.info("Destroy"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap}),this._state.resetState(),this._state.setState({isDestroyed:!0})}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}_updateState(e){let t=this._state.getState().videoPlaybackState,s=t;e.isPlaying?s=X.PLAYING:e.isLoading?s=X.LOADING:e.isPaused?s=X.PAUSED:e.isError&&(s=X.ERROR),this._logger.debug(`State updated: ${t} -> ${s}`),this._state.setState({...e,videoPlaybackState:s}),t!==s&&this._eventBus.publish(ee.VIDEO_PLAYBACK_STATE_CHANGED,{prevState:t,nextState:s})}_handlePlaying(){this._logger.debug("Playing event received"),this._updateState({isPlaying:!0,startedPlaying:!0,isLoading:!1,isStalled:!1,isWaiting:!1,isPaused:!1,isError:!1})}_handleLoading(){this._logger.debug("Loading event received"),this._updateState({isLoading:!0,isPlaying:!1})}_handlePause(){this._logger.debug("Pause event received"),this._updateState({isPlaying:!1,isPaused:!0})}_handlePaused(){this._logger.debug("Paused event received"),this._updateState({isPlaying:!1,isLoading:!1,isPaused:!0})}_handleCanPlay(){this._logger.debug("CanPlay event received"),this._updateState({canPlay:!0,isDestroyed:!1})}_handleRestart(){this._logger.debug("Restart event received"),this._updateState({isRestarted:!0})}_handleStalled(){this._logger.debug("Stalled event received"),this._updateState({isStalled:!0})}_handleWaiting(){this._logger.debug("Waiting event received"),this._updateState({isWaiting:!0})}_handleError(){this._logger.debug("Error event received"),this._updateState({isError:!0})}_handleSetVolume({volume:e}){this._logger.debug("Volume event received",{volume:e}),this._updateState({volume:e})}_handleUpdatePlayerResolution(e){this._logger.debug("Player resolution event received",{height:e.height,width:e.width}),this._updateState({videoElementResolution:{height:e.height,width:e.width}})}_handleUpdate(){this._logger.debug("Update event received"),this._updateState({canPlay:!1,isLoading:!0,isPlaying:!1,isRestarted:!1,isPaused:!1,isError:!1})}};eP([eA],e4.prototype,"destroy",null),eP([eA],e4.prototype,"init",null),eP([eA],e4.prototype,"_updateState",null),eP([eA],e4.prototype,"_handlePlaying",null),eP([eA],e4.prototype,"_handleLoading",null),eP([eA],e4.prototype,"_handlePause",null),eP([eA],e4.prototype,"_handlePaused",null),eP([eA],e4.prototype,"_handleCanPlay",null),eP([eA],e4.prototype,"_handleRestart",null),eP([eA],e4.prototype,"_handleStalled",null),eP([eA],e4.prototype,"_handleWaiting",null),eP([eA],e4.prototype,"_handleError",null),eP([eA],e4.prototype,"_handleSetVolume",null),eP([eA],e4.prototype,"_handleUpdatePlayerResolution",null),eP([eA],e4.prototype,"_handleUpdate",null);let e8=class{constructor(e){this._config={},this._logger=eO("VideoElementController - StreamController"),this._eventsMap={[ee.PLAYING]:this._cancelResetStream,[ee.LOADING]:this._cancelResetStream,[ee.LOADED]:this._cancelResetStream,[ee.PAUSED]:this._cancelResetStream,[ee.UPDATED]:this._cancelResetStream,[ee.CANCEL_RESET_STREAM]:this._cancelResetStream,[ee.STREAM_RESET]:this._resetStream,[ee.UPDATE_MEDIA_STREAM]:this.updateMediaStream,[ee.DESTROY]:this.destroy},this._getIsSrcObjectAvailable=()=>this._props.getVideoElement()?.srcObject!==void 0,this._state=e.state,this._props=e,this._eventBus=e.eventBus,this._logger.info("Created"),this._logger.verbose("Initial state",e.state),this.init()}setConfig(e){this._logger.debug("Config update received, the new one:",e),this._config=e}updateMediaStream(e){if(this._logger.info("Updating media stream",{stream:e}),!this._props.getVideoElement()){this._logger.debug("No video element known. Skipping media stream update");return}this._attachStream(e),this._eventBus.publish(ee.VIDEO_START,{})}removeMediaStream(){this._logger.info("Removing media stream");let e=this._props.getVideoElement();if(!e){this._logger.debug("No video element known. Skipping media stream remove");return}this._eventBus.publish(ee.VIDEO_PAUSE,{}),this._eventBus.publish(ee.REMOVE_MEDIA_STREAM,{}),this._getIsSrcObjectAvailable()?(this._logger.debug("Setting srcObject to null"),e.srcObject=null):(this._logger.debug("Revoking object url",{url:e.src}),window.URL.revokeObjectURL(e.src)),e.src&&(this._logger.debug("Removing src attribute from video"),e.removeAttribute("src"))}destroy(){this._logger.info("Destroying"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}_attachStream(e){this._logger.info("Attaching media stream",{stream:e});let t=this._props.getVideoElement();if(!t||!e){this._logger.debug("No video element or stream defined. Skipping stream set");return}if(t.src===e){this._logger.debug("Current video element src attribute value is equal to the new stream. Skipping stream set");return}"string"==typeof e?(this._logger.debug("Setting video element src attribute"),t.src=e):this._getIsSrcObjectAvailable()?(this._logger.debug("Setting video element srcObject attribute"),t.srcObject=e):(t.src=window.URL.createObjectURL(e),this._logger.debug(`Got MediaStream as stream, but srcObject is not available. Created new object URL: ${t.src}`))}_cancelResetStream(){this._logger.debug("Stream reset action cancel required"),this._streamResetDelayId&&(clearTimeout(this._streamResetDelayId),this._logger.debug("Stream reset action cancelled"))}_resetStream({timeout:e}){if(this._logger.debug("Reset stream required"),!e){this._logger.verbose("No timeout set, skipping stream reset",{timeout:e});return}this._cancelResetStream(),this._streamResetDelayId=setTimeout(()=>{this._logger.debug("Resetting stream timeout fired");let e=!1;this._config.onResetStream&&(e=this._config.onResetStream());let t=this._state.getState().stream;if(t&&!e){if("string"==typeof t&&t.startsWith("blob")){this._logger.debug("Streams seems to be object url. Skipping reset");return}this._logger.debug("Resetting stream"),this.removeMediaStream(),this.updateMediaStream(t)}},e)}};eP([eA],e8.prototype,"updateMediaStream",null),eP([eA],e8.prototype,"removeMediaStream",null),eP([eA],e8.prototype,"destroy",null),eP([eA],e8.prototype,"init",null),eP([eA],e8.prototype,"_attachStream",null),eP([eA],e8.prototype,"_cancelResetStream",null),eP([eA],e8.prototype,"_resetStream",null);var e6=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},e5="object"==typeof ea&&ea&&ea.Object===Object&&ea,e9="object"==typeof self&&self&&self.Object===Object&&self,e7=e5||e9||Function("return this")(),te=function(){return e7.Date.now()},tt=/\s/,ts=function(e){for(var t=e.length;t--&&tt.test(e.charAt(t)););return t},ti=/^\s+/,tr=e7.Symbol,tn=Object.prototype,ta=tn.hasOwnProperty,to=tn.toString,tl=tr?tr.toStringTag:void 0,tu=function(e){var t=ta.call(e,tl),s=e[tl];try{e[tl]=void 0;var i=!0}catch(e){}var r=to.call(e);return i&&(t?e[tl]=s:delete e[tl]),r},td=Object.prototype.toString,th=tr?tr.toStringTag:void 0,tc=0/0,t_=/^[-+]0x[0-9a-f]+$/i,tg=/^0b[01]+$/i,tf=/^0o[0-7]+$/i,tp=parseInt,tm=function(e){if("number"==typeof e)return e;if("symbol"==typeof(t=e)||null!=t&&"object"==typeof t&&"[object Symbol]"==(null==t?void 0===t?"[object Undefined]":"[object Null]":th&&th in Object(t)?tu(t):td.call(t)))return tc;if(e6(e)){var t,s,i="function"==typeof e.valueOf?e.valueOf():e;e=e6(i)?i+"":i}if("string"!=typeof e)return 0===e?e:+e;e=(s=e)?s.slice(0,ts(s)+1).replace(ti,""):s;var r=tg.test(e);return r||tf.test(e)?tp(e.slice(2),r?2:8):t_.test(e)?tc:+e},tb=Math.max,ty=Math.min,tv=function(e,t,s){var i,r,n,a,o,l,u=0,d=!1,h=!1,c=!0;if("function"!=typeof e)throw TypeError("Expected a function");function _(t){var s=i,n=r;return i=r=void 0,u=t,a=e.apply(n,s)}function g(e){var s=e-l,i=e-u;return void 0===l||s>=t||s<0||h&&i>=n}function f(){var e,s,i,r=te();if(g(r))return p(r);o=setTimeout(f,(e=r-l,s=r-u,i=t-e,h?ty(i,n-s):i))}function p(e){return(o=void 0,c&&i)?_(e):(i=r=void 0,a)}function m(){var e,s=te(),n=g(s);if(i=arguments,r=this,l=s,n){if(void 0===o)return u=e=l,o=setTimeout(f,t),d?_(e):a;if(h)return clearTimeout(o),o=setTimeout(f,t),_(l)}return void 0===o&&(o=setTimeout(f,t)),a}return t=tm(t)||0,e6(s)&&(d=!!s.leading,n=(h="maxWait"in s)?tb(tm(s.maxWait)||0,t):n,c="trailing"in s?!!s.trailing:c),m.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},m.flush=function(){return void 0===o?a:p(te())},m},tE=function(e,t,s){var i=!0,r=!0;if("function"!=typeof e)throw TypeError("Expected a function");return e6(s)&&(i="leading"in s?!!s.leading:i,r="trailing"in s?!!s.trailing:r),tv(e,t,{leading:i,maxWait:t,trailing:r})};let tS="ristrettoWasRestarted",tR=0,tT=0,tL=class{constructor(e){this._shouldSetNextUpdateVideoDurationId=!0,this._config={},this._logger=eO("VideoElementController - TimeUpdateController"),this._onNativeTimeUpdateHandlerThrottled=tE(this._onNativeTimeUpdateHandler,2e3,{trailing:!1}),this._eventsMap={[ee.TIME_UPDATE_NATIVE]:this._onNativeTimeUpdateHandlerThrottled,[ee.DESTROY]:this._destroy},this._logger.info("Created"),this._logger.debug("Initial state",e.state),this._logger.debug("Initial props",e),this._state=e.state,this._props=e,this._eventBus=e.eventBus}setConfig(e){this._logger.debug("Config update received, the new one:",e);let t=e.timeoutUpdateStatusPlaying!==this._config.timeoutUpdateStatusPlaying;this._config=e,t&&(this._eventsMap[ee.TIME_UPDATE_NATIVE]=tE(this._onNativeTimeUpdateHandler,e.timeoutUpdateStatusPlaying,{trailing:!1}),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap}),this.init())}init(){this._logger.info("Initialization requested, attaching eventBus listeners"),this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}startTimeUpdate(){if(this._logger.debug("Starting time update"),this._stopTimeUpdate(),!this._shouldSetNextUpdateVideoDurationId||!this._config){this._shouldSetNextUpdateVideoDurationId=!0;return}this._updateVideoDurationId=setTimeout(this._onTimeUpdate,this._config.timeoutUpdateVideoDuration),this._publishUpdatePlayerResolutionIfNeeded()}_onNativeTimeUpdateHandler(e){if(this._logger.debug("Native video timeUpdate caught"),e?.originalEvent?.defaultPrevented)return;let t=this._props.getVideoElement(),{canPlay:s,isPlaying:i,isLoading:r,isRestarted:n}=this._state.getState();if(this._publishUpdatePlayerResolutionIfNeeded(),!s){this._logger.verbose("CanPlay shared state is false. Skipping");return}this._eventBus.publish(ee.RESET_CHECKING_AUTOPLAY_COUNT,{});let a=tR!==t?.currentTime;this._logger.verbose(`Video current time is ${a?"":"not"} changed`),a?(this._eventBus.publish(ee.CANCEL_RESET_STREAM,{}),!ej.safari15OrHigher||n||localStorage?.getItem(tS)||(localStorage.setItem(tS,"1"),this._eventBus.publish(ee.RESTART,{})),t&&(tR=t.currentTime),(!i||r)&&this._eventBus.publish(ee.PLAYING,{})):r?this._eventBus.publish(ee.VIDEO_RESET,{}):this._eventBus.publish(ee.LOADING,{})}_stopTimeUpdate(){this._logger.debug("Stopping time update"),clearTimeout(this._updateVideoDurationId)}_onTimeUpdate(){if(this._logger.debug("Time updated"),!this._state.getState().canPlay){this.startTimeUpdate();return}let e=this._props.getVideoElement();e&&tT!==e.currentTime&&(tT=e.currentTime),this.startTimeUpdate()}_publishUpdatePlayerResolutionIfNeeded(){this._logger.debug("Setting new resolution if changed");let e=this._props.getVideoElement();if(e){let{videoWidth:t,videoHeight:s}=e,{videoElementResolution:i}=this._state.getState();this._logger.verbose(`Stored resolution is ${i?.width}x${i?.height}, current is ${t}x${s}`),(!i||i.height!==s||i.width!==t)&&this._config.minimalPossibleVideoDimension&&Math.min(s,t)>this._config.minimalPossibleVideoDimension&&this._eventBus.publish(ee.UPDATE_PLAYER_RESOLUTION,{width:t,height:s})}}_destroy(){this._logger.info("Destroying"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap}),this._shouldSetNextUpdateVideoDurationId=!1,this._stopTimeUpdate()}};eP([eA],tL.prototype,"init",null),eP([eA],tL.prototype,"startTimeUpdate",null),eP([eA],tL.prototype,"_onNativeTimeUpdateHandler",null),eP([eA],tL.prototype,"_stopTimeUpdate",null),eP([eA],tL.prototype,"_onTimeUpdate",null),eP([eA],tL.prototype,"_publishUpdatePlayerResolutionIfNeeded",null),eP([eA],tL.prototype,"_destroy",null);let tA=class{constructor(e){this._config={},this._logger=eO("VideoElementController - VideoEventsHandler"),this._timeUpdateEventWasLogged=!1,this._eventsMap={[ee.VIDEO_ELEMENT_RECREATED]:this._handleVideoElementRecreated,[ee.DESTROY]:this._handleDestroy},this._onVideoClick=e=>{this._logger.verbose('"click" video native event fired'),this._handleNativeEvent(e),this._eventBus.publish(ee.CLICK,{originalEvent:e})},this._onSeeked=e=>{this._logger.verbose('"seeked" video native event fired'),this._handleNativeEvent(e),this._eventBus.publish(ee.FORCE_PLAY_AFTER_PAUSE,{reason:"seeked video native event"})},this._onRateChange=e=>{this._logger.verbose('"ratechange" video native event fired'),this._handleNativeEvent(e),e.target&&!e.target.playbackRate&&this._eventBus.publish(ee.FORCE_PLAY_AFTER_PAUSE,{reason:"video playbackRate is 0"})},this._onCanPlayThrough=e=>{this._logger.verbose('"canplaythrough" video native event fired');let t=this._state.getState();this._handleNativeEvent(e),(t.isStalled||t.isWaiting)&&this._eventBus.publish(ee.FORCE_PLAY_AFTER_PAUSE,{reason:"canplaythrough video native event fired, and video is in the state of either stalled or waiting"})},this._onPlayingHandler=e=>{this._logger.verbose('"playing" video native event fired'),this._logger.info("Video has started playing"),this._handleNativeEvent(e),this._eventBus.publish(ee.PLAYING,{isAutoplay:!this._state.getState().isAutoplayError})},this._onAbortHandler=e=>{this._logger.verbose('"abort" video native event fired'),this._handleNativeEvent(e),e.defaultPrevented||this._eventBus.publish(ee.LOADING,{})},this._onPauseHandler=e=>{this._logger.verbose('"pause" video native event fired'),this._handleNativeEvent(e),this._eventBus.publish(ee.VIDEO_PAUSE,{}),this._eventBus.publish(ee.FORCE_PLAY_AFTER_PAUSE,{reason:"pause video event fired (most likely user paused the video manually)"})},this._onCanPlayHandler=e=>{this._logger.verbose('"canplay" video native event fired'),this._handleNativeEvent(e),e.defaultPrevented||(this._state.setState({canPlay:!0}),this._eventBus.publish(ee.CAN_PLAY,{}))},this._onErrorHandler=e=>{if(this._logger.error('"error" video native event fired',{error:e}),this._handleNativeEvent(e),this._eventBus.publish(ee.ERROR,{originalEvent:e}),!e.defaultPrevented){let{MEDIA_ERR_SRC_NOT_SUPPORTED:e}=MediaError,t=this._props.getVideoElement()?.error;t?.code!==e&&(this._logger.verbose("Video element error is not of MEDIA_ERR_SRC_NOT_SUPPORTED kind. Requesting reset"),this._eventBus.publish(ee.VIDEO_RESET,{}))}},this._onTimeUpdateHandler=e=>{this._handleNativeEvent(e),this._timeUpdateEventWasLogged||(this._logger.verbose('"timeupdate" video native event fired for the first time'),this._timeUpdateEventWasLogged=!0),this._eventBus.publishSync(ee.TIME_UPDATE_NATIVE,{originalEvent:e})},this._onLoadStartHandler=e=>{this._handleNativeEvent(e),this._logger.verbose('"loadstart" video native event fired');let{timeoutUpdateStream:t}=this._config;this._eventBus.publish(ee.LOADING,{}),this._eventBus.publish(ee.STREAM_RESET,{reason:"onLoadStartHandler",timeout:t})},this._onLoadedDataHandler=e=>{this._logger.verbose('"loadeddata" video native event fired'),this._handleNativeEvent(e),this._eventBus.publish(ee.LOADED,{})},this._onWaiting=e=>{this._logger.verbose('"waiting" video native event fired');let{timeoutWaitingStream:t}=this._config;this._handleNativeEvent(e),this._eventBus.publish(ee.WAITING,{}),this._eventBus.publish(ee.LOADING,{}),this._eventBus.publish(ee.STREAM_RESET,{reason:"onWaiting",timeout:t})},this._onStalled=e=>{this._logger.verbose('"stalled" video native event fired');let{timeoutWaitingStream:t}=this._config;this._handleNativeEvent(e),this._eventBus.publish(ee.STALLED,{}),this._eventBus.publish(ee.STREAM_RESET,{reason:"onStalled",timeout:t})},this._onEndFullscreenHandler=e=>{this._handleNativeEvent(e)},this._props=e,this._state=e.state,this._eventBus=e.eventBus,this.init()}setConfig(e){this._config=e}init(){this._eventBus.toggleSubscriptionBulk({action:"subscribe",callbacks:this._eventsMap})}toggleEvents(e){let t=this._props.getVideoElement();if(!t)return;let s="attach"===e?"addEventListener":"removeEventListener";t[s]("click",this._onVideoClick),t[s]("playing",this._onPlayingHandler),t[s]("abort",this._onAbortHandler),t[s]("pause",this._onPauseHandler),t[s]("canplay",this._onCanPlayHandler),t[s]("error",this._onErrorHandler),t[s]("timeupdate",this._onTimeUpdateHandler),t[s]("loadstart",this._onLoadStartHandler),t[s]("loadeddata",this._onLoadedDataHandler),t[s]("waiting",this._onWaiting),t[s]("stalled",this._onStalled),t[s]("canplaythrough",this._onCanPlayThrough),t[s]("seeked",this._onSeeked),t[s]("ratechange",this._onRateChange),t[s]("webkitendfullscreen",this._onEndFullscreenHandler),"addEventListener"===s?this._logger.verbose("event listeners are ATTACHED to the video element"):this._logger.verbose("event listeners are DETACHED from the video element")}_handleVideoElementRecreated(){this.toggleEvents("attach")}_handleDestroy(){this.toggleEvents("detach"),this._eventBus.toggleSubscriptionBulk({action:"unsubscribe",callbacks:this._eventsMap})}_handleNativeEvent(e){this._eventBus.publishSync(ee.NATIVE_EVENT,{eventName:e.type,event:e})}};eP([eA],tA.prototype,"init",null),eP([eA],tA.prototype,"_handleVideoElementRecreated",null),eP([eA],tA.prototype,"_handleDestroy",null);let tP={canPlay:!1,isLoading:!0,isError:!1,isAutoplayError:!1,isPaused:!1,isPlaying:!1,isRestarted:!1,isStalled:!1,isWaiting:!1,isDestroyed:!1,videoPlaybackState:X.IDLE,startedPlaying:!1},tC=class{constructor(e){this._initState={...e},this._state={...e}}setState(e,t){Object.assign(this._state,e),t&&t(this._state)}getState(){return this._state}resetState(){this.setState(this._initState)}},tB=class{constructor(){this._loggerTransport=new eI,this._logger=eO("VideoElementController"),this._config={...eF.videoElementControllerConfig},this.attachVideoElementEvents=()=>{this._logger.debug("Attach event listeners"),this._eventsHandler.toggleEvents("attach"),this._timeUpdateController.startTimeUpdate()},this.detachVideoElementEvents=()=>{this._logger.debug("Detach event listeners"),this._eventsHandler.toggleEvents("detach")},this._updated=()=>{this._eventBus.publish(ee.UPDATED,{})},this._logger.info("Created"),this._logger.debug("Initial config",this._config),this._eventBus=new eg,this._createControllers()}addEventListener(e,t){this._logger.verbose(`Attaching ${e} event listener`),this._customEventsEmitter.addEventListener(e,t)}removeEventListener(e,t){this._logger.verbose(`Detaching ${e} event listener`),this._customEventsEmitter.removeEventListener(e,t)}getIsPlaying(){return this._state.getState().isPlaying}getVideoElement(){return this._state.getState().videoElement}getCanvasElement(){return this._state.getState().canvasElement}updateConfig(e){this._config={...this._config,...e},this._logger.debug("Config update received, the new one: ",this._config),e.isRemote&&this.attachVideoElementEvents(),this._syncConfig()}setVideoElement(e){this._logger.info("Video element set",e),this._renderController.setVideoElement(e),this.attachVideoElementEvents()}createVideoElement(){return this._logger.info("Creating video element"),this._renderController.createVideoElement(),this.getVideoElement()}setStream(e){if(this._logger.info("Setting media stream"),this._state.getState().stream===e){this._logger.verbose("Previous stream is equal to the new one. Skipping.");return}return e?this._streamController.updateMediaStream(e):this._streamController.removeMediaStream(),this._updated(),this._state.setState({stream:e}),this}renderVideoInto(e){this._logger.info("Rendering video element into conatiner",e),this._renderController.renderVideoInto(e)}setVolume(e){this._logger.info("Setting volume of the video element",{volume:e}),this._eventBus.publish(ee.SET_VOLUME,{volume:e})}getState(){return this._state.getState()}destroy(){this._logger.info("Destroying"),this._config={...eF.videoElementControllerConfig},this.detachVideoElementEvents(),this._streamController.removeMediaStream(),this._renderController.destroy(),this._eventBus.publishSync(ee.DESTROY,{}),this._logger.info("VideoElementController was destroyed"),this._loggerTransport?.destroy()}reinit(){this._logger.info("Reinit requested"),[this._autoplayController,this._customEventsEmitter,this._playbackController,this._streamController,this._stateController,this._timeUpdateController,this._renderController,this._eventsHandler].forEach(e=>{e&&e.init()}),this.attachVideoElementEvents(),this._logger.info("VideoElementController was reinited")}setLoggerLevels(e,t=[],s=[]){this._logger.info("Setting new log level",{levels:e}),this._loggerTransport&&(this._loggerTransport.destroy(),this._loggerTransport=null),e.length&&(this._loggerTransport=new eI(e,t,s))}_syncConfig(){this._logger.verbose("Sycronizing configs across all controllers"),this._autoplayController?.setConfig(this._config),this._eventsHandler.setConfig(this._config),this._streamController.setConfig(this._config),this._timeUpdateController.setConfig(this._config),this._renderController.setConfig(this._config),this._stateController.setConfig(this._config)}_createControllers(){this._logger.verbose("Creating all controllers"),this._state=new tC(tP);let e={getVideoElement:this.getVideoElement,state:this._state,eventBus:this._eventBus};this._autoplayController=new ex(e),this._customEventsEmitter=new eG(e),this._eventsHandler=new tA(e),this._playbackController=new eJ(e),this._streamController=new e8(e),this._stateController=new e4(e),this._timeUpdateController=new tL(e),this._renderController=new e3(e),this._logger.verbose("Controllers created")}};eP([eA],tB.prototype,"addEventListener",null),eP([eA],tB.prototype,"removeEventListener",null),eP([eA],tB.prototype,"getIsPlaying",null),eP([eA],tB.prototype,"getVideoElement",null),eP([eA],tB.prototype,"getCanvasElement",null),(f=et||(et={}))[f.FATAL=0]="FATAL",f[f.ERROR=1]="ERROR",f[f.WARN=2]="WARN",f[f.INFO=3]="INFO",f[f.DEBUG=4]="DEBUG",f[f.VERBOSE=5]="VERBOSE",et.FATAL,et.ERROR,et.WARN,et.INFO,et.DEBUG,et.VERBOSE,et.FATAL,et.WARN,et.ERROR,et.INFO,et.DEBUG,et.VERBOSE,(p=es||(es={}))[p.MEDIA_DEVICES_UPDATED=0]="MEDIA_DEVICES_UPDATED";let tO=()=>{let e=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices)||navigator.getUserMedia&&eR(navigator.getUserMedia.bind(navigator))||navigator.webkitGetUserMedia&&eR(navigator.webkitGetUserMedia.bind(navigator))||navigator.mozGetUserMedia&&eR(navigator.mozGetUserMedia.bind(navigator));return t=>e.call(navigator,t)},tD=e=>!!e&&("boolean"==typeof e?e:!!e.deviceId&&{deviceId:ej.safari?e.deviceId:{exact:e.deviceId},channelCount:2}),tw=(e,t)=>{if(!e)return!1;if("boolean"==typeof e)return!0;let s=e.width&&e.height?Number(e.width)/Number(e.height):t.baseAspectRatio,i={};return e.frameRate&&(i.frameRate={ideal:e.frameRate,min:15}),e.facingMode&&navigator.mediaDevices.getSupportedConstraints().facingMode&&(i.facingMode={exact:e.facingMode}),e.width&&(i.width={ideal:e.width}),e.height&&(i.height={ideal:e.height}),e.width&&e.height&&s&&(i.aspectRatio=s),e.deviceId&&(i.deviceId=ej.safari?e.deviceId:{exact:e.deviceId}),e.width&&e.height&&!i.facingMode&&(i.advanced=[{width:{min:e.width-t.sizeThreshold,max:e.width+t.sizeThreshold},height:{min:e.height-t.sizeThreshold,max:e.height+t.sizeThreshold}},{aspectRatio:s}]),0!==Object.keys(i).length&&i};(m=ei||(ei={})).VIDEO_INPUT="videoinput",m.AUDIO_INPUT="audioinput",m.AUDIO_OUTPUT="audiooutput";let tM=(e,t)=>e.filter(e=>e.kind===t),tI=async()=>{let e=await navigator.mediaDevices.enumerateDevices();return{audioInputs:tM(e,ei.AUDIO_INPUT),audioOutputs:tM(e,ei.AUDIO_OUTPUT),videoInputs:tM(e,ei.VIDEO_INPUT)}};(b=er||(er={})).SYSTEM_PERMISSION_DENIED="SystemPermissionDenied",b.USER_PERMISSION_DENIED="UserPermissionDenied",b.COULD_NOT_START_VIDEO_SOURCE="CouldNotStartVideoSource",b.GENERIC="Generic";let tF=async e=>new Promise((t,s)=>{navigator.mediaDevices.getUserMedia(e??{audio:!0,video:!0}).then(e=>{e.getTracks().forEach(e=>{e.stop()}),t(!0)}).catch(e=>{let t=e.name,i=e.message,r=er.GENERIC;ej.chrome?"NotAllowedError"===t?"Permission denied by system"===i?r=er.SYSTEM_PERMISSION_DENIED:"Permission denied"===i&&(r=er.USER_PERMISSION_DENIED):"NotReadableError"===t&&(r=er.COULD_NOT_START_VIDEO_SOURCE):ej.safari?"NotAllowedError"===t&&(r=er.USER_PERMISSION_DENIED):ej.edge?"NotAllowedError"===t?r=er.USER_PERMISSION_DENIED:"NotReadableError"===t&&(r=er.COULD_NOT_START_VIDEO_SOURCE):ej.firefox&&("NotFoundError"===t?r=er.SYSTEM_PERMISSION_DENIED:"NotReadableError"===t?r=er.SYSTEM_PERMISSION_DENIED:"NotAllowedError"===t?r=er.USER_PERMISSION_DENIED:"AbortError"===t&&(r=er.COULD_NOT_START_VIDEO_SOURCE)),s({type:r,name:e.name,message:e.message})})});(y=en||(en={})).LIVE="live",y.ENDED="ended";let tN=e=>{if(!e)return!0;let{muted:t,enabled:s,readyState:i}=e;return t||!s||i===en.ENDED},tk=e=>!e.active||e.getTracks().every(tN),tV=e=>{e&&(e.getTracks().forEach(t=>{t.stop(),e.removeTrack(t)}),e.stop&&e.stop())};eP([eA],(class extends eq{constructor(){super(),this._currentMediaStream=null,this._mediaCheckCache=null,this._mediaDevices=null,navigator.mediaDevices.addEventListener("devicechange",this._onDevicesChanged)}destroy(){navigator.mediaDevices.removeEventListener("devicechange",this._onDevicesChanged),this._stopCurrentStream()}async requestPermissions(){if(this._mediaCheckCache)return this._mediaCheckCache;try{return await tF({video:!0,audio:!0}),this._mediaCheckCache={video:{isAvailable:!0,error:null},audio:{isAvailable:!0,error:null}},this._mediaCheckCache}catch(t){let e={video:{isAvailable:!1,error:null},audio:{isAvailable:!1,error:null}};return e.video=await this._checkKindPermissions({video:!0,audio:!1}),e.audio=await this._checkKindPermissions({video:!1,audio:!0}),this._mediaCheckCache=e,this._mediaCheckCache}}async getVideoDevices(){return(await this._getMediaDevices()).videoInputs}async getAudioInputDevices(){return(await this._getMediaDevices()).audioInputs}async getAudioOutputDevices(){return(await this._getMediaDevices()).audioOutputs}async getMediaStream(e,t){let s={};return(e.audio&&(s.audio=tD(e.audio)),e.video&&(s.video=tw(e.video,t)),this._currentMediaStream)?!tk(this._currentMediaStream.stream)&&await this._isCurrentStreamSatisfiesConstraints(s)?this._currentMediaStream.stream:(await this._stopCurrentStream(),this._createNewStream(s)):this._createNewStream(s)}async _stopCurrentStream(){this._currentMediaStream&&(await tV(this._currentMediaStream.stream),this._currentMediaStream=null)}async _checkKindPermissions(e){let t={isAvailable:!1,error:null};try{t.isAvailable=await tF(e)}catch(e){t.isAvailable=!1,t.error=e}return t}async _getMediaStream(e){let t=tO(),s=await t(e);return this._currentMediaStream={constraints:e,stream:s},this._currentMediaStream.stream}async _createNewStream(e){try{return await this._getMediaStream(e)}catch(t){if("OverconstrainedError"===t.name&&"deviceId"===t.constraint){let t={...e,audio:!0};return await this._getMediaStream(t)}throw t}}async _getMediaDevices(){return this._mediaDevices||(this._mediaDevices=await tI()),this._mediaDevices}async _isCurrentStreamSatisfiesConstraints(e){if(!this._currentMediaStream)return!1;try{if(e.video){let t=this._currentMediaStream.stream.getVideoTracks()[0];if(!t&&e.video||t&&!e.video||"object"==typeof e.video&&e.video.deviceId&&t.getCapabilities().deviceId!==e.video.deviceId)return!1;t&&"boolean"!=typeof e.video&&await t.applyConstraints(e.video)}}catch(e){return!1}try{if(e.audio){let t=this._currentMediaStream.stream.getAudioTracks()[0];if(!t&&e.audio||t&&!e.audio||"object"==typeof e.audio&&e.audio.deviceId&&t.getCapabilities().deviceId!==e.audio.deviceId)return!1;t&&"boolean"!=typeof e.audio&&await t.applyConstraints(e.audio)}}catch(e){return!1}return!0}async _onDevicesChanged(){this._mediaDevices=null;let e=await this._getMediaDevices();this.emitEvent(es.MEDIA_DEVICES_UPDATED,e)}}).prototype,"_onDevicesChanged",null);let tU=e=>{if(!e)return{};try{let t=new URL(e).pathname.split("/"),s=t[2],i=t[t.length-1],r=i.match(/\d+_(\w+)/)?.[1]||"source",n="master"===t[3];return{streamId:s,resolution:r,isMaster:n}}catch(e){return{}}};var tx=((v={}).THROUGHPUT_ESTIMATOR="throughputEstimator",v.DROPPED_FRAMES_ESTIMATOR="droppedFramesEstimator",v.SWITCH_HISTORY="switchHistory",v.INSUFFICIENT_BUFFER="insufficientBuffer",v.MINIMAL_BUFFER_TO_INCREASE="minimalBufferToIncrease",v.DELTA_BUFFER="deltaBuffer",v),U=k("a8VW4"),tq=((E={}).WAIT_FOR_PREFETCH_SEGMENT="waitForSegment",E.WAIT_FOR_PLAYLIST="waitForPlaylist",E);let tG={playlistLoadingTimeout:2500,forceStaticPlaylistLoadingTimeout:!1,lowLatencyMode:!0,equalPlaylistsAmountToDecline:10,blockingMode:tq.WAIT_FOR_PLAYLIST,maxVODPlaylistLoadingRetries:3,maxVODFragmentLoadingRetries:3,baseVODPlaylistRetryTimeout:500,baseVODFragmentRetryTimeout:5e3,VODLoadNextSegmentThreshold:5e3,disableTimeoutsInVOD:!0,retryLowLatencyPlaylistTimeout:1e3,targetBufferMultiplier:1,disableRotateTimeoutIncrease:!0,shouldLogFragmentsHistory:!1,workerMode:!0,partHoldBack:void 0,additionalStartParts:2,sendCustomRefererHeader:!1},tW=(tq.WAIT_FOR_PLAYLIST,tq.WAIT_FOR_PREFETCH_SEGMENT,["error","fatal"]),{ConfigConsumer:tH,setConfig:t$}=eL({playlistLoader:tG,fragmentLoader:{fragmentLoadingTimeout:2500,workerMode:!0},resolutionsManager:{autoloadLowestResolution:!0,initialResolutionWidth:0,initialResolutionHeight:720,initialResolutionBitrate:0,initialResolutionBitrateThreshold:1e5,maxPlaylistTimeDifference:4e4,awaitForSegmentEndToSwitch:!0,awaitForSegmentEndToSwitchManual:!1,recreateSourceBufferOnResolutionChange:!1,useFallbackResolutionIfResolutionNotFound:!0},bufferController:{checkMetricsInterval:150,bufferStallThreshold:.2,maxBackBufferAmount:1e4,bufferEdgeThreshold:.3,endOfRangeThreshold:.4,nudgePlaybackAmount:.1,numberOfCandidatesToDetectGap:2,numberOfFragmentToKeep:2,recreateSourceBufferOnResolutionChange:!1,saveLastSegmentsCount:3,sourceBufferStuckTimeout:1e3},throughputHistory:{ewmaFastAlpha:.9,ewmaSlowAlpha:.2,ignorePlaylistsMetrics:!0},abr:{enabledABRRules:["throughputEstimator","switchHistory","minimalBufferToIncrease","insufficientBuffer"],cooldownPeriod:1e4,minimalBufferAmountToSwitchUp:500},switchHistory:{banResolutionDuration:7e3},throughputEstimator:{optimalResolutionLowerBound:.65,optimalResolutionUpperBound:.88,amountOfFragmentToBecomeConfident:10},droppedFramesEstimator:{resetHistoryTimeout:3e5,optimalDroppedFramesFraction:.1,minimalFramesPlayed:200},fragmentParser:{workerMode:!1},debugger:{enableRemoteDebugging:!1,debuggerUrl:"wss://doppio-player-debug.stripcdn.com",maxWSConnectionRetries:3,modulesStateGatheringPeriod:1e3,enableLifecycleEvents:!0},insufficientBufferEstimator:{minimalBufferAmount:.1,ignoreMetricsBeforeBufferExceedsMinimal:!0,switchToMinimalResolution:!1},minimalBufferToIncreaseEstimator:{minimalBufferAmount:500},deltaBufferEstimator:{bufferDeltaFractionToDetectFall:.1,numberOfFallsToDetect:2},playbackStateController:{autoPlay:!1,syncToLiveEdge:!1,syncToLiveDelta:1,playingTimeFractionCollectionWindow:1e5},targetBufferIncreaser:{bufferAmountToIncrease:200,bufferAmountThreshold:300},targetBufferDecreaser:{periodOfEventsToCancelDecrease:1e4},playbackSpeedActuator:{maxPlaybackRate:1.05,minPlaybackRate:.9},playbackSpeedWatcher:{maxLiveSyncThreshold:.4,minLiveSyncThreshold:.3,maxTargetBufferMultiplier:3,targetBufferInitialMultiplier:1},bufferStallsDetector:{bufferAmountToDetectStall:.1},fragmentsFilter:{reportInconsistentTracks:!0,filterOutInconsistentTracks:!1},fragmentBuffer:{numberOfFragmentsToKeepInBuffer:3,baseChunksSaverUrl:"chunks.doppiostreams.com",saveProbability:.05}}),tj=class extends tH{};var tK=((S={}).OK="ok",S.ERROR="error",S);let tY={playlistType:{multivariantDetected:"basePlaylistRotator.playlistType.multivariantDetected",simpleDetected:"basePlaylistRotator.playlistType.simpleDetected",llDetected:"basePlaylistRotator.playlistType.llDetected",vodDetected:"basePlaylistRotator.playlistType.vodDetected"},playlists:{playlistRequested:"basePlaylistRotator.playlists.playlistRequested",playlistLoaded:"basePlaylistRotator.playlists.playlistLoaded",playlistLoadingError:"basePlaylistRotator.playlists.playlistLoadingError",playlistParsed:"basePlaylistRotator.playlists.playlistLoadingError",playlistInfo:"basePlaylistRotator.playlists.playlistInfo",vodFragmentsInfo:"basePlaylistRotator.playlists.VODFragmentsInfo",independenceTypeUpdate:"basePlaylistRotator.playlists.independenceTypeUpdate",renditionReportsUpdated:"basePlaylistRotator.playlists.renditionReportsUpdated",lastPlaylistOfSegmentLoaded:"basePlaylistRotator.playlists.lastPlaylistOfSegmentLoaded"},fragments:{fragmentsDetected:"basePlaylistRotator.fragments.fragmentsDetected",requestReleaseFromCache:"basePlaylistRotator.fragments.requestReleaseFromCache",periodFragmentsFound:"basePlaylistRotator.fragments.periodFragmentsFound"}};var tQ=k("eQOGK");let tX=class extends tj{constructor(e){super("deltaBufferEstimator",e),this.status="Idle",this.state=tK.OK,this.additionalInfo={},this.groups=["abr"],this._numberOfFalls=0,this._lastKnownBufferAmount=0,this._currentBufferAmount=0,this._onPlaylistParsedListener=this._eventBus.subscribe(tY.playlists.playlistInfo,this._onPlaylistParsed)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onPlaylistParsedListener),this.reset()}reset(){this._numberOfFalls=0}getNextEstimatedResolution(e,t,s){return this._currentBufferAmount=s.bufferAmount,!t||this._numberOfFallse===t.name)-1)]}_handleConfigUpdated(){this._numberOfFalls=0}_onPlaylistParsed(){let{_currentBufferAmount:e,_lastKnownBufferAmount:t}=this;this._lastKnownBufferAmount=e,e>t&&(this._numberOfFalls=0);let s=t/e;s>1+this.config.bufferDeltaFractionToDetectFall&&this._numberOfFalls++,this.additionalInfo={numberOfFalls:this._numberOfFalls,bufferDelta:s}}};(0,U.__decorate)([tQ.default],tX.prototype,"_onPlaylistParsed",null);var U=(k("a8VW4"),k("a8VW4"));let tz={requestResetWithOverplay:"buffer.requestResetWithOverplay",bufferMetricsAvailable:"buffer.metricsAvaialable",playbackStallChanged:"buffer.playbackStallChanged",requestSourceBufferOperation:"buffer.requestSourceBufferOperation",playbackStateChanged:"buffer.playbackStateChanged",endOfStreamReached:"buffer.endOfStreamReached",fragmentAdded:"buffer.fragmentAdded",changeCodec:"buffer.changeCodec",sourceBufferStuck:"buffer.sourceBufferStuck"},tJ={resolutionsAvailable:"resolutionsManager.resolutionsAvailable",resolutionChanged:"resolutionManager.resolutionChanged",resolutionAutoChanged:"resolutionManager.resolutionAutoChanged",requestResolutionChange:"resolutionManager.requestResolutionChange",requestRestartFromMain:"resolutionManager.requestRestartFromMain",resolutionNotFound:"resolutionManager.resolutionNotFound"};var tQ=k("eQOGK");let tZ=class{constructor(e){this._droppedFrames={},this._currentResolution=null,this._isFirstMetricsOfResolution=!0,this._eventBus=e,this._onBufferMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsReady),this._onResolutionChangedListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChanged)}destroy(){this._eventBus.unsubscribe(this._onBufferMetricsReadyListener),this._eventBus.unsubscribe(this._onResolutionChangedListener),this.reset()}getCurrentResolutionHistory(){return this._currentResolution&&this._droppedFrames[this._currentResolution.name]?this._droppedFrames[this._currentResolution.name]:null}getResolutionHistoryByName(e){return this._droppedFrames[e]||null}reset(){this._droppedFrames={},this._currentResolution=null,this._isFirstMetricsOfResolution=!0}_onBufferMetricsReady(e){if(!this._currentResolution)return;let{name:t}=this._currentResolution;if(this._droppedFrames[t]||(this._droppedFrames[t]={droppedFramesNumber:0,totalFramesNumber:0}),this._isFirstMetricsOfResolution){this._isFirstMetricsOfResolution=!1;return}this._droppedFrames[t].droppedFramesNumber+=e.droppedVideoFramesDelta,this._droppedFrames[t].totalFramesNumber+=e.totalVideoFramesDelta}_onResolutionChanged(e){this._currentResolution?.name!==e.name&&(this._currentResolution=e,this._isFirstMetricsOfResolution=!0)}};(0,U.__decorate)([tQ.default],tZ.prototype,"_onBufferMetricsReady",null),(0,U.__decorate)([tQ.default],tZ.prototype,"_onResolutionChanged",null);var tQ=k("eQOGK");let t0=class extends tj{constructor(e){super("droppedFramesEstimator",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={droppedFramesByResolution:{}},this.groups=["abr"],this._lastClearTs=0,this._droppedFramesHistory=new tZ(this._eventBus),this._onMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onMetricsReady)}destroy(){super.destroy(),this._droppedFramesHistory.destroy(),this._eventBus.unsubscribe(this._onMetricsReadyListener)}reset(){this._droppedFramesHistory.reset()}getNextEstimatedResolution(e){let{minimalFramesPlayed:t}=this.config;return e.find(({name:e})=>{let s=this._droppedFramesHistory.getResolutionHistoryByName(e);return this.additionalInfo.droppedFramesByResolution[e]=s,!s||s.totalFramesNumberthis.config.resetHistoryTimeout&&(this._droppedFramesHistory.reset(),this._lastClearTs=e.currentTimestamp)}};(0,U.__decorate)([tQ.default],t0.prototype,"_onMetricsReady",null);let t1=class extends tj{constructor(e){super("insufficientBufferEstimator",e),this.status="Idle",this.state=tK.OK,this.groups=["abr"],this.additionalInfo={},this._hasPassedMinimalBuffer=!1}destroy(){super.destroy()}reset(){this._hasPassedMinimalBuffer=!1}getNextEstimatedResolution(e,t,s){let i=s.bufferAmount>this.config.minimalBufferAmount;!this._hasPassedMinimalBuffer&&i&&(this._hasPassedMinimalBuffer=!0);let r=!this.config.ignoreMetricsBeforeBufferExceedsMinimal||this._hasPassedMinimalBuffer;if(this.additionalInfo.isResultsConfident=r,this.additionalInfo.isBufferExceedsMinimal=i,this.additionalInfo.hasPassedMinimalBuffer=this._hasPassedMinimalBuffer,!r||i||!t)return null;this._hasPassedMinimalBuffer=!1;let n=e.slice(-1)[0],a=t.url===n.url?t:e[e.findIndex(({name:e})=>e===t.name)+1];return this.config.switchToMinimalResolution?n:a}_handleConfigUpdated(){this._hasPassedMinimalBuffer=!1}},t2=class extends tj{constructor(e){super("minimalBufferToIncreaseEstimator",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["abr"]}destroy(){super.destroy()}reset(){}getNextEstimatedResolution(e,t,s){return 1e3*s.bufferAmount>this.config.minimalBufferAmount?null:t}_handleConfigUpdated(){}};var U=k("a8VW4"),tQ=k("eQOGK");let t3=class extends tj{constructor(e){super("switchHistory",e),this._lastSelectedResolution=null,this._bannedResolutions=[],this._onResolutionSelectedListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChanged),this._onMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._checkBanedResolutions)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onResolutionSelectedListener),this._eventBus.unsubscribe(this._onMetricsReadyListener),this.reset()}reset(){this._bannedResolutions=[]}getBannedResolutions(){return this._bannedResolutions.map(({resolution:e})=>e)}_handleConfigUpdated(e){e.banResolutionDuration&&this._checkBanedResolutions()}_onResolutionChanged(e){if(!this._lastSelectedResolution||this._lastSelectedResolution.bitratee.bitrate&&(this._bannedResolutions.push({resolution:e,bannedAt:Date.now()}),this._lastSelectedResolution=e)}_checkBanedResolutions(){if(!this._bannedResolutions.length)return;let e=Date.now();this._bannedResolutions=this._bannedResolutions.filter(({bannedAt:t})=>e-te);return this.additionalInfo.bannedResolution=t,e.find(({name:e})=>!t.includes(e))||null}};var U=(k("a8VW4"),k("a8VW4"));let t8={events:{browserRedirectDetected:"networkLoader.events.browserRedirectDetected",networkRequestSettled:"networkLoader.events.networkRequestSettled"},stats:{statsReady:"networkLoader.stats.statsEvent"}};var tQ=k("eQOGK");let t6=class{constructor(e,t,s){this._previousFastValue=null,this._previousSlowValue=null,this._eventBus=s,this._fastAlpha=e,this._slowAlpha=t}addValue(e){let{_fastAlpha:t,_slowAlpha:s}=this;this._previousFastValue=t*e+(1-t)*(this._previousFastValue||e),this._previousSlowValue=s*e+(1-s)*(this._previousSlowValue||e),this._eventBus.publish("EWMAMetrics",{fast:this._previousFastValue,slow:this._previousSlowValue})}getCurrentValue(){return this._previousSlowValue&&this._previousFastValue?Math.min(this._previousFastValue,this._previousSlowValue):0}getCurrentMaximalValue(){return this._previousFastValue&&this._previousSlowValue?Math.max(this._previousSlowValue,this._previousFastValue):0}reset(){this._previousSlowValue=null,this._previousFastValue=null}},t5=class extends tj{constructor(e){super("throughputHistory",e),this._measuredSpeedEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus),this._realSpeedEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus),this._ttfbEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus),this._onNetMetricsReadyListener=this._eventBus.subscribe(t8.stats.statsReady,this._onNetworkMetricsReady)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onNetMetricsReadyListener),this._measuredSpeedEwmaInstance.reset(),this._realSpeedEwmaInstance.reset()}getCurrentBitrateEstimate(){return{measuredSpeed:this._measuredSpeedEwmaInstance.getCurrentValue(),realSpeedWithoutTTFB:this._realSpeedEwmaInstance.getCurrentValue(),ttfb:this._ttfbEwmaInstance.getCurrentMaximalValue()}}reset(){this._measuredSpeedEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus),this._realSpeedEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus),this._ttfbEwmaInstance=new t6(this.config.ewmaFastAlpha,this.config.ewmaSlowAlpha,this._eventBus)}_handleConfigUpdated(e){(e.ewmaFastAlpha||e.ewmaSlowAlpha)&&this.reset()}_onNetworkMetricsReady(e){if(this.config.ignorePlaylistsMetrics&&"text"===e.type)return;let t=8*e.sizeInKb/((e.downloadDuration-e.ttfb)/1e3);this._measuredSpeedEwmaInstance.addValue(e.calculatedSpeed),this._realSpeedEwmaInstance.addValue(t),this._ttfbEwmaInstance.addValue(e.ttfb/1e3)}};(0,U.__decorate)([tQ.default],t5.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],t5.prototype,"_onNetworkMetricsReady",null);let t9=e=>e/1024,t7=e=>t9(e);var tQ=k("eQOGK");let se=class extends tj{constructor(e){super("throughputEstimator",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["abr"],this._isResultsConfident=!1,this._fragmentsLoadedAmount=0,this._throughputHistory=new t5(this._eventBus),this._onNetworkMetricsReadyListener=this._eventBus.subscribe(t8.stats.statsReady,this._onNetworkStatsReady)}destroy(){super.destroy(),this._throughputHistory.destroy(),this._eventBus.unsubscribe(this._onNetworkMetricsReadyListener)}reset(){this._throughputHistory.reset(),this._isResultsConfident=!1}getNextEstimatedResolution(e){let{realSpeedWithoutTTFB:t,measuredSpeed:s,ttfb:i}=this._throughputHistory.getCurrentBitrateEstimate();if(this.additionalInfo={realSpeedWithoutTTFB:t,measuredSpeed:s,ttfb:i},!e.length||!s||!this._isResultsConfident)return null;let r=t7(e[0].bitrate)/(i+t7(e[0].bitrate)/t);return t7(e[0].bitrate){let s=t7(e),r=s/(i+s/t);return r*this.config.optimalResolutionLowerBound<=s&&s<=r*this.config.optimalResolutionUpperBound})||e.find(({bitrate:e})=>t7(e)<=s*this.config.optimalResolutionLowerBound)||e.slice(-1)[0]}_handleConfigUpdated(){}_onNetworkStatsReady(e){"binary"===e.type&&!this._isResultsConfident&&(this._fragmentsLoadedAmount+=1,this._fragmentsLoadedAmount>=this.config.amountOfFragmentToBecomeConfident&&(this._isResultsConfident=!0))}};(0,U.__decorate)([tQ.default],se.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],se.prototype,"_onNetworkStatsReady",null);var tQ=k("eQOGK");let st={[tx.DROPPED_FRAMES_ESTIMATOR]:t0,[tx.THROUGHPUT_ESTIMATOR]:se,[tx.SWITCH_HISTORY]:t4,[tx.INSUFFICIENT_BUFFER]:t1,[tx.MINIMAL_BUFFER_TO_INCREASE]:t2,[tx.DELTA_BUFFER]:tX},ss=class extends tj{constructor(e){super("abr",e),this.state=tK.OK,this.status="Idle",this.groups=["general","abr"],this.additionalInfo={switchReasonHistory:[]},this._currentResolution=null,this._availableResolutions=[],this._estimators={},this._lastSwitchTime=0,this._logger=eO("Doppio - AbrController"),this._onResolutionChangedListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChanged),this._onResolutionsAvailableListener=this._eventBus.subscribe(tJ.resolutionsAvailable,this._onResolutionsAvailable),this._onMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._recalculateCurrentLevel),this._recreateEstimators(),this._lastSwitchTime=Date.now()}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onMetricsReadyListener),this._eventBus.unsubscribe(this._onResolutionChangedListener),this._eventBus.unsubscribe(this._onResolutionsAvailableListener),Object.values(this._estimators).forEach(e=>{e.destroy()}),this._estimators={}}_handleConfigUpdated(e){e.enabledABRRules&&this._recreateEstimators()}_recreateEstimators(){Object.values(this._estimators).forEach(e=>e.destroy()),this._estimators=this.config.enabledABRRules.reduce((e,t)=>(e[t]=new st[t](this._eventBus),e),{})}_recalculateCurrentLevel(e){let t=Object.entries(this._estimators).reduce((t,[s,i])=>(t[s]=i.getNextEstimatedResolution(this._availableResolutions,this._currentResolution,e),t),{});if(this.additionalInfo.estimations=Object.entries(t).reduce((e,[t,s])=>(e[t]=s?.name||"null",e),{}),Date.now()-this._lastSwitchTimee).sort((e,t)=>(e?.bitrate||0)-(t?.bitrate||0))[0];if(s&&s.name!==this._currentResolution?.name){let e=Object.entries(t).reduce((e,[t,i])=>(i?.name===s?.name&&e.push(t),e),[]);this.additionalInfo.switchReasonHistory.unshift(`${this._currentResolution?.name} -> ${s?.name}; ${e.join(",")}`),this._lastSwitchTime=Date.now(),this.additionalInfo.lastSwitchTime=this._lastSwitchTime,this.additionalInfo.lastSwitchReason=Object.entries(t).filter(([,e])=>e?.name===s?.name).map(([e])=>e).join("; "),this._logger.info(`ABR wants to change the resolution, ${this._currentResolution?.name} -> ${s?.name}`),this._eventBus.publish(tJ.requestResolutionChange,s)}}_onResolutionsAvailable(e){this._availableResolutions=e}_onResolutionChanged(e){this._currentResolution=e,Object.values(this._estimators).forEach(e=>e.reset())}get additionalModules(){return this._estimators}};(0,U.__decorate)([tQ.default],ss.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],ss.prototype,"_recalculateCurrentLevel",null),(0,U.__decorate)([tQ.default],ss.prototype,"_onResolutionsAvailable",null),(0,U.__decorate)([tQ.default],ss.prototype,"_onResolutionChanged",null);var U=(k("a8VW4"),k("a8VW4")),tQ=k("eQOGK");let si=class extends tj{constructor(e){super("bufferController",e),this._isPaused=!1,this._isInVodMode=!1,this._fragmentTimeRanges=[],this._videoElement=null,this._logger=eO("Doppio - BufferCleaner"),this._onBufferMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),this._onPeriodFragmentsFound=this._eventBus.subscribe(tY.fragments.periodFragmentsFound,this._onFragmentPeriodFound),this._onVODFragmentsInfoAvailableListener=this._eventBus.subscribe(tY.playlists.vodFragmentsInfo,this._onVODFragmentsInfoAvailable)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onPeriodFragmentsFound),this._eventBus.unsubscribe(this._onVODFragmentsInfoAvailableListener),this._eventBus.unsubscribe(this._onBufferMetricsReadyListener)}start(){this._isPaused=!1}pause(){this._isPaused=!0}setVODMode(e){this._isInVodMode=e}setVideoElement(e){this._videoElement=e}removeVideoElement(){this._videoElement=null}_handleConfigUpdated(){}_onVODFragmentsInfoAvailable(e){this._fragmentTimeRanges=e.map(({fragmentStartTS:e,fragmentEndTS:t})=>({startTS:e,endTS:t}))}_onBufferMetricsAvailable(e){if(!this._isPaused&&0!==e.bufferedTimeRanges.length&&(!this._isInVodMode||!this._fragmentTimeRanges.length)){let t=e.isPaused?[{startTS:e.currentPlaybackPosition-1,endTS:e.currentPlaybackPosition+1},{startTS:e.bufferedTimeRanges.slice(-1)[0]?.end-this.config.maxBackBufferAmount/1e3,endTS:e.bufferedTimeRanges.slice(-1)[0]?.end}]:[{startTS:e.currentPlaybackPosition-this.config.maxBackBufferAmount/1e3,endTS:e.bufferedTimeRanges.slice(-1)[0].end}];this._clearBufferWithSafetyTimeRanges(t)}}_onFragmentPeriodFound({endTsOfPeriod:e}){if(this._isPaused||!this._videoElement||this._videoElement.currentTimee.startTS-t.startTS).filter(({startTS:e,endTS:t})=>e({startTS:s>0?e[s-1].endTS:0,endTS:t.startTS})).filter(({startTS:e,endTS:t})=>e{this._eventBus.publish(tz.requestSourceBufferOperation,t=>{this._logger.verbose(`Removing buffered range ${e.startTS} -> ${e.endTS}`),t.remove(e.startTS,e.endTS)})})}};(0,U.__decorate)([tQ.default],si.prototype,"destroy",null),(0,U.__decorate)([tQ.default],si.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],si.prototype,"_onVODFragmentsInfoAvailable",null),(0,U.__decorate)([tQ.default],si.prototype,"_onBufferMetricsAvailable",null),(0,U.__decorate)([tQ.default],si.prototype,"_onFragmentPeriodFound",null);var U=k("a8VW4"),sr=((R={}).MANIFEST_LOADED="ManifestLoaded",R.FIRST_MEDIA_PLAYLIST_LOADED="FirstMediaPlaylistLoaded",R.FIRST_FRAGMENT_LOADED="FirstFragmentLoaded",R.FIRST_FRAGMENT_BUFFERED="FirstFragmentBuffered",R),sn=((T={}).MANIFEST_LOAD_ERROR="ManifestLoadError",T.PLAYLIST_LOAD_ERROR="PlaylistLoadError",T.FRAGMENT_LOAD_ERROR="FragmentLoadError",T),sa=((L={}).VARIANTS_DETECTED="variantDetected",L.RESOLUTION_CHANGED="resolutionChanged",L.METRICS_AVAILABLE="metricsAvailable",L.ERROR="error",L.MANIFEST_LOADING="manifestLoading",L.MANIFEST_LOADED="manifestLoaded",L.MANIFEST_PARSED="manifestParsed",L.LEVEL_LOADED="levelLoaded",L.LEVEL_SWITCHED="levelSwitched",L.LEVEL_SWITCHED_AUTO="levelSwitchedAuto",L.LEVEL_SWITCHING="levelSwitching",L.MEDIA_ATTACHED="mediaAttached",L.MEDIA_DETACHED="mediaDetached",L.FRAG_LOADED="fragmentLoaded",L.LEVEL_METADATA_LOADED="levelMetadataLoaded",L.STREAM_STATE_TRANSITION="streamStateTransition",L.PLAYBACK_STATE_CHANGED="playbackStateChanged",L.FRAG_BUFFERED="fragBuffered",L.DEBUGGER_CONNECTED="debuggerConnected",L.STREAM_ENDED="streamEnded",L.LIFECYCLE_EVENT="lifecycleEvent",L.LIFECYCLE_ERROR="lifecycleError",L.FRAGMENT_FILTERED_OUT="fragmentFilteredOut",L.RESOLUTION_NOT_FOUND="resolutionNotFound",L),so=((A={}).MEDIA_ERROR="mediaError",A.NETWORK_ERROR="networkError",A.PARSING_ERROR="parsingError",A),tQ=k("eQOGK");let sl=class extends tj{constructor(e){super("bufferController",e),this._sourceBuffer=null,this._opsQueue=[],this._sourceBufferStuckTimer=null,this._logger=eO("Doppio - BufferOpsQueue"),this._eventBus=e}setSourceBuffer(e){this._sourceBuffer&&this._sourceBuffer.removeEventListener("updateend",this._onBufferReady),this._sourceBuffer=e,this._sourceBuffer.addEventListener("updateend",this._onBufferReady),this._sourceBufferStuckTimer=setTimeout(()=>{this._eventBus.publish(tz.sourceBufferStuck,{})},this.config.sourceBufferStuckTimeout)}destroy(){super.destroy();try{this._disarmSourceBufferStuckTimer(),this._sourceBuffer?.removeEventListener("updateend",this._onBufferReady),this._sourceBuffer?.abort()}catch(e){this._logger.info("Source buffer cannot be aborted. Ignore it")}this._opsQueue=[]}removeSourceBuffer(e){this._sourceBuffer&&(this.immediatelyRecreateSourceBuffer(e),this._sourceBuffer.removeEventListener("updateend",this._onBufferReady),this._sourceBuffer=null)}addBufferOperation(e,t,s){if(!this._sourceBuffer){this._logger.warn(`There is no sourceBuffer defined. Operation (${s||"unknown"}) will be executed once sourceBuffer will be appended`),this._opsQueue.push({operation:e,errorHandler:t});return}if(this._sourceBuffer.updating||this._opsQueue.length>0)this._opsQueue.push({operation:e,errorHandler:t});else try{e(this._sourceBuffer)}catch(s){t?t(this._sourceBuffer,s):(this._eventBus.publish(sa.ERROR,{type:so.MEDIA_ERROR,details:s}),this._logger.error(`Cannot recreate source buffer: ${s.toString()}, ${e}`))}}immediatelyRecreateSourceBuffer(e){try{if(!this._sourceBuffer||!e||![...e.sourceBuffers].includes(this._sourceBuffer))return;this._disarmSourceBufferStuckTimer(),this._opsQueue=[],this._sourceBuffer.abort(),this._sourceBuffer.remove(0,Number.POSITIVE_INFINITY)}catch(e){this._logger.error(`Cannot recreate source buffer: ${e.toString()}`)}}_recheckQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._opsQueue.length)return;let e=this._opsQueue.shift();if(e)try{e.operation(this._sourceBuffer)}catch(t){e.errorHandler?e.errorHandler?.(this._sourceBuffer,t):(this._logger.error(`Cannot perform source buffer operation: ${t.toString()} ${e}`),this._eventBus.publish(sa.ERROR,{type:so.MEDIA_ERROR,details:t}))}!this._sourceBuffer.updating&&this._opsQueue.length&&this._recheckQueue()}_onBufferReady(){this._recheckQueue(),this._disarmSourceBufferStuckTimer()}_disarmSourceBufferStuckTimer(){this._sourceBufferStuckTimer&&clearTimeout(this._sourceBufferStuckTimer)}};(0,U.__decorate)([tQ.default],sl.prototype,"_onBufferReady",null),(0,U.__decorate)([tQ.default],sl.prototype,"_disarmSourceBufferStuckTimer",null);var U=k("a8VW4"),tQ=k("eQOGK");let su=class extends tj{constructor(e){super("bufferStallsDetector",e),this._isPrevCheckStalled=!1,this._onBufferMetricsAvailableListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onBufferMetricsAvailableListener)}_handleConfigUpdated(){}_onBufferMetricsAvailable({isStallCandidate:e,bufferedTimeRanges:t,currentPlaybackPosition:s}){let i=t.slice(-1)[0],r=i?i.end-s:0,n=e&&rs=>{t.publish(sd,{module:e,eventInfo:s,timestamp:Date.now()})};var s_=((P=s_||{}).UNKNOWN="unknown",P.GAP="gap",P.IN_RANGE="inRange",P.END_OF_RANGE="endOfRange",P);let sg=class extends tj{constructor(e){super("bufferController",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["buffer"],this._lastPlaybackPosition=0,this._videoElement=null,this._numberOfDetectedStallCandidates=0,this._logger=eO("Doppio - LiveGapController"),this._lifecycleEventReporter=sc("LiveGapController",this._eventBus),this._onBufferMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsReady)}setVideoElement(e){this._videoElement=e}removeVideoElement(){this._videoElement=null}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onBufferMetricsReadyListener)}_handleConfigUpdated(){}_checkIfJumpNeeded(e){let t=!1,s="unknown",i=this._lastPlaybackPosition!==e.currentPlaybackPosition;this._lastPlaybackPosition=e.currentPlaybackPosition,i?this._numberOfDetectedStallCandidates=0:this._numberOfDetectedStallCandidates+=1;let r=!e.bufferedTimeRanges.some(({isCurrentTimeRange:e})=>e);return!i&&this.config.numberOfCandidatesToDetectGap<=this._numberOfDetectedStallCandidates&&(this._numberOfDetectedStallCandidates=0,this._lifecycleEventReporter("Playback stalled"),this._logger.info("Playback position didnt changed since last check"),t=!0,s=e.currentTimeRange&&e.currentTimeRange.end-e.currentPlaybackPosition=e.bufferedTimeRanges.slice(-1)[0].end){this._nudgePlayback(e);return}let t=e.bufferedTimeRanges.find(({start:t})=>t>e.currentPlaybackPosition);if(!t){this._nudgePlayback(e);return}this._lifecycleEventReporter(`Jump to next range requested, jumping to ${t.start+.01}`),this._setNextPlaybackPosition(t.start+.01)}_nudgePlayback(e){if(e.isOnBufferEdge)return;let t=e.currentPlaybackPosition+this.config.nudgePlaybackAmount;this._lifecycleEventReporter("Nudge playback position"),this._setNextPlaybackPosition(t)}};(0,U.__decorate)([tQ.default],sg.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sg.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],sg.prototype,"_onBufferMetricsReady",null);var U=k("a8VW4"),tQ=k("eQOGK");let sf=class extends tj{constructor(e){super("bufferController",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["buffer"],this._videoElement=null,this._fragments=[],this._lastPlaybackPosition=0,this._numberOfDetectedStallCandidates=0,this._onBufferMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),this._onVODFragmentInfoAvailableListener=this._eventBus.subscribe(tY.playlists.vodFragmentsInfo,this._onVODFragmentsInfoAvailable)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onBufferMetricsReadyListener),this._eventBus.unsubscribe(this._onVODFragmentInfoAvailableListener)}setVideoElement(e){this._videoElement=e}removeVideoElement(){this._videoElement=null}_handleConfigUpdated(){}_onVODFragmentsInfoAvailable(e){this._fragments=e.map(({fragmentEndTS:e,fragmentStartTS:t})=>({startTs:t,endTs:e}))}_onBufferMetricsAvailable(e){if(!this._fragments.length||!e.bufferedTimeRanges||this._videoElement?.paused)return;let t=this._lastPlaybackPosition!==e.currentPlaybackPosition;this._lastPlaybackPosition=e.currentPlaybackPosition,t?this._numberOfDetectedStallCandidates=0:this._numberOfDetectedStallCandidates+=1;let s=!e.bufferedTimeRanges.some(({isCurrentTimeRange:e})=>e),i=!t&&this.config.numberOfCandidatesToDetectGap<=this._numberOfDetectedStallCandidates;if(s||i){let t=this._fragments.find(({startTs:t})=>t>e.currentPlaybackPosition)?.startTs||-1,s=e.bufferedTimeRanges.find(({start:t})=>t>e.currentPlaybackPosition)?.start||-1;t===s&&this._videoElement&&(this._videoElement.currentTime=s+.01,this._numberOfDetectedStallCandidates=0)}}};(0,U.__decorate)([tQ.default],sf.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sf.prototype,"_onVODFragmentsInfoAvailable",null),(0,U.__decorate)([tQ.default],sf.prototype,"_onBufferMetricsAvailable",null);let sp=class{constructor(e){this.groups=["buffer"],this._liveGapController=null,this._vodGapController=null,this._videoElement=null,this._isInVODMode=!1,this._eventBus=e,this._liveGapController=new sg(this._eventBus),this._recreateGapController()}destroy(){this._vodGapController?.destroy(),this._liveGapController?.destroy()}setIsVod(e){this._isInVODMode=e,this._recreateGapController()}setVideoElement(e){this._videoElement=e,this._liveGapController&&this._liveGapController.setVideoElement(e),this._vodGapController&&this._vodGapController.setVideoElement(e)}removeVideoElement(){this._videoElement=null,this._liveGapController?.removeVideoElement(),this._vodGapController?.removeVideoElement()}_recreateGapController(){this._vodGapController?.destroy(),this._liveGapController?.destroy(),this._isInVODMode?this._vodGapController=new sf(this._eventBus):this._liveGapController=new sg(this._eventBus),this._videoElement&&this.setVideoElement(this._videoElement)}get status(){return this._vodGapController?.status||this._liveGapController?.status||"Idle"}get state(){return this._vodGapController?.state||this._liveGapController?.state||tK.OK}get additionalInfo(){return this._vodGapController?.additionalInfo||this._liveGapController?.additionalInfo||{}}};var U=k("a8VW4"),sm=((C={}).FAST="fast",C.NORMAL="normal",C.SLOW="slow",C);let sb={targetBufferIncreaseRequested:"targetBuffer.targetBufferIncreaseRequested",targetBufferIncreased:"targetBuffer.targetBufferIncreased",targetBufferDecreaseRequested:"targetBuffer.targetBufferDecreaseRequested"},sy={setPlaybackSpeed:"playbackSpeed.setPlaybackSpeed"};var tQ=k("eQOGK");let sv=class extends tj{constructor(e){super("playbackSpeedActuator",e),this.state=tK.OK,this.status="Idle",this.groups=["PlaybackSpeed"],this._videoElement=null,this._currentPlaybackSpeed=sm.NORMAL,this._onPlaybackSpeedChangedListener=this._eventBus.subscribe(sy.setPlaybackSpeed,this._onPlaybackSpeedChanged)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onPlaybackSpeedChangedListener)}setVideoElement(e){this._videoElement=e,this._setPlaybackSpeed()}_handleConfigUpdated(){this._setPlaybackSpeed()}_onPlaybackSpeedChanged(e){this._currentPlaybackSpeed=e,this._setPlaybackSpeed()}_setPlaybackSpeed(){if(!this._videoElement)return;let e={[sm.FAST]:this.config.maxPlaybackRate,[sm.NORMAL]:1,[sm.SLOW]:this.config.minPlaybackRate};this._videoElement.playbackRate=e[this._currentPlaybackSpeed]}get additionalInfo(){return{currentPlaybackMode:this._currentPlaybackSpeed}}};(0,U.__decorate)([tQ.default],sv.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sv.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],sv.prototype,"_onPlaybackSpeedChanged",null);var U=k("a8VW4");let sE="getSideMetricsAsyncEvents.getPlaybackSpeedControllerMetrics",sS="getSideMetricsAsyncEvents.playbackSpeedControllerMetricsAvailable",sR="getSideMetricsAsyncEvents.getPlayingTimeFraction",sT="getSideMetricsAsyncEvents.getPlayingTimeFractionAvailable",sL={fragments:{fragmentLoaded:"fragmentLoader.fragments.fragmentLoaded",fragmentLoadingStarted:"fragmentLoader.fragments.fragmentLoadingStarted",fragmentLoadingAborted:"fragmentLoader.fragments.fragmentLoadingAborted",fragmentLoadingError:"fragmentLoader.fragments.fragmentLoadingError",fragmentHistoryReadyForPrint:"fragmentLoader.fragments.fragmentHistoryReadyForPrint"}},sA={fragmentLoader:sL,playlistRotator:tY,streamLoader:{playlistRotatorTypeChanged:"streamLoader.playlistRotatorTypeChanged"}},sP=(e,t)=>e.partHoldBack||e.serverControl?.partHoldBack||e.serverControl?.holdBack||t;var tQ=k("eQOGK");let sC=class extends tj{constructor(e){super("playbackSpeedWatcher",e),this.state=tK.OK,this.status="Idle",this.groups=["PlaybackSpeed"],this._originalTargetBuffer=2,this._currentTargetBufferMultiplier=1,this._currentPlaybackRateMode=sm.NORMAL,this._isPaused=!1,this._logger=eO("Doppio - PlaybackSpeedWatcher"),this._onBufferMetricsReadyListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),this._onTargetBufferDecreaseRequestedListener=this._eventBus.subscribe(sb.targetBufferDecreaseRequested,this._targetBufferDecreaseRequested),this._onTargetBufferIncreaseRequestedListener=this._eventBus.subscribe(sb.targetBufferIncreaseRequested,this._targetBufferIncreaseRequested),this._onPlaylistInfoAvailableListener=this._eventBus.subscribe(sA.playlistRotator.playlists.playlistInfo,this._onPlaylistInfoAvailable),this._onPlaybackSpeedControllerMetricsRequestedListener=this._eventBus.subscribe(sE,this._onPlaybackSpeedControllerMetricsRequested),this.config.targetBufferInitialMultiplier&&this.config.targetBufferInitialMultiplier<1&&this._logger.warn("Target buffer multiplier set to value lower than 1. It is unsafe to load less than target-duration, forcing no multiplier instead")}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onBufferMetricsReadyListener),this._eventBus.unsubscribe(this._onTargetBufferDecreaseRequestedListener),this._eventBus.unsubscribe(this._onTargetBufferIncreaseRequestedListener),this._eventBus.unsubscribe(this._onPlaylistInfoAvailableListener),this._eventBus.unsubscribe(this._onPlaybackSpeedControllerMetricsRequestedListener)}pause(){this._isPaused=!0,this._setNewPlaybackRateMode(sm.NORMAL)}resume(){this._isPaused=!1}_handleConfigUpdated(){}_setNewPlaybackRateMode(e){this._currentPlaybackRateMode!==e&&(this._currentPlaybackRateMode=e,this._eventBus.publish(sy.setPlaybackSpeed,e))}_onBufferMetricsAvailable(e){if(this._isPaused)return;let t=this._getTargetBuffer(),s=e.bufferAmountWithoutGaps-t;if(0!==e.currentPlaybackPosition){if(s>this.config.maxLiveSyncThreshold*t){this._setNewPlaybackRateMode(sm.FAST);return}if(-1*s>this.config.minLiveSyncThreshold*t){this._setNewPlaybackRateMode(sm.SLOW);return}if(this._currentPlaybackRateMode===sm.SLOW&&s>0||this._currentPlaybackRateMode===sm.FAST&&s<0){this._setNewPlaybackRateMode(sm.NORMAL);return}}}_targetBufferIncreaseRequested(){this._currentTargetBufferMultiplier1&&(this._currentTargetBufferMultiplier-=1,this._eventBus.publish(sb.targetBufferIncreased,{}))}_onPlaylistInfoAvailable(e){this._originalTargetBuffer=sP(e,3*e.targetDuration)}_onPlaybackSpeedControllerMetricsRequested(){this._eventBus.publish(sS,this._getTargetBuffer())}_getTargetBuffer(){return this._originalTargetBuffer*this._currentTargetBufferMultiplier*this.config.targetBufferInitialMultiplier}get additionalInfo(){return{currentTargetBufferMultiplier:this._currentTargetBufferMultiplier,currentTargetBuffer:this._getTargetBuffer()}}};(0,U.__decorate)([tQ.default],sC.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sC.prototype,"_onBufferMetricsAvailable",null),(0,U.__decorate)([tQ.default],sC.prototype,"_targetBufferIncreaseRequested",null),(0,U.__decorate)([tQ.default],sC.prototype,"_targetBufferDecreaseRequested",null),(0,U.__decorate)([tQ.default],sC.prototype,"_onPlaylistInfoAvailable",null),(0,U.__decorate)([tQ.default],sC.prototype,"_onPlaybackSpeedControllerMetricsRequested",null);var U=k("a8VW4");let sB=class{registerEvent(){this._registeredEvents.push(Date.now())}checkEventsInPeriod(e){let t=Date.now()-e;return this._registeredEvents=this._registeredEvents.filter(e=>e>=t),this._registeredEvents.length}clear(){this._registeredEvents=[]}constructor(){this._registeredEvents=[]}};var tQ=k("eQOGK");let sO=class extends tj{constructor(e){super("targetBufferDecreaser",e),this.state=tK.OK,this.status="Idle",this.groups=["PlaybackSpeed"],this.additionalInfo={},this.currentTargetBufferMultiplier=1,this._nextCheckTimestamp=0,this._currentPlaybackRateMode=sm.NORMAL,this._slowdownEventsCollector=new sB,this._onPlaybackRateModeChangedListener=this._eventBus.subscribe(sy.setPlaybackSpeed,this._onPlaybackRateModeChanged),this._onBufferMetricsAvailableListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),this._onTargetBufferIncreasedListener=this._eventBus.subscribe(sb.targetBufferIncreased,this._onTargetBufferIncreased)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onPlaybackRateModeChangedListener),this._eventBus.unsubscribe(this._onBufferMetricsAvailableListener),this._eventBus.unsubscribe(this._onTargetBufferIncreasedListener)}_handleConfigUpdated(){}_onPlaybackRateModeChanged(e){e!==this._currentPlaybackRateMode&&(e===sm.SLOW||this._currentPlaybackRateMode===sm.SLOW)&&this._slowdownEventsCollector.registerEvent(),this._currentPlaybackRateMode=e}_onBufferMetricsAvailable(){0!==this._nextCheckTimestamp&&this._nextCheckTimestamp1&&this._currentPlaybackRateMode!==sm.SLOW&&0===this._slowdownEventsCollector.checkEventsInPeriod(this.config.periodOfEventsToCancelDecrease)&&(this._eventBus.publish(sb.targetBufferDecreaseRequested,{}),this.currentTargetBufferMultiplier-=1,this._nextCheckTimestamp=this.currentTargetBufferMultiplier>1?Date.now()+this.config.periodOfEventsToCancelDecrease:0)}_onTargetBufferIncreased(){this.currentTargetBufferMultiplier+=1,this._nextCheckTimestamp=Date.now()+this.config.periodOfEventsToCancelDecrease}};(0,U.__decorate)([tQ.default],sO.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sO.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],sO.prototype,"_onPlaybackRateModeChanged",null),(0,U.__decorate)([tQ.default],sO.prototype,"_onBufferMetricsAvailable",null),(0,U.__decorate)([tQ.default],sO.prototype,"_onTargetBufferIncreased",null);var U=k("a8VW4"),tQ=k("eQOGK");let sD=class extends tj{constructor(e){super("targetBufferIncreaser",e),this.state=tK.OK,this.status="Idle",this.groups=["PlaybackSpeed"],this._hasFallenBelowLine=!0,this._onBufferMetricsAvailableListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onBufferMetricsAvailableListener)}_handleConfigUpdated(){}_onBufferMetricsAvailable(e){if(this._hasFallenBelowLine){1e3*e.bufferAmountWithoutGaps>=this.config.bufferAmountThreshold&&(this._hasFallenBelowLine=!1);return}1e3*e.bufferAmountWithoutGaps=this._stallsToChangeState&&this._setNextState(sM.PAUSED)}_onCanPlayThrough(){this._startTS||(this._startTS=Date.now()),this.config.autoPlay&&this._videoElement?.play()}_onPlaylistInfoAvailable(e){this._targetLiveEdge=sP(e,3*e.targetDuration)}_onPlay(){this.config.syncToLiveEdge&&this._videoElement&&(this._videoElement.buffered.length?this._syncToLiveEdge(this._videoElement.buffered.end(this._videoElement.buffered.length-1)):this._syncOnNextMetrics=!0)}_getDesiredPosition(e){return e-this.config.syncToLiveDelta*this._targetLiveEdge}_syncToLiveEdge(e){if(!this._videoElement||!this._videoElement?.buffered.length)return;let t=this._getDesiredPosition(e);t>this._videoElement.buffered.start(0)&&t>this._videoElement.currentTime&&(this._videoElement.currentTime=t)}_onPlaying(){this._stallTS&&(this._stalledTimeRanges.push({startTS:this._stallTS,endTS:Date.now()}),this._stallTS=0)}_onStall(){this._stallTS=Date.now()}_onPlayingTimeFractionRequested(){let e=this._calculatePlayingTimeFraction();this._eventBus.publish(sT,e)}_calculatePlayingTimeFraction(){if(!this._startTS)return null;let e=Date.now()-this.config.playingTimeFractionCollectionWindow;this._stalledTimeRanges=this._stalledTimeRanges.filter(({endTS:t})=>t>e);let t=Date.now()-this._startTS,s=this._stalledTimeRanges.reduce((e,t)=>e+(t.endTS-t.startTS),0),i=this._stallTS?Date.now()-this._stallTS:0;return this._startTS=Date.now(),(t-s-i)/t}};(0,U.__decorate)([tQ.default],sI.prototype,"reset",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onFragmentRequested",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onMetricsAvailable",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onCanPlayThrough",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onPlaylistInfoAvailable",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onPlay",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onPlaying",null),(0,U.__decorate)([tQ.default],sI.prototype,"_onPlayingTimeFractionRequested",null);let sF={fragments:{fragmentsParsed:"fragmentParser.fragments.fragmentsParsed",videoFragmentParsed:"fragmentParser.fragments.videoFragmentParsed",audioFragmentParsed:"fragmentParser.fragments.audioFragmentParsed"}};var tQ=k("eQOGK");let sN=class extends tj{constructor(e){super("bufferController",e),this._cache=[],this._lastMsn=-1}append(e){for(let t of e){if(!this._cache.length){t.isInitSection&&(this._cache=[t]);continue}if(t.msn!==this._lastMsn){let e=t.msn-this.config.saveLastSegmentsCount+1;this._cache=[...this._cache.filter(t=>t.isInitSection||t.msn>=e),t]}else this._cache.push(t);this._lastMsn=t.msn}}getAll(){return this._cache}reset(){this._cache=[],this._lastMsn=-1}destroy(){super.destroy(),this._cache=[],this._lastMsn=-1}};var U=k("a8VW4");let sk=e=>new Promise(t=>{e.publish(sE,{}),e.subscribeOnce(sS,e=>{t(e)})}),sV=e=>new Promise(t=>{e.publish(sR,{}),e.subscribeOnce(sT,e=>{t(e)})});var tQ=k("eQOGK");let sU=class extends tj{constructor(e){super("bufferController",e),this.state=tK.OK,this.status="Idle",this.groups=["buffer","general"],this.additionalInfo={},this._videoElement=null,this._checkIntervalId=null,this._lastCheckTimestamp=0,this._lastFramesTotal=0,this._lastFramesDropped=0,this._lastFramesPlayed=0,this._lastRealFPS=0,this._lastPlaybackFPS=0,this._lastPlaybackPosition=0,this._lastBufferAmount=0,this._logger=eO("Doppio - BufferMetrics")}destroy(){this._checkIntervalId&&globalThis.clearInterval(this._checkIntervalId)}setVideoElement(e){this._videoElement=e,this._rearmInterval()}removeVideoElement(){this._videoElement=null,this._checkIntervalId&&globalThis.clearInterval(this._checkIntervalId)}_handleConfigUpdated(e){Number.isNaN(e.checkMetricsInterval)||this._rearmInterval()}_rearmInterval(){this._checkIntervalId&&globalThis.clearInterval(this._checkIntervalId),this._checkIntervalId=globalThis.setInterval(this._performCheck,this.config.checkMetricsInterval)}_getCurrentBufferAmount(e){if(!this._videoElement)return this._logger.warn("Cannot compute buffer, there is no video element registered"),0;let{currentTime:t,buffered:s}=this._videoElement;return 0===s.length||t>s.end(s.length-1)||!e?0:s.end(s.length-1)-t}_getCurrentBufferAmountWithoutGaps(e,t){if(!this._videoElement)return this._logger.warn("Cannot compute buffer, there is no video element registered"),0;if(!e)return 0;let{currentTime:s}=this._videoElement;return e.end-s+t.filter(({start:t})=>t>=e.end).reduce((e,t)=>e+(t.end-t.start),0)}async _performCheck(){if(!this._videoElement){this._checkIntervalId&&globalThis.clearInterval(this._checkIntervalId),this._logger.warn("Cannot compute metrics, there is no video element registered");return}let{creationTime:e,totalVideoFrames:t,droppedVideoFrames:s}=this._videoElement.getVideoPlaybackQuality(),{buffered:i,currentTime:r,paused:n,duration:a,playbackRate:o}=this._videoElement,l=e/1e3;if(!this._lastCheckTimestamp){this._lastCheckTimestamp=l,this._lastFramesTotal=t,this._lastFramesDropped=s,this._lastFramesPlayed=t-s,this._lastPlaybackPosition=r;return}let u=await sk(this._eventBus),d=await sV(this._eventBus)||0,h=t-s,c=l-this._lastCheckTimestamp,_=r-this._lastPlaybackPosition,g=t-this._lastFramesTotal,f=s-this._lastFramesDropped,p=h-this._lastFramesPlayed,m=g/c,b=g/_,y=this._lastRealFPS-m,v=this._lastPlaybackFPS-b,E=Array(i.length).fill(null).map((e,t)=>{let s={start:i.start(t),end:i.end(t),index:t,isCurrentTimeRange:!1};return(s.start<=r&&r<=s.end||n&&0===t)&&(s.isCurrentTimeRange=!0),s}),S=E.find(({isCurrentTimeRange:e})=>e)||null,R=this._getCurrentBufferAmount(S),T=R0&&!n&&(R`video/mp4; codecs="${e}"`,sq=class e extends tj{constructor(e){super("bufferController",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["buffer","general"],this._sourceBuffer=null,this._isSourceBufferReady=!1,this._awaitingForNextSourceBuffer=!1,this._isVODMode=!1,this._closeOnNextSegment=!1,this._currentVideoDuration=Number.POSITIVE_INFINITY,this._videoElement=null,this._mediaSource=null,this._knownObjectURL="",this._mimeType='video/mp4; codecs="mp4a.40.2,avc1.64001f"',this._shouldRecreateSourceBufferOnStall=!1,this._sourceBufferStuckTimer=null,this._logger=eO("Doppio - BufferController"),this._logger.info("Created"),this._eventBus=e,this._bufferCleaner=new si(this._eventBus),this._bufferMetrics=new sU(this._eventBus),this._bufferStallsDetector=new su(this._eventBus),this._bufferOpsQueue=new sl(this._eventBus),this._playbackSpeedController=new sw(this._eventBus),this._playbackStateController=new sI(this._eventBus),this._bufferChunksCache=new sN(this._eventBus),this._onFragmentParsedListener=this._eventBus.subscribe(sF.fragments.fragmentsParsed,this._onFragmentsParsed),this._onSoftResetRequestedListener=this._eventBus.subscribe(tz.requestResetWithOverplay,this._onSoftResetRequested),this._onVODPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.vodDetected,this._onVODPlaylistDetected),this._onSimplePlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.simpleDetected,this._onLivePlaylistDetected),this._onLLPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.llDetected,this._onLivePlaylistDetected),this._onSourceBufferOperationRequestedListener=this._eventBus.subscribe(tz.requestSourceBufferOperation,this._onSourceBufferOperationRequested),this._onPlaylistInfoAvailableListener=this._eventBus.subscribe(sA.playlistRotator.playlists.playlistInfo,this._onPlaylistInfoAvailable),this._onEndOfStreamReachedListener=this._eventBus.subscribe(tz.endOfStreamReached,this._onEndOfStreamReached),this._onResolutionCodecChangeRequestListener=this._eventBus.subscribe(tz.changeCodec,this._onResolutionCodecChangeRequest),this._onResolutionChangeListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChange),this._onPlaybackStallChangedListener=this._eventBus.subscribe(tz.playbackStallChanged,this._onPlaybackStallChanged),this._onSourceBufferStuckListener=this._eventBus.subscribe(tz.sourceBufferStuck,this._onSourceBufferStuck),this._gapController=new sp(this._eventBus)}attachVideoElement(e){this._logger.info("Attach video element"),this._bufferMetrics.setVideoElement(e),this._playbackSpeedController.setVideoElement(e),this._gapController.setVideoElement(e),this._bufferCleaner.setVideoElement(e),this._playbackStateController.setVideoElement(e),this._videoElement=e,this._recreateMediaSource()}scheduleSourceBufferRecreation(){this._awaitingForNextSourceBuffer=!0}detachVideoElement(){if(this._logger.info("Detaching video element"),this._eventBus.publish(tz.requestResetWithOverplay,{}),this._bufferMetrics.removeVideoElement(),this._playbackSpeedController.removeVideoElement(),this._gapController.removeVideoElement(),this._bufferCleaner.removeVideoElement(),this._playbackStateController.setVideoElement(null),this._mediaSource?.readyState==="open"&&this._videoElement&&this._videoElement.readyState>=this._videoElement.HAVE_METADATA)try{this._logger.verbose("Calling endOfStream of mediaSource"),this._mediaSource.endOfStream()}catch(e){this._logger.warn(`Error occurred while detaching video element. Ignoring it ${e.message}`)}try{this._mediaSource&&this._sourceBuffer&&([...this._mediaSource.sourceBuffers].includes(this._sourceBuffer)&&(this._logger.debug("Removing sourceBuffer from MediaSource"),this._mediaSource.removeSourceBuffer(this._sourceBuffer)),this._sourceBuffer=null)}catch(e){this._logger.error(`Failed to reset source buffer ${e.message}`)}if(this._mediaSource&&(this._mediaSource.removeEventListener("sourceopen",this._onSourceBufferOpened),this._mediaSource.removeEventListener("sourceclose",this._onSourceBufferClosed),this._mediaSource.removeEventListener("error",this._onSourceBufferClosed)),this._videoElement){if(this._knownObjectURL){let e=this._knownObjectURL;setTimeout(()=>{this._logger.debug(`Revoking Object URL ${e}`),globalThis.URL.revokeObjectURL(e)},100)}this._videoElement.src===this._knownObjectURL&&(this._videoElement.removeAttribute("src"),this._videoElement.load())}this._mediaSource=null,this._videoElement=null,this._knownObjectURL="",this._isSourceBufferReady=!1}destroy(){super.destroy(),this._logger.info("Destroy"),this.detachVideoElement(),this._eventBus.unsubscribe(this._onFragmentParsedListener),this._eventBus.unsubscribe(this._onSoftResetRequestedListener),this._eventBus.unsubscribe(this._onSourceBufferOperationRequestedListener),this._eventBus.unsubscribe(this._onVODPlaylistDetectedListener),this._eventBus.unsubscribe(this._onSimplePlaylistDetectedListener),this._eventBus.unsubscribe(this._onLLPlaylistDetectedListener),this._eventBus.unsubscribe(this._onPlaylistInfoAvailableListener),this._eventBus.unsubscribe(this._onEndOfStreamReachedListener),this._eventBus.unsubscribe(this._onResolutionCodecChangeRequestListener),this._eventBus.unsubscribe(this._onResolutionChangeListener),this._eventBus.unsubscribe(this._onPlaybackStallChangedListener),this._eventBus.unsubscribe(this._onSourceBufferStuckListener),this._gapController.destroy(),this._bufferMetrics.destroy(),this._bufferOpsQueue.destroy(),this._bufferCleaner.destroy(),this._playbackSpeedController.destroy(),this._playbackStateController.destroy(),this._bufferChunksCache.destroy(),this._disarmSourceBufferStuckTimer()}reset(){this._disarmSourceBufferStuckTimer(),this._recreateSourceBuffer(),this._bufferChunksCache.reset()}_onFragmentsParsed(e){for(let t of(this._awaitingForNextSourceBuffer&&(this._awaitingForNextSourceBuffer=!1,this._recreateSourceBuffer()),this._bufferOpsQueue.addBufferOperation(()=>{this._mediaSource&&"open"===this._mediaSource.readyState&&(this._mediaSource.duration=this._currentVideoDuration)},()=>{this._logger.warn("Could not set mediaSource duration")},"setMediaSourceDuration"),e))this._bufferOpsQueue.addBufferOperation(e=>{this._logger.debug(`Adding ${t.getMsnPn()} to buffer`),e.appendBuffer(t.data),t.msn>-1&&(this._logger.debug(`${t.startTs} -> ${t.endTs} loaded (${t.getMsnPn()})`),this._eventBus.publish(tz.fragmentAdded,t)),this._mediaSource&&t.endTs===this._mediaSource.duration&&this._eventBus.publish(tz.endOfStreamReached,{})},(e,s)=>{this._logger.error(`${t.url} (${t.getMsnPn()}) cannot be added to buffer: ${s}`)},"appendBuffer");this._sourceBuffer||this._bufferChunksCache.append(e),this._bufferOpsQueue.addBufferOperation(()=>{this._mediaSource&&"open"===this._mediaSource.readyState&&(this._mediaSource.duration=this._currentVideoDuration,this._videoElement&&0===this._videoElement.currentTime&&this._videoElement.buffered.length>0&&this._videoElement.buffered.start(0)>0&&(this._videoElement.currentTime=this._videoElement.buffered.start(0)))},()=>{this._logger.warn("Could not change current time of video")},"setVideoElementStartPosition")}_onSourceBufferOpened(){if(this._disarmSourceBufferStuckTimer(),this._mediaSource){"open"===this._mediaSource.readyState&&(this._mediaSource.duration=this._currentVideoDuration),this._isSourceBufferReady=!0,this._sourceBuffer=this._mediaSource.addSourceBuffer(this._mimeType),this._bufferOpsQueue.setSourceBuffer(this._sourceBuffer);let e=this._bufferChunksCache.getAll();this._bufferChunksCache.destroy(),e.length&&this._onFragmentsParsed(e)}}_recreateSourceBuffer(){this._logger.info("Will recreate source buffer"),this._bufferOpsQueue.immediatelyRecreateSourceBuffer(this._mediaSource),this._videoElement&&(this._videoElement.currentTime=0)}_onResolutionCodecChangeRequest({codec:e}){if(e){let t=sx(e);t!==this._mimeType&&(this._mimeType=t)}}_onSourceBufferClosed(){this._isSourceBufferReady=!1}_onSoftResetRequested(){this._shouldRecreateSourceBufferOnStall=!1,this._awaitingForNextSourceBuffer=!0,this._playbackStateController.resetPlayingTimeCollector()}_endOfStreamReached(){this._mediaSource&&(this._closeOnNextSegment=!0)}_onSourceBufferOperationRequested(e){this._bufferOpsQueue.addBufferOperation(e)}_onLivePlaylistDetected(){this._isVODMode=!1,this._bufferCleaner.setVODMode(!1),this._gapController.setIsVod(!1),this._currentVideoDuration=Number.POSITIVE_INFINITY,this._playbackSpeedController.resume(),this._mediaSource&&"open"===this._mediaSource.readyState&&(this._mediaSource.duration=this._currentVideoDuration)}_onVODPlaylistDetected(){this._isVODMode=!0,this._bufferCleaner.setVODMode(!0),this._playbackSpeedController.pause(),this._gapController.setIsVod(!0)}_onPlaybackStallChanged(e){e&&this._shouldRecreateSourceBufferOnStall&&(this._logger.info("Will recreate source buffer, because playback stall was detected"),this._onSoftResetRequested())}_onPlaylistInfoAvailable(e){e&&e.playlists&&e.playlists[0].attributes.CODECS&&(this._mimeType=sx(e.playlists[0].attributes.CODECS),this._bufferOpsQueue.addBufferOperation(e=>{e.changeType(this._mimeType)},()=>{this._logger.warn("Could not change codecs")},"changeType")),("VOD"===e.playlistType||e.endList)&&(this._currentVideoDuration=e.segments.reduce((e,t)=>e+t.duration,0),this._mediaSource&&"open"===this._mediaSource.readyState&&(this._mediaSource.duration=this._currentVideoDuration,this._mediaSource.setLiveSeekableRange(0,this._currentVideoDuration)))}_onEndOfStreamReached(){this._bufferOpsQueue.addBufferOperation(()=>{this._logger.info("Setting endOfStream"),this._mediaSource?.endOfStream()})}_onResolutionChange(){this.config.recreateSourceBufferOnResolutionChange?(this._logger.info("Will recreate source buffer, because resolution was changed, and config.recreateSourceBufferOnResolutionChange is true"),this._onSoftResetRequested()):this._shouldRecreateSourceBufferOnStall=!0}_onSourceBufferStuck(){this._onSoftResetRequested()}_recreateMediaSource(){this._mediaSource&&(this._mediaSource.removeEventListener("sourceopen",this._onSourceBufferOpened),this._mediaSource.removeEventListener("sourceclose",this._onSourceBufferClosed),this._mediaSource.removeEventListener("error",this._onSourceBufferClosed)),this._mediaSource=new e.MediaSource,this._mediaSource.addEventListener("sourceopen",this._onSourceBufferOpened,{once:!0}),this._mediaSource.addEventListener("sourceclose",this._onSourceBufferClosed),this._mediaSource.addEventListener("error",this._onSourceBufferClosed),this._videoElement&&(this._videoElement.src=globalThis.URL.createObjectURL(this._mediaSource)),this._sourceBufferStuckTimer=setTimeout(()=>{this._recreateMediaSource()},this.config.sourceBufferStuckTimeout)}_disarmSourceBufferStuckTimer(){this._sourceBufferStuckTimer&&clearTimeout(this._sourceBufferStuckTimer)}get additionalModules(){return{gapController:this._gapController,bufferMetrics:this._bufferMetrics,playbackSpeed:this._playbackSpeedController}}static get MediaSource(){if(window?.ManagedMediaSource)return window.ManagedMediaSource;if(window?.MediaSource)return window.MediaSource;throw Error("No Media Source candidates found")}};(0,U.__decorate)([tQ.default],sq.prototype,"_onFragmentsParsed",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onSourceBufferOpened",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onResolutionCodecChangeRequest",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onSourceBufferClosed",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onSoftResetRequested",null),(0,U.__decorate)([tQ.default],sq.prototype,"_endOfStreamReached",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onSourceBufferOperationRequested",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onLivePlaylistDetected",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onVODPlaylistDetected",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onPlaybackStallChanged",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onPlaylistInfoAvailable",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onEndOfStreamReached",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onResolutionChange",null),(0,U.__decorate)([tQ.default],sq.prototype,"_onSourceBufferStuck",null),(0,U.__decorate)([tQ.default],sq.prototype,"_recreateMediaSource",null);let sG=class extends eg{};var U=k("a8VW4");let sW={fragmentsReleased:"fragmentsFilter.fragmentsReleased",problemDetected:"fragmentsFilter.problemDetected"};var tQ=k("eQOGK");let sH=class extends tj{constructor(e){super("fragmentParser",e),this._localFragmentParser=null,this._workerFragmentParser=null,this._fragmentsCache=[],this._isCacheRequired=!1,this._logger=eO("Doppio - FragmentParser"),this._onFragmentReleasedListener=this._eventBus.subscribe(sW.fragmentsReleased,this._onFragmentsLoaded),this._onVODPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.vodDetected,this._onVODPlaylistDetected),this._onSimplePlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.simpleDetected,this._onLivePlaylistDetected),this._onLLPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.llDetected,this._onLivePlaylistDetected),this._onReleaseFromCacheRequestedListener=this._eventBus.subscribe(tY.fragments.requestReleaseFromCache,this._onReleaseFromCacheRequested)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onFragmentReleasedListener),this._eventBus.unsubscribe(this._onVODPlaylistDetectedListener),this._eventBus.unsubscribe(this._onSimplePlaylistDetectedListener),this._eventBus.unsubscribe(this._onLLPlaylistDetectedListener),this._eventBus.unsubscribe(this._onReleaseFromCacheRequestedListener)}_handleConfigUpdated(){}_onReleaseFromCacheRequested({msn:e}){let t=this._fragmentsCache.find(t=>t.msn===e);t&&this._eventBus.publish(sF.fragments.fragmentsParsed,[t])}_onLivePlaylistDetected(){this._isCacheRequired=!1,this._fragmentsCache=[]}_onVODPlaylistDetected(){this._isCacheRequired=!0}async _onFragmentsLoaded(e){this._logger.verbose(`Sending fragment ${e.map(e=>e.getMsnPn())} for parsing`),this._eventBus.publish(sF.fragments.fragmentsParsed,e)}};(0,U.__decorate)([tQ.default],sH.prototype,"destroy",null),(0,U.__decorate)([tQ.default],sH.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],sH.prototype,"_onReleaseFromCacheRequested",null),(0,U.__decorate)([tQ.default],sH.prototype,"_onLivePlaylistDetected",null),(0,U.__decorate)([tQ.default],sH.prototype,"_onVODPlaylistDetected",null),(0,U.__decorate)([tQ.default],sH.prototype,"_onFragmentsLoaded",null);var U=k("a8VW4");let s$=e=>{let t=new DataView(e),s=0,i=[];for(;s{let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0));return e.reduce((e,s)=>(t.set(s,e),e+s.byteLength),0),t.buffer},sK="fragmentsQueue.fragmentReleased";var tQ=k("eQOGK");let sY={saveData:"fragmentsBufferEvents.saveData"},sQ=class extends tj{constructor(e){super("fragmentsFilter",e),this._logger=eO("Doppio - FragmentsFilter"),this._lastKnownInitSectionNumberOfTracks=null,this._onFragmentReleasedListenerToken=this._eventBus.subscribe(sK,this._onFragmentReleasedFromQueue)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onFragmentReleasedListenerToken)}_onFragmentReleasedFromQueue(e){let t=[];for(let s of e)if(s.isInitSection)this._parseInitSection(s),t.push(s);else{let e=this._parseMediaFragment(s);(!this.config.filterOutInconsistentTracks||e)&&t.push(s)}this._eventBus.publish(sW.fragmentsReleased,t)}_parseInitSection(e){this._logger.debug("Parsing init section");let t=s$(e.data),s=t.find(({name:e})=>"moov"===e)||null;if(this._logger.verbose(`Found following root boxes: ${t.map(({name:e})=>e).join(", ")}`),s){let e=s$(s.payload);this._logger.verbose(`Found following child of moov boxes: ${e.map(({name:e})=>e).join(", ")}`);let t=e.filter(({name:e})=>"trak"===e);this._logger.info(`Found ${t.length} trak boxes`),this._lastKnownInitSectionNumberOfTracks=t.length}}_parseMediaFragment(e){if(null===this._lastKnownInitSectionNumberOfTracks)return!0;let t=s$(e.data),s=t.filter(({name:e})=>"sidx"===e);this._logger.verbose(`Found following root boxes: ${t.map(({name:e})=>e).join(", ")}`);let i=t.filter(({name:e})=>"moof"===e),r=[],n=!1;for(let e of(s.length>0&&s.length%this._lastKnownInitSectionNumberOfTracks!=0&&(this._logger.warn(`Inconsistent media chunk: number of SIDX boxes is invalid, ${s.length} found, ${this._lastKnownInitSectionNumberOfTracks} expected`),r.push(`Number of SIDX boxes (${s.length}) is not equal to the known amount of media tracks (${this._lastKnownInitSectionNumberOfTracks})`),n=!0),i)){let t=s$(e.payload),s=t.filter(({name:e})=>"traf"===e);this._logger.verbose(`Found following child of moof boxes: ${t.map(({name:e})=>e).join(", ")}`),s.length!==this._lastKnownInitSectionNumberOfTracks&&(this._logger.warn(`Inconsistent media chunk: number of TRAF boxes is invalid, ${s.length} found, ${this._lastKnownInitSectionNumberOfTracks} expected`),r.push(`Number of TRAF boxes (${s.length}) is not equal to the known amount of media tracks (${this._lastKnownInitSectionNumberOfTracks})`),n=!0)}return n&&(this._logger.warn(`Fragment ${e.getMsnPn()} should be reported`),this._eventBus.publish(sW.problemDetected,{fragment:e.url.split("/").slice(-1)[0],reason:r.join("; ")}),this._eventBus.publish(sY.saveData,{})),n}};(0,U.__decorate)([tQ.default],sQ.prototype,"_onFragmentReleasedFromQueue",null);var U=k("a8VW4"),tQ=k("eQOGK"),sX=((O={}).UNKNOWN="unknown",O.INDEPENDENT="independent",O.PART="part",O);let sz=class{constructor(e){this.state=tK.OK,this.status="Idle",this.groups=["queue"],this._queuedFragments=[],this._additionalInfo={},this._logger=eO("Doppio - FragmentsQueue"),this._eventBus=e,this._fragmentRequestedListenerToken=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoadingStarted,this._onFragmentRequested),this._onFragmentsDetectedListenerToken=this._eventBus.subscribe(tY.fragments.fragmentsDetected,this._onFragmentsDetected),this._softResetRequestedListenerToken=this._eventBus.subscribe(tz.requestResetWithOverplay,this._onSoftResetRequested),this._fragmentLoadedListenerToken=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoaded,this._onFragmentLoaded),this._fragmentAbortedListenerToken=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoadingAborted,this._onFragmentAborted),this._fragmentErrorListenerToken=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoadingError,this._onFragmentAborted),this._onFragmentReleaseFromCacheRequestedToken=this._eventBus.subscribe(tY.fragments.requestReleaseFromCache,this._onFragmentReleasedFromCache),this._onResolutionChangedListenerToken=this._eventBus.subscribe(tJ.resolutionChanged,this._onSoftResetRequested)}getCurrentQueue(){return this._queuedFragments}destroy(){this._eventBus.unsubscribe(this._onFragmentsDetectedListenerToken),this._eventBus.unsubscribe(this._fragmentLoadedListenerToken),this._eventBus.unsubscribe(this._fragmentRequestedListenerToken),this._eventBus.unsubscribe(this._softResetRequestedListenerToken),this._eventBus.unsubscribe(this._onResolutionChangedListenerToken),this._eventBus.unsubscribe(this._fragmentErrorListenerToken),this._eventBus.unsubscribe(this._fragmentAbortedListenerToken),this._eventBus.unsubscribe(this._onFragmentReleaseFromCacheRequestedToken),this.reset()}reset(){this._queuedFragments=[],this.status="Idle"}_onSoftResetRequested(){this.reset()}_onFragmentRequested(e){if(this._queuedFragments.find(({url:t})=>e.url===t)){this._logger.warn(`Same fragment (${e.getMsnPn()}) was already in queue! Ignoring it`);return}this._logger.verbose(`Add fragment ${e.getMsnPn()} to queue`),e.goToLifecycleStage("addedToQueue"),this._queuedFragments.push(e),this.status="Awaiting fragments"}_onFragmentLoaded(e){let t=this._queuedFragments.find(({msn:t,pn:s})=>t===e.msn&&s===e.pn);if(!t){this._logger.warn(`Received fragment ${e.getMsnPn()} was not in queue. Pls check it`);return}this._logger.debug(`Fragment ${e.getMsnPn()} was resolved finally`),t.data=e.data,this._checkQueue()}_onFragmentReleasedFromCache({msn:e}){this._queuedFragments=this._queuedFragments.filter(t=>t.msn===e),this._checkQueue()}_onFragmentsDetected(e){e.forEach(e=>{let t=this._queuedFragments.find(({msn:t,pn:s})=>t===e.msn&&s===e.pn);t&&(t.independent=e.independent)}),this._checkQueue()}_onFragmentAborted(e){let t=this._queuedFragments.filter(({msn:t})=>t<=e.msn);this._queuedFragments=this._queuedFragments.filter(e=>!t.includes(e)),this._checkQueue()}_checkQueue(){if(this._logger.verbose("Checking queue"),!this._queuedFragments.length){this._logger.verbose("Queue is empty. Skipping");return}if(!this._queuedFragments[0].data||this._queuedFragments[0].independent===sX.UNKNOWN){this._logger.verbose("First queued fragment is empty. Skipping");return}let e=this._queuedFragments.findIndex(e=>!e.data||e.independent===sX.UNKNOWN);if(-1===e){this._logger.verbose("Looks like whole queue was resolved"),this._releaseFragmentsFromQueue(this._queuedFragments);return}this._logger.verbose(`${e} fragments ready. Releasing them`);let t=this._queuedFragments.slice(0,e);this._releaseFragmentsFromQueue(t)}_releaseFragmentsFromQueue(e){this._logger.verbose(`Release fragment ${e.map(e=>e.getMsnPn())}from queue`),e.forEach(e=>e.goToLifecycleStage("releasedFromQueue")),this._queuedFragments=this._queuedFragments.filter(t=>!e.includes(t)),this._eventBus.publish(sK,e),this.status=this._queuedFragments.length>0?this.status:"Idle"}get additionalInfo(){return{...this._additionalInfo,awaitingFragments:this.getCurrentQueue().map(e=>({...e,data:void 0}))}}};(0,U.__decorate)([tQ.default],sz.prototype,"_onSoftResetRequested",null),(0,U.__decorate)([tQ.default],sz.prototype,"_onFragmentRequested",null),(0,U.__decorate)([tQ.default],sz.prototype,"_onFragmentLoaded",null),(0,U.__decorate)([tQ.default],sz.prototype,"_onFragmentReleasedFromCache",null),(0,U.__decorate)([tQ.default],sz.prototype,"_onFragmentsDetected",null),(0,U.__decorate)([tQ.default],sz.prototype,"_onFragmentAborted",null),(0,U.__decorate)([tQ.default],sz.prototype,"_releaseFragmentsFromQueue",null);let sJ=new class{async reportError(e,t){try{await fetch(this._ooEndpoint,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({doppioLifecycleError:{errorType:e,context:t}})})}catch(e){}}constructor(){this._ooEndpoint="/api/front/v2/logs/streaming"}};var U=(k("a8VW4"),k("a8VW4"),k("a8VW4")),sZ=k("lYhjM"),U=k("a8VW4"),s0={};s0='function e(e,t,r,o){Object.defineProperty(e,t,{get:r,set:o,enumerable:!0,configurable:!0})}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},r={},o={},a=t.parcelRequire94c2_uo2xw;null==a&&((a=function(e){if(e in r)return r[e].exports;if(e in o){var t=o[e];delete o[e];var a={id:e,exports:{}};return r[e]=a,t.call(a.exports,a,a.exports),a.exports}var s=Error("Cannot find module \'"+e+"\'");throw s.code="MODULE_NOT_FOUND",s}).register=function(e,t){o[e]=t},t.parcelRequire94c2_uo2xw=a);var s=a.register;s("gMZQX",function(t,r){e(t.exports,"ENetworkLoadFetchNetworkEvent",function(){return a});var o,a=((o={}).FETCH="fetch",o.ABORT="abort",o.DESTROY="destroy",o.DATA_READY="dataReady",o.STATS_READY="statsReady",o.CHANGE_STATE="changeState",o.ERROR="error",o.REDIRECT_DETECTED="redirectDetected",o)}),s("j9q3y",function(t,r){e(t.exports,"NetworkLoadFetch",function(){return $23b27e332a61b135$export$df6d58d46cb3f0ea});var o=a("aoPbh"),s=a("lYhjM"),n=a("lR17I");let $23b27e332a61b135$export$df6d58d46cb3f0ea=class $23b27e332a61b135$export$df6d58d46cb3f0ea{constructor(e){this.requestUrl="",this.realUrl="",this.mode="",this._dataChunks=[],this._receivedLength=0,this._abortController=new AbortController,this._startLoadTimestamp=0,this._isAborted=!1,this._config=e}abort(){this._isAborted=!0,this._abortController.abort()}async fetch(e,t){try{globalThis.performance&&globalThis.performance.clearResourceTimings&&globalThis.performance.clearResourceTimings(),this._config.onChangeState(s.ELoadingState.LOADING),this._startLoadTimestamp=Date.now(),this.requestUrl=e,this.mode=t,this._receivedLength=0;let r=new Request(this.requestUrl),a={signal:this._abortController.signal};this._config.requestCustomReferer&&(a.headers={"X-Referer":this._config.requestCustomReferer});let n=await fetch(r,a);this.realUrl=n.url;let i=n.body?.getReader();if(!i)throw Error();for(;;){let{done:e,value:t}=await i.read();if(e)break;this._dataChunks.push(t),this._receivedLength+=t.length}if(!n.ok&&(!n.status||n.status>399))throw this.error={status:n.status,statusText:n.statusText},Error();let l=(0,o.mergeUint8Arrays)(this._dataChunks).buffer;this._config.onDataReady("text"!==this.mode?l:new TextDecoder("utf-8").decode(l)),this._config.onStatsReady(this._getNetworkStats()),this.realUrl!==this.requestUrl&&this._config.onRedirectDetected(this.requestUrl,this.realUrl),this._config.onChangeState(s.ELoadingState.LOADED,{realUrl:n.url,status:n.status})}catch(e){if(this._isAborted){this._config.onStatsReady(this._getNetworkStats()),this._config.onChangeState(s.ELoadingState.ABORTED);return}this.error||(this.error={status:-1,statusText:e.toString()}),this._config.onError(this.error),this._config.onChangeState(s.ELoadingState.ERROR,{status:this.error.status})}}_getNetworkStats(){let e=Date.now()-this._startLoadTimestamp,t="text"===this.mode?"text":"binary";return(0,n.getNetworkStats)(this.requestUrl,e,this._receivedLength,t)}}}),s("aoPbh",function(t,r){e(t.exports,"mergeUint8Arrays",function(){return o});let o=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t}}),s("lYhjM",function(t,r){e(t.exports,"ELoadingState",function(){return a});var o,a=((o={}).UNKNOWN="unknown",o.LOADING="loading",o.LOADED="loaded",o.ABORTED="aborted",o.ERROR="error",o.DESTROYED="destroyed",o)}),s("lR17I",function(t,r){e(t.exports,"getNetworkStats",function(){return a});let o=(e,t,r)=>{if(!globalThis.performance||!globalThis.performance.getEntriesByName)return null;let o=globalThis.performance.getEntriesByName(e)[0];if(!o)return null;let{connectStart:a,connectEnd:s,domainLookupEnd:n,duration:i,domainLookupStart:l,encodedBodySize:d,responseStart:u,requestStart:c}=o,h=(d||t)/1024;return globalThis.performance.clearResourceTimings(),{connectDuration:s-a,domainLookupDuration:n-l,sizeInKb:h,ttfb:u-c,downloadDuration:i,calculatedSpeed:h/(i/1e3)*8,type:r,url:e}},a=(e,t,r,a)=>o(e,r,a)||{connectDuration:0,domainLookupDuration:0,sizeInKb:r/1024,ttfb:0,url:e,downloadDuration:t,calculatedSpeed:r/1024/(t/1e3)*8,type:a}});var n=a("gMZQX"),i=a("j9q3y");const l=new Map;self.addEventListener("message",({data:e})=>{if(e.type)switch(e.type){case n.ENetworkLoadFetchNetworkEvent.ABORT:{let t=l.get(e.payload.url);t&&t.abort();break}case n.ENetworkLoadFetchNetworkEvent.DESTROY:{let t=l.get(e.payload.url);t&&t.abort(),l.delete(e.payload.url);break}case n.ENetworkLoadFetchNetworkEvent.FETCH:{let t=new i.NetworkLoadFetch({requestCustomReferer:e.payload.requestCustomReferer,onDataReady:t=>{self.postMessage({type:n.ENetworkLoadFetchNetworkEvent.DATA_READY,payload:{binaryData:t,url:e.payload.url}})},onChangeState:(t,r)=>{self.postMessage({type:n.ENetworkLoadFetchNetworkEvent.CHANGE_STATE,payload:{newState:t,url:e.payload.url,metadata:r}})},onStatsReady:t=>{self.postMessage({type:n.ENetworkLoadFetchNetworkEvent.STATS_READY,payload:{stats:t,url:e.payload.url}})},onError:t=>{self.postMessage({type:n.ENetworkLoadFetchNetworkEvent.ERROR,payload:{error:t,url:e.payload.url}})},onRedirectDetected:(e,t)=>{self.postMessage({type:n.ENetworkLoadFetchNetworkEvent.REDIRECT_DETECTED,payload:{url:e,responseUrl:t}})}});t.fetch(e.payload.url,e.payload.mode),l.set(e.payload.url,t)}}});';var tQ=k("eQOGK"),sZ=k("lYhjM"),s1=k("gMZQX"),s2=k("j9q3y");let s3=[sZ.ELoadingState.ERROR,sZ.ELoadingState.LOADED,sZ.ELoadingState.ABORTED],s4=new Map,s8=async(e="",t)=>{let s=s4.get(e);return!s&&t&&(s=new Worker(URL.createObjectURL(new Blob([`${I(s0)}`],{type:"application/javascript"}))),s4.set(e,s)),s||null},s6=async e=>{let t=await s8(e);t&&t.terminate(),s4.delete(e)},s5=class{constructor(e,t){if(this.data=null,this.error=null,this.stats=null,this.realUrl="",this._state=sZ.ELoadingState.UNKNOWN,this._retriesAmount=0,this._timeoutAbortHandler=null,this._retryTimeoutHandler=null,this._logger=eO("Doppio - NetworkLoader"),this._fetcherWorker=null,this._fetcherSimple=null,this._workerMode=!1,this._eventBus=t,!e.url||!e.onStateChanged)throw Error("Invalid config");this._workerMode=!!e.workerMode,this._config=e,this._logger.debug("Created with config",e),this._recreateFetcherAndAutoload()}startLoad(){return this._state===sZ.ELoadingState.UNKNOWN&&(this._armTimeoutAbort(),this._logger.debug(`Starting load ${this._config.url}`),this._startAsyncLoad(),!0)}cancel(e){this._disarmTimeoutAbort(),this._disarmRetryTimeout(),this.error={status:-1,statusText:`Cancelled because of ${e??"unknown reason"}`},s3.includes(this._state)||(this._logger.warn(`${this._config.url} loading was cancelled with reason ${e}, current status is ${this._state}`),this._workerMode?this._fetcherWorker?.postMessage({type:s1.ENetworkLoadFetchNetworkEvent.ABORT,payload:{url:this._config.url}}):this._fetcherSimple?.abort())}destroy(){s3.includes(this._state)||(this.cancel("Destroyed"),this._state=sZ.ELoadingState.DESTROYED),this._disarmTimeoutAbort(),this._disarmRetryTimeout(),this.data=null,this.error=null,this._removeFetcherFromWorker()}_onAbortTimeoutFired(){this._logger.info(`${this._config.url} loading timeout`),this.cancel("Loading timeout")}_armRetryTimeout(){this._logger.info(`Retry loading ${this._retriesAmount} time`),this._disarmRetryTimeout(),this._setNewState(sZ.ELoadingState.UNKNOWN),this._retriesAmount++,this._retryTimeoutHandler=globalThis.setTimeout(()=>{this.startLoad()},2**this._retriesAmount)}_disarmRetryTimeout(){this._retryTimeoutHandler&&globalThis.clearTimeout(this._retryTimeoutHandler)}_armTimeoutAbort(){if(!this._config.loadingTimeout||this._config.loadingTimeout<=0){this._logger.debug("LoadingTimeout is not defined or below zero! Skipping abort timeout arming");return}this._logger.debug("Arming loading abort timeout"),this._timeoutAbortHandler&&(this._logger.debug("Another timeout already armed. Cancel it"),this._disarmTimeoutAbort()),this._timeoutAbortHandler=setTimeout(()=>{this._onAbortTimeoutFired()},this._config.loadingTimeout)}_disarmTimeoutAbort(){this._timeoutAbortHandler&&(this._logger.debug("Disarming abort timeout"),clearTimeout(this._timeoutAbortHandler))}_setNewState(e,t){if(this._state!==e){if(e===sZ.ELoadingState.LOADED&&this._logger.verbose(`${this._config.url} loading finished`),s3.includes(e)&&(this._eventBus.publish(t8.events.networkRequestSettled,{response:{url:this.url,body:this.data,timestamp:performance.now(),...t||{}}}),this._removeFetcherFromWorker(),this._disarmTimeoutAbort()),this._logger.verbose(`Loading ${this._config.url}, state transition: ${this._state} -> ${e}`),[(0,sZ.ELoadingState).ABORTED,(0,sZ.ELoadingState).ERROR].includes(e)&&this._state!==sZ.ELoadingState.DESTROYED&&this._config.maxRetries&&this._config.baseRetryTimeout&&this._retriesAmount{this.startLoad()}))}_handleDataReady(e){this.data=e}_handleLoadStatsReady(e){this.stats=e,this._eventBus.publish(t8.stats.statsReady,e)}_handleError(e){this.error=e,this._logger.warn(`Cannot load ${this._config.url}`,e)}_handleRedirectDetected(e,t){this._eventBus.publish(t8.events.browserRedirectDetected,{requestUrl:e,responseUrl:t})}_handleWorkerMessage({data:e}){if(e.payload.url===this._config.url&&e.type)switch(e.type){case s1.ENetworkLoadFetchNetworkEvent.DATA_READY:this._handleDataReady(e.payload.binaryData);break;case s1.ENetworkLoadFetchNetworkEvent.CHANGE_STATE:this._setNewState(e.payload.newState,e.payload.metadata);break;case s1.ENetworkLoadFetchNetworkEvent.STATS_READY:this._handleLoadStatsReady(e.payload.stats);break;case s1.ENetworkLoadFetchNetworkEvent.ERROR:this._handleError(e.payload.error);break;case s1.ENetworkLoadFetchNetworkEvent.REDIRECT_DETECTED:this._handleRedirectDetected(e.payload.url,e.payload.responseUrl)}}get url(){return this._config.url}};(0,U.__decorate)([tQ.default],s5.prototype,"_setNewState",null),(0,U.__decorate)([tQ.default],s5.prototype,"_handleDataReady",null),(0,U.__decorate)([tQ.default],s5.prototype,"_handleLoadStatsReady",null),(0,U.__decorate)([tQ.default],s5.prototype,"_handleError",null),(0,U.__decorate)([tQ.default],s5.prototype,"_handleRedirectDetected",null),(0,U.__decorate)([tQ.default],s5.prototype,"_handleWorkerMessage",null);var tQ=k("eQOGK");let s9=class extends tj{constructor(e){super("fragmentLoader",e),this.state=tK.OK,this.status="Idle",this.groups=["loader"],this.additionalInfo={loadingFragments:{}},this._lastRequestedFragments=[],this._pendingFragments=[],this._loaders=[],this._logger=eO("Doppio - FragmentLoader"),this._fragmentsDetectedSubscription=this._eventBus.subscribe(tY.fragments.fragmentsDetected,this._onFragmentsDetected),this._fragmentAddedToBufferSubscription=this._eventBus.subscribe(tz.fragmentAdded,this._onFragmentAddedToBuffer),this._fragmentHistoryReadyToPrintSubscription=this._eventBus.subscribe(sL.fragments.fragmentHistoryReadyForPrint,this._onFragmentHistoryReadyToPrint),this._logger.info("Instance created")}destroy(){super.destroy(),this._loaders.forEach(e=>{e.destroy()}),this._eventBus.unsubscribe(this._fragmentsDetectedSubscription),this._eventBus.unsubscribe(this._fragmentAddedToBufferSubscription),this._eventBus.unsubscribe(this._fragmentHistoryReadyToPrintSubscription),this._logger.info("Destroyed")}_handleConfigUpdated(){}_onFragmentsDetected(e){this.status="Handling new fragments",this._logger.debug("Fragments was requested to load",e.map(e=>e.getMsnPn()));let t=e.filter(e=>!this._lastRequestedFragments.find(t=>t.url===e.url));this._logger.verbose("Actual fragments is",t.map(e=>e.getMsnPn())),this._pendingFragments=this._pendingFragments.concat(t),t.forEach(e=>{this._eventBus.publish(sL.fragments.fragmentLoadingStarted,e),this.additionalInfo.loadingFragments.url=sZ.ELoadingState.UNKNOWN,this._addFragmentToQueue(e.url,e.requestedLoadingTimeout,e)}),this._lastRequestedFragments=e}_onFragmentAddedToBuffer(e){e.goToLifecycleStage("addedToBuffer")}_onFragmentLoadAborted(e){e.goToLifecycleStage("loadDataAborted")}_onFragmentHistoryReadyToPrint(e){this._logger.info(e.historyString)}_addFragmentToQueue(e,t=this.config?.fragmentLoadingTimeout,s){this._logger.verbose(`Requesting ${e} to load; Fragment ${s.getMsnPn()}`),s.goToLifecycleStage("loadDataStart");let i=new s5({url:e,autoLoad:!0,mode:"arrayBuffer",onStateChanged:this._onLoaderStateChanged,loadingTimeout:t,workerMode:this.config.workerMode},this._eventBus);this._loaders.push(i)}_onLoaderStateChanged(e,t,s){if(this.additionalInfo.loadingFragments[s.url]=t,![(0,sZ.ELoadingState).LOADED,(0,sZ.ELoadingState).ERROR,(0,sZ.ELoadingState).ABORTED].includes(t))return;this._logger.verbose(`Loader state changed: ${e} -> ${t}`);let i=this._pendingFragments.find(e=>e.url===s.url);if(i&&(i.stats=s.stats,i.data=s.data),!i){this._logger.warn("Downloaded fragment was not even planned. Ignoring it",{url:s.url});return}s.error&&(i.error=s.error),t===sZ.ELoadingState.LOADED&&(this._logger.debug(`${s.url} fragment downloaded (${i.getMsnPn()})`),i.goToLifecycleStage("loadDataEnd"),delete this.additionalInfo.loadingFragments[s.url],this._eventBus.publish(sL.fragments.fragmentLoaded,i)),t===sZ.ELoadingState.ERROR&&(this._lastRequestedFragments=this._lastRequestedFragments.filter(e=>e.url!==s.url),this._logger.debug(`${s.url} fragment loading error (${i.getMsnPn()})`),this._onFragmentLoadAborted(i),this._eventBus.publish(sL.fragments.fragmentLoadingError,i)),t===sZ.ELoadingState.ABORTED&&(this._lastRequestedFragments=this._lastRequestedFragments.filter(e=>e.url!==s.url),this._logger.debug(`${s.url} fragment loading aborted (${i.getMsnPn()})`),this._onFragmentLoadAborted(i),this._eventBus.publish(sL.fragments.fragmentLoadingError,i)),this._pendingFragments=this._pendingFragments.filter(e=>e!==i),this._loaders=this._loaders.filter(e=>e!==s),this.status=this._loaders.length?"Loading fragments":"Idle"}};(0,U.__decorate)([tQ.default],s9.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],s9.prototype,"_onFragmentsDetected",null),(0,U.__decorate)([tQ.default],s9.prototype,"_onFragmentAddedToBuffer",null),(0,U.__decorate)([tQ.default],s9.prototype,"_onFragmentLoadAborted",null),(0,U.__decorate)([tQ.default],s9.prototype,"_onFragmentHistoryReadyToPrint",null),(0,U.__decorate)([tQ.default],s9.prototype,"_onLoaderStateChanged",null);var U=(k("a8VW4"),k("a8VW4"));let s7=e=>{try{return!!new URL(e).origin}catch(e){return!1}};var tQ=k("eQOGK");let ie=class e{static #e=this._logger=eO("Doppio - Fragment");constructor(t,s,i){this._shouldLogHistory=!1,this._history=[],this._hasLifecycleEnded=!1,this._isStuckTimer=null,this._lastTs=Date.now(),Object.assign(this,t),this._eventBus=s,this._shouldLogHistory=i||!1,this.duration=t.duration,this.msn=t.msn,this.pn=t.pn,t.playlistUrl||t.fragmentUrl?this.url=e._buildUrl(t.playlistUrl,t.fragmentUrl):this.url=t.url,e._logger.verbose(`Fragment ${this.getMsnPn()} created`),this.goToLifecycleStage("created")}getMsnPn(){return`${this.msn}/${this.pn||0}`}goToLifecycleStage(e){if(this._clearStuckTimer(),!this._shouldLogHistory||this._hasLifecycleEnded)return;let t=Date.now();this._history.push({event:e,timeSincePreviousEvent:t-this._lastTs}),this._lastTs=t,"loadDataAborted"===e?(this._hasLifecycleEnded=!0,this._publishHistoryReadyForPrint("Fragments lifecycle: ABORTED")):"addedToBuffer"===e?(this._hasLifecycleEnded=!0,this._publishHistoryReadyForPrint("Fragments lifecycle: SUCCESS")):this._isStuckTimer=setTimeout(this._handleFragmentStuck,3e3)}static _buildUrl(e,t){if(s7(t))return t;let s=new URL(e);if(t.startsWith("/"))return`${s.origin}${t}`;let i=s.pathname.split("/");return i.pop()||i.pop(),`${s.origin}/${i.concat(t).join("/")}`}_handleFragmentStuck(){this._publishHistoryReadyForPrint("Fragments lifecycle: STUCK")}_publishHistoryReadyForPrint(e){this._eventBus?.publish(sL.fragments.fragmentHistoryReadyForPrint,{historyString:`${e} ${this.getMsnPn()}:${this._history.map(e=>`Event: ${e.event}, ${e.timeSincePreviousEvent}ms since previous event`).join("\n")}`})}_clearStuckTimer(){this._isStuckTimer&&clearTimeout(this._isStuckTimer)}};(0,U.__decorate)([tQ.default],ie.prototype,"_handleFragmentStuck",null);var U=k("a8VW4"),it={},is={};function ii(e,t){return(is=ii=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e}).__esModule=!0,is.default=is,ii(e,t)}(is=ii).__esModule=!0,is.default=is,(it=function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,is(e,t)}).__esModule=!0,it.default=it;var ir=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var s=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(s,1),s>-1},t.trigger=function(e){var t=this.listeners[e];if(t){if(2==arguments.length)for(var s=t.length,i=0;i-1;t=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)},t}(ir),ih=function(e){var t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||""),s={};return t[1]&&(s.length=parseInt(t[1],10)),t[2]&&(s.offset=parseInt(t[2],10)),s},ic=function(e){for(var t,s=e.split(RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))')),i={},r=s.length;r--;)""!==s[r]&&((t=/([^=]*)=(.*)/.exec(s[r]).slice(1))[0]=t[0].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^['"](.*)['"]$/g,"$1"),i[t[0]]=t[1]);return i},i_=function(e){function t(){var t;return(t=e.call(this)||this).customParsers=[],t.tagMappers=[],t}I(it)(t,e);var s=t.prototype;return s.push=function(e){var t,s,i=this;if(0!==(e=e.trim()).length){if("#"!==e[0]){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce(function(t,s){var i=s(e);return i===e?t:t.concat([i])},[e]).forEach(function(e){for(var r=0;r0&&(o.duration=t.duration),0===t.duration&&(o.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=a},key:function(){if(!t.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if("NONE"===t.attributes.METHOD){r=null;return}if(!t.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if("com.apple.streamingkeydelivery"===t.attributes.KEYFORMAT){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:t.attributes};return}if("com.microsoft.playready"===t.attributes.KEYFORMAT){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:t.attributes.URI};return}if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===t.attributes.KEYFORMAT){if(-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(t.attributes.METHOD)){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if("SAMPLE-AES-CENC"===t.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==t.attributes.URI.substring(0,23)){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(t.attributes.KEYID&&"0x"===t.attributes.KEYID.substring(0,2))){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:t.attributes.KEYFORMAT,keyId:t.attributes.KEYID.substring(2)},pssh:function(t){for(var s=I(iu).atob?I(iu).atob(t):(0,e.Buffer).from(t,"base64").toString("binary"),i=new Uint8Array(s.length),r=0;re.reduce((e,t)=>(t.startTs=e.prevStart,t.endTs=t.startTs+t.duration,e.prevStart=t.endTs,e.parts.push(t),e),{parts:[],prevStart:t}).parts,iy=(e,t={})=>{let s=e.mediaSequence,i=e.segments.map((e,t)=>({...e,uri:e.uri,msnNumber:s+t,partNumber:0,parts:(e?.parts||[]).map((e,i)=>({...e,msnNumber:s+t,partNumber:i}))})).map(e=>(e.parts=e.dateTimeObject?ib(e.parts,e.dateTimeObject.getTime()/1e3):e.parts,e)),r=s+i.length,n=(e.preloadSegment?.parts||[]).map((e,t)=>({...e,msnNumber:r,partNumber:t})),a=(e.preloadSegment?.preloadHints||[]).map((e,t)=>({...e,msnNumber:r,partNumber:t+n.length})),o=i.slice(-1)[0],l={...e.preloadSegment,parts:e.preloadSegment&&o.dateTimeObject?ib(n,o.dateTimeObject.getTime()/1e3+o.duration):n,preloadHints:a,msnNumber:r,partNumber:0},u={...e,segments:i,preloadSegment:l};return t.partHoldBack&&(u.partHoldBack=t.partHoldBack),u},iv=class extends tj{constructor(e,t,s){super(t,s),this._lastPlaylistContent="",this._samePlaylistsCount=0,this._isActive=!0,this._currentPlaylistLoader=null,this._url=null,this._logger=eO(`Doppio - ${e}`),this._lifecycleEventReporter=sc("playlistRotator",this._eventBus),this._logger.info("Instance created")}destroy(){super.destroy(),this._isActive=!1,this._logger.info("Destroyed")}_onPlaylistLoadingStateChanged(e,t){if(!this._isActive){this._logger.warn("Loader was destroyed, but we are trying to load handle playlist load state change!");return}if(!this._currentPlaylistLoader||[(0,sZ.ELoadingState).ABORTED,(0,sZ.ELoadingState).ERROR].includes(t)){this._lifecycleEventReporter(`Loading error reported, ${this._currentPlaylistLoader?.error}`),this._logger.warn(`Playlist loader reported ${t===sZ.ELoadingState.ERROR?"error":"as aborted"} (${this._currentPlaylistLoader?.error?.statusText||"no error"} with status ${this._currentPlaylistLoader?.error?.statusText||"no status"}). Planning next load`),this._eventBus.publish(tY.playlists.playlistLoadingError,{error:this._currentPlaylistLoader?.error}),t===sZ.ELoadingState.ERROR&&this._currentPlaylistLoader?.error?.status.toString()[0]==="4"&&(this._logger.warn("Playlist loading reported 4xx status. Requesting start over"),this._eventBus.publish(tJ.requestRestartFromMain,{})),this._currentPlaylistLoader=null,this._planNextLoad();return}if(t!==sZ.ELoadingState.LOADED)return;if(!this._isPlaylistValid(this._currentPlaylistLoader.data)){this._logger.warn("Playlist seems to be invalid. Plan next load"),this._currentPlaylistLoader=null,this._planNextLoad();return}this._eventBus.publish(tY.playlists.playlistLoaded,{originalUrl:this._url,realUrl:this._currentPlaylistLoader.realUrl,stats:this._currentPlaylistLoader.stats});let s=this._currentPlaylistLoader.data,i=this._isPlaylistChanged(s);if(this._currentPlaylistLoader=null,!i){this._logger.warn("Loaded playlist is identical to previous one. Skipping it"),this._planNextLoad();return}let r=this._parsePlaylist(s);if(!r){this._logger.warn("Empty playlist parse result! Should restart"),this._eventBus.publish(tJ.requestRestartFromMain,{});return}this._eventBus.publish(tY.playlists.playlistInfo,r),this._lifecycleEventReporter("Playlist loaded"),this._handleParsedPlaylist(r)}_isPlaylistValid(e){return!!e?.trim().length&&e?.includes("#EXT-X-VERSION")}_isPlaylistChanged(e){return this._lastPlaylistContent!==e}_isPlaylistUpToDate(e){if(void 0!==this.config.equalPlaylistsAmountToDecline&&this.config.equalPlaylistsAmountToDecline<1)return!0;if(e===this._lastPlaylistContent){this._samePlaylistsCount++;let{equalPlaylistsAmountToDecline:e=2}=this.config;if(this._samePlaylistsCount>=e)return!1}else this._samePlaylistsCount=0;return this._lastPlaylistContent=e,!0}_parsePlaylist(e){this._logger.verbose("Parsing manifest");try{let t=new im;t.push(e),t.end();let{manifest:s}=t;this._logger.verbose("Manifest parsed");let i=Array.isArray(s?.playlists)&&s.playlists.length>0,r=Array.isArray(s?.segments)&&s.segments.length>0;return i||r||sJ.reportError("Playlist seems to be parsed invalid",{playlistContent:e,playlistUrl:this._url,parsedPlaylistResult:s}),iy(s,{partHoldBack:this.config.partHoldBack?this.config.partHoldBack/1e3:void 0})}catch(t){return sJ.reportError("Could not parse playlist",{playlistContent:e,playlistUrl:this._url}),null}}_isMultiVariantPlaylist(e){return e.playlists&&(!e.segments||Array.isArray(e.segments)&&0===e.segments.length)}_isVODPlaylist(e){return"VOD"===e.playlistType||e.endList}_isSimplePlaylist(e){return!this._isLowLatencyPlaylist(e)&&!this._isVODPlaylist(e)}_isLowLatencyPlaylist(e){return!!e.partInf}_handleFragmentsDetected(e){this._logger.verbose("Detected fragments",e.map(e=>e.getMsnPn())),this._logger.debug("Fragments was detected and extracted. Emitting it"),this._lifecycleEventReporter(`Found fragments ${e.map(({url:e})=>e).join(",")}`),this._eventBus.publish(tY.fragments.fragmentsDetected,e)}_handleLLManifestDetected(e){this._logger.debug("Low-latency playlist detected. Emitting it"),this._eventBus.publish(tY.playlistType.llDetected,e)}_handleVODPlaylist(e){this._logger.debug("VOD playlist detected. Emitting it"),this._eventBus.publish(tY.playlistType.vodDetected,e)}_handleMultivariantManifestDetected(e){let t=e.playlists.reduce((e,t)=>(e[t.attributes.NAME]={name:t.attributes.NAME,bitrate:t.attributes.BANDWIDTH,url:t.uri,width:t.attributes.RESOLUTION.width,height:t.attributes.RESOLUTION.height},e),{});this._logger.verbose("Variants detected",t),this._logger.debug("Multivariant playlist detected. Emitting it"),this._eventBus.publish(tY.playlistType.multivariantDetected,t)}_handleSimplePlaylistDetected(e){this._logger.debug("Simple playlist detected. Emitting it"),this._eventBus.publish(tY.playlistType.simpleDetected,e)}};(0,U.__decorate)([tQ.default],iv.prototype,"_onPlaylistLoadingStateChanged",null);var tQ=k("eQOGK");let iE=class extends iv{constructor(e,t){let{url:s,startManifest:i,initialMSN:r,initialPN:n,lastLoadedFragment:a}=t;super("LLPlaylistRotationController","playlistLoader",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["loader"],this._playlistLoaderTimeout=null,this._nextMSN=-1,this._nextPN=-1,this._partHoldBack=-1,this._lastLoadedFragment=null,this._awaitingFragmentURL=null,this._hasLoadedInitialAmount=!1,this._lifecycleEventReporter("Created"),this._url=s,this._lastLoadedFragment=a,i?this._handleParsedPlaylist(i):(this._nextMSN=Number.isFinite(r)?r:-1,this._nextPN=Number.isFinite(n)?n:-1,this._loadNextPlaylist()),this._onSegmentLoadedListener=this._eventBus.subscribe(sL.fragments.fragmentLoaded,this._onFragmentFinished),this._onSegmentFailedListener=this._eventBus.subscribe(sL.fragments.fragmentLoadingError,this._onFragmentFinished),this._onSegmentAbortedListener=this._eventBus.subscribe(sL.fragments.fragmentLoadingAborted,this._onFragmentFinished),this._onFragmentAddedListener=this._eventBus.subscribe(tz.fragmentAdded,this._onFragmentAdded),this.config.targetBufferMultiplier&&this.config.targetBufferMultiplier<1&&this._logger.warn("Target buffer multiplier set to value lower than 1. It is unsafe to load less than target-duration, forcing no multiplier instead")}destroy(){this._isActive=!1,super.destroy(),this._currentPlaylistLoader?.destroy(),this._currentPlaylistLoader=null,this._logger.info("Destroy controller"),this._eventBus.unsubscribe(this._onSegmentLoadedListener),this._eventBus.unsubscribe(this._onSegmentAbortedListener),this._eventBus.unsubscribe(this._onSegmentFailedListener),this._eventBus.unsubscribe(this._onFragmentAddedListener),this._lifecycleEventReporter("Destroyed")}abortCurrentPlaylistLoading(){this._logger.info("Aborting current loading playlist")}setURL(e,t){if(t){this._url=e;return}this._logger.info(`Setting new url ${e}`),this._currentPlaylistLoader?.destroy(),this._url=e,this._nextPN=-1,this._nextMSN=-1,this._loadNextPlaylist()}_handleConfigUpdated(e){if(e.equalPlaylistsAmountToDecline&&(this._samePlaylistsCount=0),!1===e.lowLatencyMode){let e=this._parsePlaylist(this._lastPlaylistContent);e?this._handleSimplePlaylistDetected(e):this._eventBus.publish(tJ.requestRestartFromMain,{})}}_loadNextPlaylist(){if(!this._isActive){this._logger.warn("Loader was destroying, but we trying to load next playlist!");return}let{playlistLoadingTimeout:e}=this.config;this._logger.debug("Loading next playlist"),this._lifecycleEventReporter(`Loading next playlist with url ${this._url}`),this.status="Loading playlist",this._currentPlaylistLoader&&this._currentPlaylistLoader.cancel(`Another playlist with url ${this._url} scheduled to load`);let t=this._buildUrl();this._currentPlaylistLoader=new s5({url:t,loadingTimeout:e,autoLoad:!0,mode:"text",onStateChanged:this._onPlaylistLoadingStateChanged,workerMode:this.config.workerMode,requestCustomReferer:this.config.sendCustomRefererHeader?x().location?.href:void 0},this._eventBus),this._eventBus.publish(tY.playlists.playlistRequested,{})}_handleParsedPlaylist(e){this._lifecycleEventReporter("Playlist parsed");let t=Math.max(this.config.targetBufferMultiplier,1);if(this._partHoldBack=sP(e,e.targetDuration||2)*t,this._isMultiVariantPlaylist(e)){this._handleMultivariantManifestDetected(e);return}if(this._isSimplePlaylist(e)){this._handleSimplePlaylistDetected(e);return}if(this._isVODPlaylist(e)){this._handleVODPlaylist(e);return}let s=0===(e.preloadSegment.parts||[]).length,i=e.segments.flatMap(t=>t.parts.map(({uri:t,independent:s,partNumber:i,startTs:r,endTs:n,msnNumber:a,duration:o})=>new ie({url:t,independent:s?sX.INDEPENDENT:sX.PART,msn:a,pn:i,duration:o,isTransmuxingBypassRequested:!!e.segments[0].map?.uri,startTs:r,endTs:n},this._eventBus,this.config.shouldLogFragmentsHistory))).concat((e.preloadSegment.parts||[]).map(({uri:t,independent:s=!1,msnNumber:i,partNumber:r,startTs:n,endTs:a,duration:o})=>new ie({url:t,independent:s?sX.INDEPENDENT:sX.PART,msn:i,pn:r,duration:o,isTransmuxingBypassRequested:!!e.segments[0].map?.uri,startTs:n,endTs:a},this._eventBus,this.config.shouldLogFragmentsHistory))).filter(({msn:e,pn:t})=>!this._hasLoadedInitialAmount||e>this._nextMSN||e===this._nextMSN&&t>=this._nextPN),r=i.reverse(),n=r.reduce((e,t)=>(e.currentDuration(e.startTs||0)<(this._lastLoadedFragment?.endTs||0)):-1,o=Math.min(r.length,Math.max(n,a)+this.config.additionalStartParts);this._logger.debug(`Minimal part ${r[o]?.msn}:${r[o]?.pn}(${new Date(r[o]?.startTs||0)})`);let l=r.findIndex(({independent:e},t)=>t>=o&&e===sX.INDEPENDENT);-1===l&&(l=r.length-1),this._logger.debug(`Part to start load from: ${r[l]?.msn}:${r[l]?.pn}`);let u=l>-1?r.slice(0,l+1).reverse():i;if(this.config.blockingMode===tq.WAIT_FOR_PREFETCH_SEGMENT&&Array.isArray(e.preloadSegment.preloadHints)&&e.preloadSegment.preloadHints.length&&(this._awaitingFragmentURL=e.preloadSegment.preloadHints[0]?.uri||null,u.push(...e.preloadSegment.preloadHints.map(({uri:t,msnNumber:s,partNumber:i})=>new ie({url:t,independent:sX.UNKNOWN,msn:s,pn:i,duration:0,isTransmuxingBypassRequested:!!e.segments[0].map?.uri},this._eventBus,this.config.shouldLogFragmentsHistory)))),e.segments[0].map?.uri&&u.unshift(new ie({playlistUrl:this._url||"",fragmentUrl:e.segments[0].map?.uri,duration:0,independent:sX.INDEPENDENT,msn:-1,pn:-1,isTransmuxingBypassRequested:!0,isInitSection:!0},this._eventBus,this.config.shouldLogFragmentsHistory)),this._handleFragmentsDetected(u),this._hasLoadedInitialAmount=!0,this._nextMSN=e.mediaSequence+e.segments.length,this._nextPN=(e.preloadSegment.parts||[]).length,this.additionalInfo.msn=this._nextMSN,this.additionalInfo.pn=this._nextPN,this.status="Awaiting fragment to load next playlist",s&&this._eventBus.publish(tY.playlists.lastPlaylistOfSegmentLoaded,{}),this.config.blockingMode===tq.WAIT_FOR_PLAYLIST){this._loadNextPlaylist();return}}_planNextLoad(){this._playlistLoaderTimeout=x().setTimeout(()=>{this._loadNextPlaylist()},this.config.retryLowLatencyPlaylistTimeout)}_buildUrl(){if(-1===this._nextPN||-1===this._nextMSN)return this._url||"";if(!this._url)return"";let e=new URL(this._url);return e.searchParams.set("_HLS_msn",`${this._nextMSN}`),e.searchParams.set("_HLS_part",`${this._nextPN}`),e.toString()}_onFragmentFinished(e){this._logger.debug(`${e.startTs} -> ${e.endTs} loaded (${e.getMsnPn()})`),this.config.blockingMode===tq.WAIT_FOR_PREFETCH_SEGMENT&&this._awaitingFragmentURL===e.url&&(this._logger.debug("Prefetch segment is ready now, loading next playlist"),this._loadNextPlaylist())}_onFragmentAdded(e){this._lastLoadedFragment=e}};(0,U.__decorate)([tQ.default],iE.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],iE.prototype,"_onFragmentFinished",null),(0,U.__decorate)([tQ.default],iE.prototype,"_onFragmentAdded",null);var U=k("a8VW4"),tQ=k("eQOGK");let iS=class extends iv{constructor(e,t,s){super("SimplePlaylistRotationController","playlistLoader",e),this.state=tK.OK,this.status="Idle",this.groups=["loader"],this.additionalInfo={},this._playlistLoaderTimeout=null,this._lastTargetDuration=2,this._lifecycleEventReporter("Created"),this._url=t,s?this._handleParsedPlaylist(s):this._loadNextPlaylist()}destroy(){this._isActive=!1,super.destroy(),this._currentPlaylistLoader?.destroy(),this._currentPlaylistLoader=null,this._logger.info("Destroy controller"),this._playlistLoaderTimeout&&clearTimeout(this._playlistLoaderTimeout),this._lifecycleEventReporter("Destroyed")}abortCurrentPlaylistLoading(){this._logger.info("Aborting current loading playlist"),this._currentPlaylistLoader?.destroy()}setURL(e,t){if(t){this._url=e;return}this._logger.info(`Setting new url ${e}`),this._currentPlaylistLoader?.destroy(),this._url=e,this._loadNextPlaylist()}_handleConfigUpdated(e){e.equalPlaylistsAmountToDecline&&(this._samePlaylistsCount=0)}_loadNextPlaylist(){if(!this._isActive){this._logger.warn("Loader was destroying, but we trying to load next playlist!");return}let{playlistLoadingTimeout:e}=this.config;this._logger.debug("Loading next playlist"),this._lifecycleEventReporter(`Loading next playlist with url ${this._url}`),this.status="Loading playlist",this._currentPlaylistLoader&&this._currentPlaylistLoader.cancel(`Another playlist with url ${this._url} scheduled to load`),this._url&&(this._currentPlaylistLoader=new s5({url:this._url,loadingTimeout:e,autoLoad:!0,mode:"text",onStateChanged:this._onPlaylistLoadingStateChanged,workerMode:this.config.workerMode,requestCustomReferer:this.config.sendCustomRefererHeader?x().location?.href:void 0},this._eventBus),this._eventBus.publish(tY.playlists.playlistRequested,{}))}_handleParsedPlaylist(e){if(this._lifecycleEventReporter("Playlist parsed"),this._isMultiVariantPlaylist(e)){this._handleMultivariantManifestDetected(e);return}if(this._isLowLatencyPlaylist(e)&&this.config.lowLatencyMode){this._handleLLManifestDetected(e);return}if(this._isVODPlaylist(e)){this._handleVODPlaylist(e);return}if(this._eventBus.publish(tY.playlists.lastPlaylistOfSegmentLoaded,{}),!this._url)return;let t=this._url;this._lastTargetDuration=e.targetDuration||2;let s=e.segments.map(s=>new ie({fragmentUrl:s.uri,playlistUrl:t,duration:s.duration,independent:sX.INDEPENDENT,msn:s.msnNumber,pn:s.partNumber,isTransmuxingBypassRequested:!!e.segments[0].map?.uri},this._eventBus,this.config.shouldLogFragmentsHistory));e.segments[0]?.map?.uri&&s.unshift(new ie({fragmentUrl:e.segments[0].map.uri,playlistUrl:t,independent:sX.INDEPENDENT,msn:-1,pn:-1,isTransmuxingBypassRequested:!0,duration:0,isInitSection:!0},this._eventBus,this.config.shouldLogFragmentsHistory)),this._handleFragmentsDetected(s),this._planNextLoad()}_planNextLoad(){let e=this._getNextPlaylistLoadTimeout();this._currentPlaylistLoader&&(this._currentPlaylistLoader.destroy(),this._currentPlaylistLoader=null),this._logger.info(`Expecting next load in ${e} ms`),this._lifecycleEventReporter("Awaiting next loading"),this.status="Awaiting next loading",this._playlistLoaderTimeout=globalThis.setTimeout(()=>{this._loadNextPlaylist()},e)}_getNextPlaylistLoadTimeout(){let{forceStaticPlaylistLoadingTimeout:e,staticPlaylistLoadingTimeoutInDurations:t}=this.config;if(e&&t)return this._logger.verbose(`forceStaticPlaylistLoadingTimeout is set to true and staticPlaylistLoadingTimeoutInDurations is set to ${t}. Using static timeout`),t*this._lastTargetDuration*1e3;let s=!this.config.disableRotateTimeoutIncrease&&this._samePlaylistsCount>1?1.5:1;return this._logger.verbose(`There was ${this._samePlaylistsCount} same playlists. Multiplier is ${s}. Target duration is ${this._lastTargetDuration}`),s*this._lastTargetDuration*1e3}};(0,U.__decorate)([tQ.default],iS.prototype,"_handleConfigUpdated",null);var U=k("a8VW4"),sZ=k("lYhjM"),tQ=k("eQOGK"),iR=((D=iR||{})[D.NONE=0]="NONE",D[D.LOADING=1]="LOADING",D[D.LOADED=2]="LOADED",D[D.ERROR=3]="ERROR",D);let iT=class extends iv{constructor(e,t,s){super("VODPlaylistRotationController","playlistLoader",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={},this._fragments=[],this._lastHandledFragments=[],this._chunksRetryTimeout=null,this._isDurationPositive=!1,this._url=t,this._onFragmentLoadedListener=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoaded,this._onFragmentLoaded),this._onFragmentAbortedListener=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoadingAborted,this._onFragmentLoadingError),this._onFragmentErrorListener=this._eventBus.subscribe(sA.fragmentLoader.fragments.fragmentLoadingError,this._onFragmentLoadingError),this._onBufferMetricsAvailableListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),s?this._handleParsedPlaylist(s):this._loadNextPlaylist()}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onFragmentLoadedListener),this._eventBus.unsubscribe(this._onBufferMetricsAvailableListener),this._eventBus.unsubscribe(this._onFragmentErrorListener),this._eventBus.unsubscribe(this._onFragmentAbortedListener)}setURL(e,t){if(t){this._url=e;return}this._logger.info(`Setting new url ${e}`),this._currentPlaylistLoader?.destroy(),this._url=e,this._loadNextPlaylist()}abortCurrentPlaylistLoading(){this._logger.info("Aborting current loading playlist"),this._currentPlaylistLoader?.destroy()}_handleConfigUpdated(){}_loadNextPlaylist(){let{playlistLoadingTimeout:e,baseVODPlaylistRetryTimeout:t,maxVODPlaylistLoadingRetries:s}=this.config;this._logger.debug("Loading VOD playlist"),this._currentPlaylistLoader&&this._currentPlaylistLoader.cancel(`Another playlist with url ${this._url} scheduled to load`),this._currentPlaylistLoader=new s5({url:this._url||"",loadingTimeout:e,autoLoad:!0,mode:"text",onStateChanged:this._onPlaylistLoadingStateChanged,baseRetryTimeout:t,maxRetries:s,workerMode:this.config.workerMode},this._eventBus)}_onPlaylistLoadingStateChanged(e,t){if(!this._currentPlaylistLoader||[(0,sZ.ELoadingState).ABORTED,(0,sZ.ELoadingState).ERROR].includes(t)){this.state=tK.ERROR,this.additionalInfo={playlistLoadError:this._currentPlaylistLoader?.error},this._logger.warn(`Playlist loader reported ${t===sZ.ELoadingState.ERROR?"error":"as aborted"} (${this._currentPlaylistLoader?.error?.statusText||"no error"} with status ${this._currentPlaylistLoader?.error?.statusText||"no status"}). Planning next load`),this._currentPlaylistLoader=null;return}if(t!==sZ.ELoadingState.LOADED)return;let s=this._currentPlaylistLoader.data;this._currentPlaylistLoader=null;let i=this._parsePlaylist(s);if(!i){this._eventBus.publish(tJ.requestRestartFromMain,{});return}this._eventBus.publish(tY.playlists.playlistInfo,i),this._handleParsedPlaylist(i)}_handleParsedPlaylist(e){if(this._isMultiVariantPlaylist(e)){this._handleMultivariantManifestDetected(e);return}if(this._isLowLatencyPlaylist(e)&&this.config.lowLatencyMode){this._handleLLManifestDetected(e);return}if(this._isSimplePlaylist(e)){this._handleSimplePlaylistDetected(e);return}this.status="Playlist loaded",this._populateVODFragments(e.segments)}_planNextLoad(){}_populateVODFragments(e){let t=0;for(let s=0;s0,this._eventBus.publish(tY.playlists.vodFragmentsInfo,this._fragments)}_loadFragment(e){let t=e.map(({url:e})=>e);e.filter(({readinessState:e,url:s})=>2===e&&t.includes(s)).forEach(e=>{this._logger.info(`Some fragments already loaded, reemitting it: ${e.fragmentIndex}`),this._eventBus.publish(tY.fragments.requestReleaseFromCache,{msn:e.fragmentIndex})});let s=e.filter(({readinessState:e})=>[0].includes(e));s.forEach(e=>e.readinessState=1),this._handleFragmentsDetected(s.map(e=>new ie({msn:e.fragmentIndex,playlistUrl:this._url||"",fragmentUrl:e.url,pn:0,independent:sX.INDEPENDENT,duration:e.fragmentEndTS-e.fragmentStartTS,requestedLoadingTimeout:this.config.disableTimeoutsInVOD?-1:this.config.baseVODFragmentRetryTimeout,startTs:e.fragmentStartTS,endTs:e.fragmentEndTS,isTransmuxingBypassRequested:e.url.endsWith(".mp4")},this._eventBus,this.config.shouldLogFragmentsHistory))),this._lastHandledFragments=t}_onFragmentLoaded(e){this._logger.info(`Fragment ${e.msn} loaded`);let t=this._fragments.find(({fragmentIndex:t})=>t===e.msn);t&&(t.readinessState=2,t.data=e.data,this.additionalInfo.fragments=this._fragments.map(e=>({...e,data:void 0})))}_onFragmentLoadingError(e){let t=this._fragments.find(({fragmentIndex:t})=>t===e.msn);t&&(t.readinessState=3,this._chunksRetryTimeout||(this._chunksRetryTimeout=globalThis.setTimeout(this._retryFragments,this.config.baseVODFragmentRetryTimeout)))}_retryFragments(){this._chunksRetryTimeout=null,this._fragments.filter(({readinessState:e})=>3===e).forEach(e=>e.readinessState=0)}_onBufferMetricsAvailable(e){if(this._fragments.some(({readinessState:e})=>1===e)||!this._isDurationPositive)return;let t=[],{currentTimeRange:s,currentPlaybackPosition:i,isInLastBufferedRange:r,bufferedTimeRanges:n}=e,a=r||!!s&&!n.some(({start:e,end:t})=>e<=s.end+1&&s.end+1<=t),o=i+this.config.VODLoadNextSegmentThreshold/1e3;if(s&&s.end-i!(e<=i&&i<=t))),s||(t=this._findNextFragmentsByTime(i,i)),t.length){this._logger.info(`Loading following fragments ${t.map(({fragmentIndex:e})=>e).join(",")}`);let e=Math.min(...t.map(({fragmentStartTS:e})=>e)),s=Math.max(...t.map(({fragmentEndTS:e})=>e));this._eventBus.publish(tY.fragments.periodFragmentsFound,{startTsOfPeriod:e,endTsOfPeriod:s}),this._loadFragment(t)}}_findNextFragmentsByTime(e,t){return this._fragments.filter(({fragmentEndTS:s,fragmentStartTS:i})=>i<=e&&e<=s||i>=e&&t>=s||i<=t&&t<=s)}};(0,U.__decorate)([tQ.default],iT.prototype,"destroy",null),(0,U.__decorate)([tQ.default],iT.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],iT.prototype,"_onPlaylistLoadingStateChanged",null),(0,U.__decorate)([tQ.default],iT.prototype,"_planNextLoad",null),(0,U.__decorate)([tQ.default],iT.prototype,"_onFragmentLoaded",null),(0,U.__decorate)([tQ.default],iT.prototype,"_onFragmentLoadingError",null),(0,U.__decorate)([tQ.default],iT.prototype,"_retryFragments",null),(0,U.__decorate)([tQ.default],iT.prototype,"_onBufferMetricsAvailable",null);var tQ=k("eQOGK"),iL=((w={}).VOD="VOD",w.LOW_LATENCY="lowLatency",w.SIMPLE="simple",w);let iA=class{constructor(e="simple",t,s){this.state=tK.OK,this.status="Idle",this.additionalInfo={},this.groups=["loader"],this._streamUrl=null,this._aclToken=null,this._playlistsRotator=null,this._actualRenditionReport=null,this._lastAddedFragment=null,this._logger=eO("Doppio - StreamLoader"),this._eventBus=s,this._logger.info("Created"),this._fragmentsLoader=new s9(this._eventBus),this._initialType=e,this._simplePlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.simpleDetected,this._onSimplePlaylistDetected),this._llPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.llDetected,this._onLLPlaylistDetected),this._vodPlaylistDetectedListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.vodDetected,this._onVODPlaylistDetected),this._onSoftResetRequestedListener=this._eventBus.subscribe(tz.requestResetWithOverplay,this._resetPlaylistLoaders),this._onBrowserRedirectDetectedListener=this._eventBus.subscribe(t8.events.browserRedirectDetected,this._onBrowserRedirectDetected),this._onFragmentAddedListener=this._eventBus.subscribe(tz.fragmentAdded,this._onFragmentAdded),this._lastAddedFragment=t}startLoad(e){this._streamUrl=e,this._recreateLoaders()}destroy(){this._logger.info(`Destroying instance, ${this._streamUrl}`),this._fragmentsLoader.destroy(),this._playlistsRotator?.destroy(),this._eventBus.unsubscribe(this._simplePlaylistDetectedListener),this._eventBus.unsubscribe(this._llPlaylistDetectedListener),this._eventBus.unsubscribe(this._vodPlaylistDetectedListener),this._eventBus.unsubscribe(this._onSoftResetRequestedListener),this._eventBus.unsubscribe(this._onFragmentAddedListener),this._eventBus.unsubscribe(this._onBrowserRedirectDetectedListener)}setActualRenditionReport(e){e&&(this._actualRenditionReport=e)}_recreateLoaders(){this.status="Restarting";let e=this._buildUrl();this._logger.debug("Recreate loaders"),e&&(this._fragmentsLoader.destroy(),this._fragmentsLoader=new s9(this._eventBus),this._playlistsRotator?this._playlistsRotator?.setURL(e):this._recreateInitialLoader(),this.status="Working")}_recreateInitialLoader(){switch(this._initialType){case"simple":default:this._onSimplePlaylistDetected();break;case"VOD":this._onVODPlaylistDetected();break;case"lowLatency":this._onLLPlaylistDetected()}}_buildUrl(){return this._streamUrl?`${this._streamUrl}${this._aclToken?"?aclToken="+this._aclToken:""}`:null}_onFragmentAdded(e){this._lastAddedFragment=e}_onSimplePlaylistDetected(e){if(this._playlistsRotator instanceof iS)return;this._eventBus.publish(sA.streamLoader.playlistRotatorTypeChanged,"simple"),this._logger.info("Simple playlist detected, switching to simple loader");let t=this._buildUrl();t&&(this._playlistsRotator?.destroy(),this._playlistsRotator=new iS(this._eventBus,t,e),this.additionalInfo.playlistRotatorType="SimplePlaylistRotator")}_onVODPlaylistDetected(e){if(this._playlistsRotator instanceof iT)return;this._eventBus.publish(sA.streamLoader.playlistRotatorTypeChanged,"VOD"),this._logger.info("VOD playlist detected, switching to VOD loader");let t=this._buildUrl();t&&(this._playlistsRotator?.destroy(),this._playlistsRotator=new iT(this._eventBus,t,e),this.additionalInfo.playlistRotatorType="VODPlaylistRotator")}_onLLPlaylistDetected(e){if(this._playlistsRotator instanceof iE)return;this._eventBus.publish(sA.streamLoader.playlistRotatorTypeChanged,"lowLatency"),this._logger.info("LL Playlist detected, switching to ll loader");let t=this._buildUrl();t&&(this._playlistsRotator?.destroy(),this._playlistsRotator=new iE(this._eventBus,{url:t,startManifest:e,initialMSN:this._actualRenditionReport?.lastMsn,initialPN:this._actualRenditionReport?.lastPart,lastLoadedFragment:this._lastAddedFragment}),this.additionalInfo.playlistRotatorType="LowLatencyPlaylistRotator")}_resetPlaylistLoaders(){this._playlistsRotator?.abortCurrentPlaylistLoading(),this.status="Idle"}_onBrowserRedirectDetected({responseUrl:e}){this._streamUrl=e;let t=this._buildUrl();t&&this._playlistsRotator?.setURL(t,!0)}get additionalModules(){let e={};return this._playlistsRotator&&(e.playlistRotator=this._playlistsRotator),this._fragmentsLoader&&(e.fragmentLoader=this._fragmentsLoader),e}};(0,U.__decorate)([tQ.default],iA.prototype,"_onFragmentAdded",null),(0,U.__decorate)([tQ.default],iA.prototype,"_onSimplePlaylistDetected",null),(0,U.__decorate)([tQ.default],iA.prototype,"_onVODPlaylistDetected",null),(0,U.__decorate)([tQ.default],iA.prototype,"_onLLPlaylistDetected",null),(0,U.__decorate)([tQ.default],iA.prototype,"_resetPlaylistLoaders",null),(0,U.__decorate)([tQ.default],iA.prototype,"_onBrowserRedirectDetected",null);var tQ=k("eQOGK");let iP=class extends tj{constructor(e){super("resolutionsManager",e),this.state=tK.OK,this.status="Idle",this.additionalInfo={currentResolution:""},this.groups=["resolutionsManager"],this._currentResolutionsDecreasing=[],this._currentResolution=null,this._awaitingResolution=null,this._lastMSN=-1,this._lastDSN=-1,this._lastPDT=-1,this._url="",this._isAutoEnabled=!0,this._logger=eO("Doppio - ResolutionManager"),this._lastPlaylistRotatorType=iL.SIMPLE,this._streamLoader=null,this._restartTimeout=null,this._renditionReports=[],this._lastLoadedFragment=null,this._codecsByResolutions={},this._multiVariantsPlaylistDetectionListener=this._eventBus.subscribe(sA.playlistRotator.playlistType.multivariantDetected,this._onMultiVariantsPlaylists),this._onResolutionChangeRequestedListener=this._eventBus.subscribe(tJ.requestResolutionChange,this._onResolutionChangeRequested),this._onPlaylistInfoAvailableListener=this._eventBus.subscribe(sA.playlistRotator.playlists.playlistInfo,this._onPlaylistInfoAvailable),this._onRestartFromMainRequestedListener=this._eventBus.subscribe(tJ.requestRestartFromMain,this._restartFormMain),this._onPlaylistRotatorTypeChangedListener=this._eventBus.subscribe(sA.streamLoader.playlistRotatorTypeChanged,this._onPlaylistRotatorTypeChanged),this._onEndOfSegmentPlaylistLoadedListener=this._eventBus.subscribe(tY.playlists.lastPlaylistOfSegmentLoaded,this._onEndOfSegmentPlaylistLoaded),this._onFragmentAddedListener=this._eventBus.subscribe(tz.fragmentAdded,this._onFragmentAdded)}destroy(){super.destroy(),this._restartTimeout&&(clearTimeout(this._restartTimeout),this._restartTimeout=null),this._eventBus.unsubscribe(this._multiVariantsPlaylistDetectionListener),this._eventBus.unsubscribe(this._onResolutionChangeRequestedListener),this._eventBus.unsubscribe(this._onPlaylistInfoAvailableListener),this._eventBus.unsubscribe(this._onRestartFromMainRequestedListener),this._eventBus.unsubscribe(this._onPlaylistRotatorTypeChangedListener),this._eventBus.unsubscribe(this._onEndOfSegmentPlaylistLoadedListener),this._eventBus.unsubscribe(this._onFragmentAddedListener),this._streamLoader?.destroy(),this._codecsByResolutions={}}setUrl(e){this._url!==e&&(this._lastPDT=-1,this._lastDSN=-1,this._lastMSN=-1,this._logger.info("Setting new url"),this._url=e,this._currentResolution=null,this._currentResolutionsDecreasing=[],this._restart())}setResolution(e,t=!1){if(this._awaitingResolution=null,e.name===this._currentResolution?.name)return;if(this._url&&tU(this._url).streamId&&tU(e.url).streamId&&tU(this._url).streamId!==tU(e.url).streamId){this._logger.warn(`Tried to set resolution with ${e.url}, but the current url is ${this._url}. Skipping since they don't match`);return}let s=this._currentResolution;this._logger.info(`Resolution changed: ${this._currentResolution?.name} -> ${e.name}`),this._currentResolution=e,this.additionalInfo.currentResolution=e.name,this._eventBus.publish(tJ.resolutionChanged,e),this._codecsByResolutions[e.url]&&this._eventBus.publish(tz.changeCodec,{codec:this._codecsByResolutions[e.url]}),t&&s&&this._eventBus.publish(tJ.resolutionAutoChanged,{prevResolution:s.name,nextResolution:e.name}),this._restart()}setNearestResolutionByWidth(e){return this._setResolutionByCriteria(({width:t})=>t<=e)}setNearestResolutionByHeight(e){return this._setResolutionByCriteria(({height:t})=>t<=e)}setNearestResolutionByBitrate(e){return this._setResolutionByCriteria(({bitrate:t})=>t<=e+this.config.initialResolutionBitrateThreshold)}setResolutionByName(e){return this._setResolutionByCriteria(({name:t})=>t===e)}toggleAutoResolution(e){this._isAutoEnabled=e}restart(){this._restart()}_handleConfigUpdated(){}_setResolutionByCriteria(e){let t=this._findResolutionByCriteria(e);if(!t){this._logger.warn("There are no any resolution in current stream"),this.state=tK.ERROR,this._awaitingResolution=null;return}if(this.config.awaitForSegmentEndToSwitchManual&&this._currentResolution&&this._lastMSN>-1){this._logger.info("Await for segment end for switch resolution"),this._awaitingResolution=t;return}this.setResolution(t)}_findResolutionByCriteria(e){if(!this._currentResolutionsDecreasing.length)return null;if(1===this._currentResolutionsDecreasing.length)return this._currentResolutionsDecreasing[0];let t=this._currentResolutionsDecreasing.find(e);return t||(this._eventBus.publish(tJ.resolutionNotFound,{}),!1!==this.config.useFallbackResolutionIfResolutionNotFound)?t||this._currentResolutionsDecreasing.slice(-1)[0]:null}_restartFormMain(){this._currentResolution=null,this._logger.info("Restart from main"),this._renditionReports=[],this._eventBus.publish(tz.requestResetWithOverplay,{}),this._restart(2e3)}_restart(e=0){this._restartTimeout&&(clearTimeout(this._restartTimeout),this._restartTimeout=null),this._logger.info("Restart resolution manager"),this._destroyStreamLoader(),this._restartTimeout=setTimeout(()=>{this._recreateStreamLoader()},e)}_destroyStreamLoader(){this._streamLoader?.destroy(),this._streamLoader=null,this.status="Awaiting resolutions"}_recreateStreamLoader(){this._destroyStreamLoader(),this._streamLoader=new iA(this._lastPlaylistRotatorType,this._lastLoadedFragment,this._eventBus),this._streamLoader.setActualRenditionReport(this._getActualRenditionReport()),this._streamLoader.startLoad(this._currentResolution?this._currentResolution.url:this._url)}_onMultiVariantsPlaylists(e){if(this._currentResolutionsDecreasing=Object.values(e).sort((e,t)=>t.bitrate-e.bitrate),this.additionalInfo.resolutionsAvailable=this._currentResolutionsDecreasing.map(({name:e})=>e),this._eventBus.publish(tJ.resolutionsAvailable,this._currentResolutionsDecreasing),this.config.initialResolutionBitrate){this.setNearestResolutionByBitrate(this.config.initialResolutionBitrate);return}if(this.config.initialResolutionHeight){this.setNearestResolutionByHeight(this.config.initialResolutionHeight);return}if(this.config.initialResolutionWidth){this.setNearestResolutionByWidth(this.config.initialResolutionWidth);return}this.config.autoloadLowestResolution&&this.setResolution(this._currentResolutionsDecreasing.slice(-1)[0])}_onEndOfSegmentPlaylistLoaded(){this._awaitingResolution&&(this._logger.info("Last playlist of segment loaded. Ready to switch"),this.setResolution(this._awaitingResolution,!0))}_onFragmentAdded(e){this._lastLoadedFragment=e}_onPlaylistInfoAvailable(e){let{mediaSequence:t,discontinuitySequence:s,segments:i}=e;if(e.playlists&&(this._codecsByResolutions=e.playlists.reduce((e,t)=>t.attributes?.CODECS?{...e,[t.uri]:t.attributes.CODECS}:e,{})),void 0===t||void 0===s||void 0===i)return;let r=i[0]?.dateTimeObject?.getTime()||0;-1!==this._lastPDT&&-1!==this._lastDSN&&-1!==this._lastMSN&&(s!==this._lastDSN&&(this._logger.info("DSN changed. Requesting overplay"),this._eventBus.publish(tz.requestResetWithOverplay,{})),Math.abs(r-this._lastPDT)>this.config.maxPlaylistTimeDifference&&(this._logger.warn("PDT delta reached max delta. Restarting from main"),this._restartFormMain())),this._lastMSN=t,this._lastDSN=s,this._lastPDT=r,this._renditionReports=e.renditionReports||[],this._streamLoader?.setActualRenditionReport(this._getActualRenditionReport())}_onResolutionChangeRequested(e){if(this._isAutoEnabled){if(this.config.awaitForSegmentEndToSwitch){this._logger.info("Await for segment end for switch resolution"),this._awaitingResolution=e;return}this.setResolution(e,!0)}}_getActualRenditionReport(){if(!this._renditionReports.length)return null;try{return this._renditionReports.find(({uri:e})=>new URL(e).pathname===new URL(this._currentResolution?.url||"").pathname)||null}catch(e){return null}}_onPlaylistRotatorTypeChanged(e){this._lastPlaylistRotatorType=e}get additionalModules(){return this.additionalInfo.isAutoEnabled=this._isAutoEnabled,this._streamLoader?{streamLoader:this._streamLoader}:{}}};(0,U.__decorate)([tQ.default],iP.prototype,"_handleConfigUpdated",null),(0,U.__decorate)([tQ.default],iP.prototype,"_restartFormMain",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onMultiVariantsPlaylists",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onEndOfSegmentPlaylistLoaded",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onFragmentAdded",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onPlaylistInfoAvailable",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onResolutionChangeRequested",null),(0,U.__decorate)([tQ.default],iP.prototype,"_onPlaylistRotatorTypeChanged",null);var U=k("a8VW4"),tQ=k("eQOGK");let iC=class{constructor(e,t){this._isResolutionSelected=!1,this._eventBus=t,this._sendEvent=e,this._isDebugEnabled=document?.cookie?.includes("__mmpDebug__=1"),this._onPlaylistLoadingStartedListener=this._eventBus.subscribe(tY.playlists.playlistRequested,this._onPlaylistLoadingStarted),this._onResolutionChangedListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChanged),this._onResolutionChangedAutoListener=this._eventBus.subscribe(tJ.resolutionAutoChanged,this._onResolutionAutoChanged),this._onPlaylistLoadedListener=this._eventBus.subscribe(tY.playlists.playlistLoaded,this._onPlaylistLoaded),this._onPlaylistParsedListener=this._eventBus.subscribe(tY.playlists.playlistInfo,this._onPlaylistInfoAvailable),this._onFragmentLoadedListener=this._eventBus.subscribe(sL.fragments.fragmentLoaded,this._onFragmentLoaded),this._onDebuggerConnectedListener=this._eventBus.subscribe(sh,this._onDebuggerConnected),this._onNetworkRequestSettledListener=this._eventBus.subscribe(t8.events.networkRequestSettled,this._onNetworkRequestSettled)}destroy(){this._eventBus.unsubscribe(this._onPlaylistLoadingStartedListener),this._eventBus.unsubscribe(this._onPlaylistLoadedListener),this._eventBus.unsubscribe(this._onPlaylistParsedListener),this._eventBus.unsubscribe(this._onFragmentLoadedListener),this._eventBus.unsubscribe(this._onDebuggerConnectedListener),this._eventBus.unsubscribe(this._onResolutionChangedListener),this._eventBus.unsubscribe(this._onResolutionChangedAutoListener),this._eventBus.unsubscribe(this._onNetworkRequestSettledListener)}_onPlaylistLoadingStarted(){this._isResolutionSelected||this._sendEvent(new CustomEvent(sa.MANIFEST_LOADING))}_onResolutionChanged(){this._isResolutionSelected=!0}_onPlaylistLoaded(e){let{originalUrl:t,realUrl:s,stats:i}=e;if(this._isResolutionSelected){this._sendEvent(new CustomEvent(sa.LEVEL_LOADED,{detail:{netStats:i}}));return}this._sendEvent(new CustomEvent(sa.MANIFEST_LOADED,{detail:{originalUrl:t,realUrl:s}}))}_onPlaylistInfoAvailable(e){this._sendEvent(new CustomEvent(sa.MANIFEST_PARSED,{detail:e}))}_onFragmentLoaded(e){this._sendEvent(new CustomEvent(sa.FRAG_LOADED,{detail:{netStats:e.stats,duration:e.duration}}))}_onDebuggerConnected(e){this._sendEvent(new CustomEvent(sa.DEBUGGER_CONNECTED,{detail:{panelUrl:e}}))}_onResolutionAutoChanged({prevResolution:e,nextResolution:t}){this._sendEvent(new CustomEvent(sa.LEVEL_SWITCHED_AUTO,{detail:{prevResolution:e,nextResolution:t}}))}_onNetworkRequestSettled({response:e}){this._isDebugEnabled&&globalThis.dispatchEvent(new CustomEvent("mmpFetchSettled",{detail:{response:e}}))}};(0,U.__decorate)([tQ.default],iC.prototype,"_onPlaylistLoadingStarted",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onResolutionChanged",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onPlaylistLoaded",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onPlaylistInfoAvailable",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onFragmentLoaded",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onDebuggerConnected",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onResolutionAutoChanged",null),(0,U.__decorate)([tQ.default],iC.prototype,"_onNetworkRequestSettled",null);let iB=e=>{if(s7(e))return e;let t=new URL(document.location.href);if(e.startsWith("/"))return`${t.origin}${e}`;let s=t.pathname.split("/").filter(e=>e.trim().length>0);return s.pop()||s.pop(),`${t.origin}/${s.concat(e).join("/")}`};var tQ=k("eQOGK");let iO=class{get additionalInfo(){return{totalHeapSize:performance.memory?.totalJSHeapSize,usedHeapSize:performance.memory?.usedJSHeapSize,sizeLimit:performance.memory?.jsHeapSizeLimit,...this._lastMetrics||{}}}constructor(){this.state=tK.OK,this.status="Idle",this.groups=["general"],this._lastMetrics=null}};var U=k("a8VW4"),tQ=k("eQOGK"),iD=k("3264a");let iw=class extends tj{constructor(e){super("debugger",e),this._debuggableModules={},this._modulesInfoGatheringInterval=null,this._debuggerWorker=null,this._onLifecycleEventReportedListener=this._eventBus.subscribe(sd,this._onLifecycleEventReported),this.config.enableRemoteDebugging&&this.config.debuggerUrl&&this.config.maxWSConnectionRetries&&this._startDebugger()}registerDebuggableModules(e){this._debuggableModules={...this._debuggableModules,...e}}unregisterDebuggableModules(e){e.forEach(e=>{delete this._debuggableModules[e]})}destroy(){super.destroy(),this._debuggerWorker?.disconnect(),this._eventBus.unsubscribe(this._onLifecycleEventReportedListener)}_handleConfigUpdated(e){this._debuggerWorker&&(e.debuggerUrl||e.maxWSConnectionRetries)&&(this._destroyWorker(),this._getDebuggerModule()),!1===e.enableRemoteDebugging&&this._stopDebugger(),e.enableRemoteDebugging&&(this._destroyWorker(),this._getDebuggerModule()),e.modulesStateGatheringPeriod&&(this._disarmSendModulesInfoTimeout(),this._armSendModulesInfoTimeout())}_destroyWorker(){this._debuggerWorker?.disconnect(),this._debuggerWorker=null}_startDebugger(){this._getDebuggerModule(),this._armSendModulesInfoTimeout()}_stopDebugger(){this._debuggerWorker&&(this._debuggerWorker.disconnect(),this._disarmSendModulesInfoTimeout())}async _sendMessage(e){(await this._getDebuggerModule()).sendMessage(e)}_onConnected(e){this._eventBus.publish(sh,e),this._armSendModulesInfoTimeout()}_onDisconnected(){this._disarmSendModulesInfoTimeout()}_onLifecycleEventReported(e){this._debuggerWorker&&this.config.enableLifecycleEvents&&this._sendMessage({command:iD.ECommand.MODULE_LIFECYCLE_EVENT_AVAILABLE,event:e})}_armSendModulesInfoTimeout(){this._modulesInfoGatheringInterval=globalThis.setInterval(this._sendModulesInfo,this.config.modulesStateGatheringPeriod)}_disarmSendModulesInfoTimeout(){this._modulesInfoGatheringInterval&&globalThis.clearInterval(this._modulesInfoGatheringInterval)}_unzipDebuggableModules(e){let t={...e};return Object.values(e).forEach(e=>{e.additionalModules&&(t={...t,...this._unzipDebuggableModules(e.additionalModules)})}),t}_sendModulesInfo(){let e=Object.entries(this._unzipDebuggableModules(this._debuggableModules)).reduce((e,[t,s])=>(e[t]={additionalInfo:s.additionalInfo,state:s.state,groups:s.groups,status:s.status},e),{});this._sendMessage({command:iD.ECommand.MODULES_INFO_AVAILABLE,payload:e})}async _getDebuggerModule(){if(!this._debuggerWorker){let{DebuggerWorker:e}=await k("iVqGx");this._debuggerWorker=new e,this._debuggerWorker.setConfig(this.config.debuggerUrl,this.config.maxWSConnectionRetries,this._onConnected,this._onDisconnected),this._debuggerWorker.connect()}return this._debuggerWorker}};(0,U.__decorate)([tQ.default],iw.prototype,"_onConnected",null),(0,U.__decorate)([tQ.default],iw.prototype,"_onDisconnected",null),(0,U.__decorate)([tQ.default],iw.prototype,"_onLifecycleEventReported",null),(0,U.__decorate)([tQ.default],iw.prototype,"_sendModulesInfo",null);var U=k("a8VW4"),tQ=k("eQOGK");let iM=class extends tj{constructor(e){super("fragmentBuffer",e),this._logger=eO("Doppio - FragmentsBuffer"),this._initSectionCache=null,this._expectedUnitedChunkName="",this._fragmentsCache=[],this._onFragmentReleasedListenerToken=this._eventBus.subscribe(sK,this._onFragmentReleasedFromQueue),this._onSaveDataRequestedListenerToken=this._eventBus.subscribe(sY.saveData,this.sendUnitedChunk)}destroy(){super.destroy(),this._eventBus.unsubscribe(this._onFragmentReleasedListenerToken),this._eventBus.unsubscribe(this._onSaveDataRequestedListenerToken),this._initSectionCache=null,this._fragmentsCache=[]}sendUnitedChunk(){if(!(!this._initSectionCache||Math.random()>this.config.saveProbability))try{let e=sj([this._initSectionCache.data].concat(...this._fragmentsCache.map(({data:e})=>e))),t=new Headers;t.append("Content-Type","video/mp4"),fetch(`https://${this.config.baseChunksSaverUrl}/${this._expectedUnitedChunkName}`,{method:"PUT",headers:t,body:e,redirect:"follow"}).catch(e=>{this._logger.warn(`Could not save problem chunks: ${e}`)})}catch(e){this._logger.warn(`Could not save problem chunks: ${e}`)}}_onFragmentReleasedFromQueue(e){try{for(let t of e){if(t.isInitSection){this._initSectionCache=t,this._expectedUnitedChunkName=t.url.split("/").slice(-1)[0],this._fragmentsCache=[];return}this._fragmentsCache.push(t);let s=Math.max(...e.map(({msn:e})=>e)),i=Math.max(0,s-this.config.numberOfFragmentsToKeepInBuffer+1);this._fragmentsCache=this._fragmentsCache.filter(({msn:e})=>e>=i)}}catch(e){this._logger.warn("Could not handle fragment"),this._fragmentsCache=[],this._initSectionCache=null}}};(0,U.__decorate)([tQ.default],iM.prototype,"sendUnitedChunk",null),(0,U.__decorate)([tQ.default],iM.prototype,"_onFragmentReleasedFromQueue",null);var U=k("a8VW4"),tQ=k("eQOGK");let iI={lifecycleEvent:"LifecycleEventsManager.LIFECYCLE_EVENT",lifecycleError:"LifecycleEventsManager.LIFECYCLE_ERROR"},iF=class{constructor(e){this._manifestLoaded=!1,this._firstMediaPlaylistLoaded=!1,this._firstFragmentLoaded=!1,this._firstFragmentBuffered=!1,this._eventBus=e,this._onManifestLoadedListener=this._eventBus.subscribe(tY.playlistType.multivariantDetected,this._onManifestLoaded),this._onSimplePlaylistDetectedListener=this._eventBus.subscribe(tY.playlistType.simpleDetected,this._onPlaylistLoaded),this._onLLPlaylistDetectedListener=this._eventBus.subscribe(tY.playlistType.llDetected,this._onPlaylistLoaded),this._onVODPlaylistDetectedListener=this._eventBus.subscribe(tY.playlistType.vodDetected,this._onPlaylistLoaded),this._onFragmentLoadedListener=this._eventBus.subscribe(sL.fragments.fragmentLoaded,this._onFragmentLoaded),this._onFragmentBufferedListener=this._eventBus.subscribe(tz.fragmentAdded,this._onFragmentBuffered),this._onFragmentLoadErrorListener=this._eventBus.subscribe(sL.fragments.fragmentLoadingError,this._onFragmentLoadError),this._onFragmentLoadAbortListener=this._eventBus.subscribe(sL.fragments.fragmentLoadingAborted,this._onFragmentLoadError),this._onPlaylistLoadErrorListener=this._eventBus.subscribe(tY.playlists.playlistLoadingError,this._onPlaylistLoadError)}destroy(){this._eventBus.unsubscribe(this._onManifestLoadedListener),this._eventBus.unsubscribe(this._onSimplePlaylistDetectedListener),this._eventBus.unsubscribe(this._onLLPlaylistDetectedListener),this._eventBus.unsubscribe(this._onVODPlaylistDetectedListener),this._eventBus.unsubscribe(this._onFragmentLoadedListener),this._eventBus.unsubscribe(this._onFragmentBufferedListener),this._eventBus.unsubscribe(this._onFragmentLoadErrorListener),this._eventBus.unsubscribe(this._onFragmentLoadAbortListener),this._eventBus.unsubscribe(this._onPlaylistLoadErrorListener)}reset(){this._manifestLoaded=!1,this._firstMediaPlaylistLoaded=!1,this._firstFragmentLoaded=!1,this._firstFragmentBuffered=!1}_onManifestLoaded(){this._manifestLoaded||(this._manifestLoaded=!0,this._eventBus.publish(iI.lifecycleEvent,{eventType:sr.MANIFEST_LOADED}))}_onPlaylistLoaded(){this._firstMediaPlaylistLoaded||(this._firstMediaPlaylistLoaded=!0,this._eventBus.publish(iI.lifecycleEvent,{eventType:sr.FIRST_MEDIA_PLAYLIST_LOADED}))}_onFragmentLoaded(){this._firstFragmentLoaded||(this._firstFragmentLoaded=!0,this._eventBus.publish(iI.lifecycleEvent,{eventType:sr.FIRST_FRAGMENT_LOADED}))}_onFragmentBuffered(){this._firstFragmentBuffered||(this._firstFragmentBuffered=!0,this._eventBus.publish(iI.lifecycleEvent,{eventType:sr.FIRST_FRAGMENT_BUFFERED}))}_onFragmentLoadError(e){this._eventBus.publish(iI.lifecycleError,{errorType:sn.FRAGMENT_LOAD_ERROR,nativeError:Error(`Could not load fragment: ${e.error?.statusText} (${e.error?.status})`)})}_onPlaylistLoadError({error:e}){this._eventBus.publish(iI.lifecycleError,{errorType:this._manifestLoaded?sn.PLAYLIST_LOAD_ERROR:sn.MANIFEST_LOAD_ERROR,nativeError:Error(`Could not load ${this._manifestLoaded?"playlist":"manifest"}: ${e?.statusText}(${e?.status})`)})}};(0,U.__decorate)([tQ.default],iF.prototype,"_onManifestLoaded",null),(0,U.__decorate)([tQ.default],iF.prototype,"_onPlaylistLoaded",null),(0,U.__decorate)([tQ.default],iF.prototype,"_onFragmentLoaded",null),(0,U.__decorate)([tQ.default],iF.prototype,"_onFragmentBuffered",null),(0,U.__decorate)([tQ.default],iF.prototype,"_onFragmentLoadError",null),(0,U.__decorate)([tQ.default],iF.prototype,"_onPlaylistLoadError",null);let iN=class extends EventTarget{constructor(){super(),this._eventBus=new sG,this._loggerTransport=null,this._fragmentParser=new sH(this._eventBus),this._fragmentQueue=new sz(this._eventBus),this._buffer=new sq(this._eventBus),this._resolutionManager=new iP(this._eventBus),this._abrController=new ss(this._eventBus),this._debugger=new iw(this._eventBus),this._fragmentsFilter=new sQ(this._eventBus),this._fragmentsBuffer=new iM(this._eventBus),this._url=null,this._key=null,this._videoElement=null,this._isStarted=!1,this._commonMetricsCollector=new iO,this._lifecycleEventsManager=new iF(this._eventBus),this._logger=eO("Doppio - core");let e=(Math.random()+1).toString(36).substring(7);this._eventBus.setAppId(e),this._loggerTransport=new eI(tW,[],[]),this._logger.info("Created"),this._onResolutionsAvailableListener=this._eventBus.subscribe(tJ.resolutionsAvailable,this._onResolutionsAvailable),this._onMetricsAvailableListener=this._eventBus.subscribe(tz.bufferMetricsAvailable,this._onBufferMetricsAvailable),this._onResolutionChangedListener=this._eventBus.subscribe(tJ.resolutionChanged,this._onResolutionChanged),this._onStreamEndedListener=this._eventBus.subscribe(tz.endOfStreamReached,this._onStreamEnded),this._onPlaybackStateChangedListener=this._eventBus.subscribe(tz.playbackStateChanged,this._onPlaybackStateChanged),this._legacyEventsController=new iC(this.dispatchEvent.bind(this),this._eventBus),this._debugger.registerDebuggableModules({fragmentQueue:this._fragmentQueue,commonInfo:this._commonMetricsCollector,resolutionManager:this._resolutionManager,abr:this._abrController}),this._onLifecycleEventReportedListener=this._eventBus.subscribe(iI.lifecycleEvent,this._onLifecycleEventReported),this._onLifecycleErrorReportedListener=this._eventBus.subscribe(iI.lifecycleError,this._onLifecycleErrorReported),this._onResolutionNotFoundListener=this._eventBus.subscribe(tJ.resolutionNotFound,this._onResolutionNotFound),this._onFragmentsFilterProblemDetectedListener=this._eventBus.subscribe(sW.problemDetected,this._onFragmentFilterProblemDetected)}destroy(){this._eventBus.unsubscribe(this._onResolutionsAvailableListener),this._eventBus.unsubscribe(this._onResolutionChangedListener),this._eventBus.unsubscribe(this._onMetricsAvailableListener),this._eventBus.unsubscribe(this._onStreamEndedListener),this._eventBus.unsubscribe(this._onPlaybackStateChangedListener),this._eventBus.unsubscribe(this._onLifecycleEventReportedListener),this._eventBus.unsubscribe(this._onLifecycleErrorReportedListener),this._eventBus.unsubscribe(this._onResolutionNotFoundListener),this._eventBus.unsubscribe(this._onFragmentsFilterProblemDetectedListener),this._fragmentParser.destroy(),this._buffer.destroy(),this._resolutionManager.destroy(),this._abrController.destroy(),this._fragmentQueue.destroy(),this._debugger.destroy(),this._legacyEventsController.destroy(),this._videoElement?.removeEventListener("error",this._onMediaElementError),this._logger.info("Destroyed"),this._lifecycleEventsManager.destroy(),this._fragmentsFilter.destroy(),this._fragmentsBuffer.destroy(),setTimeout(()=>{this._loggerTransport?.destroy()},1e3),s6(this._eventBus.getAppId())}get version(){return"v1.11.15"}get isStarted(){return this._isStarted}recoverMediaError(){this._buffer.detachVideoElement(),this._videoElement&&this._buffer.attachVideoElement(this._videoElement),this._resolutionManager.restart(),this._videoElement?.play()}start(){if(!this._url){this._logger.fatal("Stream URL is not defined. Cannot start player");return}if(this._videoElement||this._logger.warn("Video element is not defined."),this._isStarted){this._restart();return}this._debugger.registerDebuggableModules({bufferController:this._buffer}),this._resolutionManager.setUrl(this._url),this._isStarted=!0}setUrl(e){if(!e.trim())return this._stop(),this;let t=iB(e),s=this._url!==t&&this._isStarted;return this._url=t,this._key=null,s&&(this._lifecycleEventsManager.reset(),this._restart()),this}setKey(e){return this._key=e,this}setVideoElement(e){return e===this._videoElement||(this._videoElement&&(this._buffer.detachVideoElement(),this._videoElement.removeEventListener("error",this._onMediaElementError)),this._videoElement=e,this._buffer.attachVideoElement(e),this._buffer.scheduleSourceBufferRecreation(),this._videoElement.addEventListener("error",this._onMediaElementError)),this}getFragmentQueue(){return this._fragmentQueue.getCurrentQueue()}setLoggerLevel(e,t=[],s=[]){return this._loggerTransport&&(this._loggerTransport.destroy(),this._loggerTransport=null),this._loggerTransport=new eI(e,t,s),this}setResolutionByName(e){return this._resolutionManager.setResolutionByName(e),this}setResolutionByBitrate(e){return this._resolutionManager.setNearestResolutionByBitrate(e)}disableABR(){return this._resolutionManager.toggleAutoResolution(!1),this}enableABR(){return this._resolutionManager.toggleAutoResolution(!0),this}setConfig(e){t$(e,this._eventBus)}async _restart(){this._logger.info("restarting"),this._buffer?.reset(),await this.recoverMediaError(),this._fragmentParser.destroy(),this._fragmentParser=new sH(this._eventBus),this._fragmentQueue.reset(),this._url&&this._resolutionManager.setUrl(this._url)}_stop(){this._url=null,this._restart(),this._resolutionManager.setUrl("")}_onResolutionsAvailable(e){this.dispatchEvent(new CustomEvent(sa.VARIANTS_DETECTED,{detail:e}))}_onStreamEnded(){this.dispatchEvent(new Event(sa.STREAM_ENDED))}_onResolutionChanged(e){this.dispatchEvent(new CustomEvent(sa.RESOLUTION_CHANGED,{detail:e}))}_onBufferMetricsAvailable(e){this.dispatchEvent(new CustomEvent(sa.METRICS_AVAILABLE,{detail:e}))}_onPlaybackStateChanged({prevState:e,nextState:t}){this.dispatchEvent(new CustomEvent(sa.PLAYBACK_STATE_CHANGED,{detail:{prevState:e,nextState:t}}))}_onFragmentFilterProblemDetected({reason:e,fragment:t}){this.dispatchEvent(new CustomEvent(sa.FRAGMENT_FILTERED_OUT,{detail:{reason:e,fragment:t}}))}_onMediaElementError(){sJ.reportError("VideoElementError",{msg:this._videoElement?.error?.message,code:this._videoElement?.error?.code}),this._eventBus.publish(sY.saveData,{}),this._logger.error(`Media error occurred ${this._videoElement?.error?.message} ${this._videoElement?.error?.code}`),this._videoElement?.error&&this.recoverMediaError()}_onLifecycleEventReported({eventType:e}){this.dispatchEvent(new CustomEvent(sa.LIFECYCLE_EVENT,{detail:{eventType:e}}))}_onLifecycleErrorReported({errorType:e,nativeError:t}){this.dispatchEvent(new CustomEvent(sa.LIFECYCLE_ERROR,{detail:{errorType:e,nativeError:t}}))}_onResolutionNotFound(){this.dispatchEvent(new CustomEvent(sa.RESOLUTION_NOT_FOUND))}_addAirPlaySourceIfNeeded(){if(this._url&&this._videoElement&&window.ManagedMediaSource){let e=document.createElement("source");e.type="application/x-mpegURL",e.src=this._url.replace(/playlistType=lowLatency/gi,""),this._videoElement.appendChild(e)}}};(0,U.__decorate)([tQ.default],iN.prototype,"_onResolutionsAvailable",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onStreamEnded",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onResolutionChanged",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onBufferMetricsAvailable",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onPlaybackStateChanged",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onFragmentFilterProblemDetected",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onMediaElementError",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onLifecycleEventReported",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onLifecycleErrorReported",null),(0,U.__decorate)([tQ.default],iN.prototype,"_onResolutionNotFound",null)}),l("lt6Wo",function(e,t){e.exports=s("1vz0y").then(()=>o("7p8k5"))}),l("4gxuw",function(e,t){n(e.exports,"AbstractWrapper",function(){return i});var s=o("giOKx");class i{constructor(e,t={}){this._videoElement=null,this._lastKnownConfig={},this._lastKnownStreamConfig=null,this._playerInstance=null,this._metricsCollector=null,this._eventBusInstance=e,this._eventBusInstance.publish(s.EPlayersEvents.MODULE_LOADED,{}),this._persistent=!!t.persistent}setMetricsCollector(e){this._metricsCollector=e}destroy(){return this._destroyPlayerInstance(),this._isStarted=!1,this}setAppKey(e){return this._appKey=e,this}setVideoElement(e){return this._videoElement=e,e&&this._playerInstance?.setVideoElement(e),this}recreatePlayerInstance(){this._playerInstance&&(this.destroy(),this._playerInstance=null),this._createPlayerInstance()}start(){return this._playerInstance||this.recreatePlayerInstance(),this._playerInstance?.start(),this._isStarted=!0,this}stop(){return this._isStarted=!1,this._persistent&&this._playerInstance&&"stop"in this._playerInstance?this._playerInstance.stop():this._destroyPlayerInstance(),this}setPlayerConfig(e){return this._lastKnownConfig=e,this._playerInstance?.setConfig(e,!0),this}_destroyPlayerInstance(){this._playerInstance&&(this._detachEventListeners(),this._playerInstance.destroy(),this._playerInstance=null)}}})}),s.register("1vz0y",function(e,t){e.exports=Promise.resolve(require("./Debugger.worker.eb4b0e32.0fa53712.c8e4592d.js")).then(()=>s("9oTkO"))});//# sourceMappingURL=Doppio.c259b94d.346a58fd.js.map }