@scarlett-player/embed 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ScarlettPlayer={})}(this,function(e){"use strict";class t{constructor(e){this.subscribers=new Set,this.value=e}get(){return this.value}set(e){Object.is(this.value,e)||(this.value=e,this.notify())}update(e){this.set(e(this.value))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){this.subscribers.forEach(e=>{try{e()}catch(t){console.error("[Scarlett Player] Error in signal subscriber:",t)}})}destroy(){this.subscribers.clear()}getSubscriberCount(){return this.subscribers.size}}function r(e){return new t(e)}const i={playbackState:"idle",playing:!1,paused:!0,ended:!1,buffering:!1,waiting:!1,seeking:!1,currentTime:0,duration:NaN,buffered:null,bufferedAmount:0,mediaType:"unknown",source:null,title:"",poster:"",volume:1,muted:!1,playbackRate:1,fullscreen:!1,pip:!1,controlsVisible:!0,qualities:[],currentQuality:null,audioTracks:[],currentAudioTrack:null,textTracks:[],currentTextTrack:null,live:!1,liveEdge:!0,seekableRange:null,liveLatency:0,lowLatencyMode:!1,chapters:[],currentChapter:null,error:null,bandwidth:0,autoplay:!1,loop:!1,airplayAvailable:!1,airplayActive:!1,chromecastAvailable:!1,chromecastActive:!1,interacting:!1,hovering:!1,focused:!1};class s{constructor(e){this.signals=new Map,this.changeSubscribers=new Set,this.initializeSignals(e)}initializeSignals(e){const t={...i,...e};for(const[i,s]of Object.entries(t)){const e=i,t=r(s);t.subscribe(()=>{this.notifyChangeSubscribers(e)}),this.signals.set(e,t)}}get(e){const t=this.signals.get(e);if(!t)throw new Error(`[StateManager] Unknown state key: ${e}`);return t}getValue(e){return this.get(e).get()}set(e,t){this.get(e).set(t)}update(e){for(const[t,r]of Object.entries(e)){const e=t;this.signals.has(e)&&this.set(e,r)}}subscribeToKey(e,t){const r=this.get(e);return r.subscribe(()=>{t(r.get())})}subscribe(e){return this.changeSubscribers.add(e),()=>this.changeSubscribers.delete(e)}notifyChangeSubscribers(e){const t=this.get(e).get(),r={key:e,value:t,previousValue:t};this.changeSubscribers.forEach(e=>{try{e(r)}catch(t){console.error("[StateManager] Error in change subscriber:",t)}})}reset(){this.update(i)}resetKey(e){const t=i[e];this.set(e,t)}snapshot(){const e={};for(const[t,r]of this.signals)e[t]=r.get();return Object.freeze(e)}getSubscriberCount(e){return this.signals.get(e)?.getSubscriberCount()??0}destroy(){this.signals.forEach(e=>e.destroy()),this.signals.clear(),this.changeSubscribers.clear()}}const n={maxListeners:100,async:!1,interceptors:!0};class a{constructor(e){this.listeners=new Map,this.onceListeners=new Map,this.interceptors=new Map,this.options={...n,...e}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);return this.listeners.get(e).add(t),this.checkMaxListeners(e),()=>this.off(e,t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,new Set);const r=this.onceListeners.get(e);return r.add(t),this.listeners.has(e)||this.listeners.set(e,new Set),()=>{r.delete(t)}}off(e,t){const r=this.listeners.get(e);r&&(r.delete(t),0===r.size&&this.listeners.delete(e));const i=this.onceListeners.get(e);i&&(i.delete(t),0===i.size&&this.onceListeners.delete(e))}emit(e,t){const r=this.runInterceptors(e,t);if(null===r)return;const i=this.listeners.get(e);if(i){Array.from(i).forEach(e=>{this.safeCallHandler(e,r)})}const s=this.onceListeners.get(e);if(s){Array.from(s).forEach(e=>{this.safeCallHandler(e,r)}),this.onceListeners.delete(e)}}async emitAsync(e,t){const r=await this.runInterceptorsAsync(e,t);if(null===r)return;const i=this.listeners.get(e);if(i){const e=Array.from(i).map(e=>this.safeCallHandlerAsync(e,r));await Promise.all(e)}const s=this.onceListeners.get(e);if(s){const t=Array.from(s).map(e=>this.safeCallHandlerAsync(e,r));await Promise.all(t),this.onceListeners.delete(e)}}intercept(e,t){if(!this.options.interceptors)return()=>{};this.interceptors.has(e)||this.interceptors.set(e,new Set);const r=this.interceptors.get(e);return r.add(t),()=>{r.delete(t),0===r.size&&this.interceptors.delete(e)}}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){return(this.listeners.get(e)?.size??0)+(this.onceListeners.get(e)?.size??0)}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.interceptors.clear()}runInterceptors(e,t){if(!this.options.interceptors)return t;const r=this.interceptors.get(e);if(!r||0===r.size)return t;let i=t;for(const n of r)try{if(i=n(i),null===i)return null}catch(s){console.error("[EventBus] Error in interceptor:",s)}return i}async runInterceptorsAsync(e,t){if(!this.options.interceptors)return t;const r=this.interceptors.get(e);if(!r||0===r.size)return t;let i=t;for(const n of r)try{const e=n(i);if(i=e instanceof Promise?await e:e,null===i)return null}catch(s){console.error("[EventBus] Error in interceptor:",s)}return i}safeCallHandler(e,t){try{e(t)}catch(r){console.error("[EventBus] Error in event handler:",r)}}async safeCallHandlerAsync(e,t){try{const r=e(t);r instanceof Promise&&await r}catch(r){console.error("[EventBus] Error in event handler:",r)}}checkMaxListeners(e){const t=this.listenerCount(e);t>this.options.maxListeners&&console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) exceeded for event: ${e}. Current count: ${t}. This may indicate a memory leak.`)}}const o=["debug","info","warn","error"],l=e=>{const t=`${e.scope?`[${e.scope}]`:"[ScarlettPlayer]"} ${e.message}`,r=e.metadata??"";switch(e.level){case"debug":console.debug(t,r);break;case"info":console.info(t,r);break;case"warn":console.warn(t,r);break;case"error":console.error(t,r)}};let d=class e{constructor(e){this.level=e?.level??"warn",this.scope=e?.scope,this.enabled=e?.enabled??!0,this.handlers=e?.handlers??[l]}child(t){return new e({level:this.level,scope:this.scope?`${this.scope}:${t}`:t,enabled:this.enabled,handlers:this.handlers})}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}setEnabled(e){this.enabled=e}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);-1!==t&&this.handlers.splice(t,1)}log(e,t,r){if(!this.enabled||!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),scope:this.scope,metadata:r};for(const n of this.handlers)try{n(i)}catch(s){console.error("[Logger] Handler error:",s)}}shouldLog(e){return o.indexOf(e)>=o.indexOf(this.level)}};var h=(e=>(e.SOURCE_NOT_SUPPORTED="SOURCE_NOT_SUPPORTED",e.SOURCE_LOAD_FAILED="SOURCE_LOAD_FAILED",e.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",e.PROVIDER_SETUP_FAILED="PROVIDER_SETUP_FAILED",e.PLUGIN_SETUP_FAILED="PLUGIN_SETUP_FAILED",e.PLUGIN_NOT_FOUND="PLUGIN_NOT_FOUND",e.PLAYBACK_FAILED="PLAYBACK_FAILED",e.MEDIA_DECODE_ERROR="MEDIA_DECODE_ERROR",e.MEDIA_NETWORK_ERROR="MEDIA_NETWORK_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e))(h||{});class u{constructor(e,t,r){this.errors=[],this.eventBus=e,this.logger=t,this.maxHistory=r?.maxHistory??10}handle(e,t){const r=this.normalizeError(e,t);return this.addToHistory(r),this.logError(r),this.eventBus.emit("error",r),r}throw(e,t,r){const i={code:e,message:t,fatal:r?.fatal??this.isFatalCode(e),timestamp:Date.now(),context:r?.context,originalError:r?.originalError};return this.handle(i,r?.context)}getHistory(){return[...this.errors]}getLastError(){return this.errors[this.errors.length-1]??null}clearHistory(){this.errors=[]}hasFatalError(){return this.errors.some(e=>e.fatal)}normalizeError(e,t){return this.isPlayerError(e)?{...e,context:{...e.context,...t}}:{code:this.getErrorCode(e),message:e.message,fatal:this.isFatal(e),timestamp:Date.now(),context:t,originalError:e}}getErrorCode(e){const t=e.message.toLowerCase();return t.includes("network")?"MEDIA_NETWORK_ERROR":t.includes("decode")?"MEDIA_DECODE_ERROR":t.includes("source")?"SOURCE_LOAD_FAILED":t.includes("plugin")?"PLUGIN_SETUP_FAILED":t.includes("provider")?"PROVIDER_SETUP_FAILED":"UNKNOWN_ERROR"}isFatal(e){return this.isFatalCode(this.getErrorCode(e))}isFatalCode(e){return["SOURCE_NOT_SUPPORTED","PROVIDER_NOT_FOUND","MEDIA_DECODE_ERROR"].includes(e)}isPlayerError(e){return"object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"fatal"in e&&"timestamp"in e}addToHistory(e){this.errors.push(e),this.errors.length>this.maxHistory&&this.errors.shift()}logError(e){const t=`[${e.code}] ${e.message}`;e.fatal?this.logger.error(t,{code:e.code,context:e.context}):this.logger.warn(t,{code:e.code,context:e.context})}}class c{constructor(e,t){this.cleanupFns=[],this.pluginId=e,this.stateManager=t.stateManager,this.eventBus=t.eventBus,this.container=t.container,this.getPluginFn=t.getPlugin,this.logger={debug:(r,i)=>t.logger.debug(`[${e}] ${r}`,i),info:(r,i)=>t.logger.info(`[${e}] ${r}`,i),warn:(r,i)=>t.logger.warn(`[${e}] ${r}`,i),error:(r,i)=>t.logger.error(`[${e}] ${r}`,i)}}getState(e){return this.stateManager.getValue(e)}setState(e,t){this.stateManager.set(e,t)}on(e,t){return this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}emit(e,t){this.eventBus.emit(e,t)}getPlugin(e){return this.getPluginFn(e)}onDestroy(e){this.cleanupFns.push(e)}subscribeToState(e){return this.stateManager.subscribe(e)}runCleanups(){for(const t of this.cleanupFns)try{t()}catch(e){this.logger.error("Cleanup function failed",{error:e})}this.cleanupFns=[]}getCleanupFns(){return this.cleanupFns}}class f{constructor(e,t,r,i){this.plugins=new Map,this.eventBus=e,this.stateManager=t,this.logger=r,this.container=i.container}register(e,t){if(this.plugins.has(e.id))throw new Error(`Plugin "${e.id}" is already registered`);this.validatePlugin(e);const r=new c(e.id,{stateManager:this.stateManager,eventBus:this.eventBus,logger:this.logger,container:this.container,getPlugin:e=>this.getReadyPlugin(e)});this.plugins.set(e.id,{plugin:e,state:"registered",config:t,cleanupFns:[],api:r}),this.logger.info(`Plugin registered: ${e.id}`),this.eventBus.emit("plugin:registered",{name:e.id,type:e.type})}async unregister(e){const t=this.plugins.get(e);t&&("ready"===t.state&&await this.destroyPlugin(e),this.plugins.delete(e),this.logger.info(`Plugin unregistered: ${e}`))}async initAll(){const e=this.resolveDependencyOrder();for(const t of e)await this.initPlugin(t)}async initPlugin(e){const t=this.plugins.get(e);if(!t)throw new Error(`Plugin "${e}" not found`);if("ready"!==t.state){if("initializing"===t.state)throw new Error(`Plugin "${e}" is already initializing (possible circular dependency)`);for(const r of t.plugin.dependencies||[]){const t=this.plugins.get(r);if(!t)throw new Error(`Plugin "${e}" depends on missing plugin "${r}"`);"ready"!==t.state&&await this.initPlugin(r)}try{if(t.state="initializing",t.plugin.onStateChange){const e=this.stateManager.subscribe(t.plugin.onStateChange.bind(t.plugin));t.api.onDestroy(e)}if(t.plugin.onError){const e=this.eventBus.on("error",e=>{t.plugin.onError?.(e.originalError||new Error(e.message))});t.api.onDestroy(e)}await t.plugin.init(t.api,t.config),t.state="ready",this.logger.info(`Plugin ready: ${e}`),this.eventBus.emit("plugin:active",{name:e})}catch(r){throw t.state="error",t.error=r,this.logger.error(`Plugin init failed: ${e}`,{error:r}),this.eventBus.emit("plugin:error",{name:e,error:r}),r}}}async destroyAll(){const e=this.resolveDependencyOrder().reverse();for(const t of e)await this.destroyPlugin(t)}async destroyPlugin(e){const t=this.plugins.get(e);if(t&&"ready"===t.state)try{await t.plugin.destroy(),t.api.runCleanups(),t.state="registered",this.logger.info(`Plugin destroyed: ${e}`),this.eventBus.emit("plugin:destroyed",{name:e})}catch(r){this.logger.error(`Plugin destroy failed: ${e}`,{error:r}),t.state="registered"}}getPlugin(e){const t=this.plugins.get(e);return t?t.plugin:null}getReadyPlugin(e){const t=this.plugins.get(e);return"ready"===t?.state?t.plugin:null}hasPlugin(e){return this.plugins.has(e)}getPluginState(e){return this.plugins.get(e)?.state??null}getPluginIds(){return Array.from(this.plugins.keys())}getReadyPlugins(){return Array.from(this.plugins.values()).filter(e=>"ready"===e.state).map(e=>e.plugin)}getPluginsByType(e){return Array.from(this.plugins.values()).filter(t=>t.plugin.type===e).map(e=>e.plugin)}selectProvider(e){const t=this.getPluginsByType("provider");for(const r of t){const t=r.canPlay;if("function"==typeof t&&t(e))return r}return null}resolveDependencyOrder(){const e=new Set,t=new Set,r=[],i=(s,n=[])=>{if(e.has(s))return;if(t.has(s)){const e=[...n,s].join(" -> ");throw new Error(`Circular dependency detected: ${e}`)}const a=this.plugins.get(s);if(a){t.add(s);for(const e of a.plugin.dependencies||[])this.plugins.has(e)&&i(e,[...n,s]);t.delete(s),e.add(s),r.push(s)}};for(const s of this.plugins.keys())i(s);return r}validatePlugin(e){if(!e.id||"string"!=typeof e.id)throw new Error("Plugin must have a valid id");if(!e.name||"string"!=typeof e.name)throw new Error(`Plugin "${e.id}" must have a valid name`);if(!e.version||"string"!=typeof e.version)throw new Error(`Plugin "${e.id}" must have a valid version`);if(!e.type||"string"!=typeof e.type)throw new Error(`Plugin "${e.id}" must have a valid type`);if("function"!=typeof e.init)throw new Error(`Plugin "${e.id}" must have an init() method`);if("function"!=typeof e.destroy)throw new Error(`Plugin "${e.id}" must have a destroy() method`)}}class g{constructor(e){if(this._currentProvider=null,this.destroyed=!1,this.seekingWhilePlaying=!1,this.seekResumeTimeout=null,"string"==typeof e.container){const t=document.querySelector(e.container);if(!(t&&t instanceof HTMLElement))throw new Error(`ScarlettPlayer: container not found: ${e.container}`);this.container=t}else{if(!(e.container instanceof HTMLElement))throw new Error("ScarlettPlayer requires a valid HTMLElement container or CSS selector");this.container=e.container}if(this.initialSrc=e.src,this.eventBus=new a,this.stateManager=new s({autoplay:e.autoplay??!1,loop:e.loop??!1,volume:e.volume??1,muted:e.muted??!1,poster:e.poster??""}),this.logger=new d({level:e.logLevel??"warn",scope:"ScarlettPlayer"}),this.errorHandler=new u(this.eventBus,this.logger),this.pluginManager=new f(this.eventBus,this.stateManager,this.logger,{container:this.container}),e.plugins)for(const t of e.plugins)this.pluginManager.register(t);this.logger.info("ScarlettPlayer initialized",{autoplay:e.autoplay,plugins:e.plugins?.length??0}),this.eventBus.emit("player:ready",void 0)}async init(){this.checkDestroyed();for(const[e,t]of this.pluginManager.plugins)"provider"!==t.plugin.type&&"registered"===t.state&&await this.pluginManager.initPlugin(e);return this.initialSrc&&await this.load(this.initialSrc),Promise.resolve()}async load(e){this.checkDestroyed();try{if(this.logger.info("Loading source",{source:e}),this.stateManager.update({playing:!1,paused:!0,ended:!1,buffering:!0,currentTime:0,duration:0,bufferedAmount:0,playbackState:"loading"}),this._currentProvider){const e=this._currentProvider.id;this.logger.info("Destroying previous provider",{provider:e}),await this.pluginManager.destroyPlugin(e),this._currentProvider=null}const t=this.pluginManager.selectProvider(e);if(!t)return void this.errorHandler.throw(h.PROVIDER_NOT_FOUND,`No provider found for source: ${e}`,{fatal:!0,context:{source:e}});this._currentProvider=t,this.logger.info("Provider selected",{provider:t.id}),await this.pluginManager.initPlugin(t.id),this.stateManager.set("source",{src:e,type:this.detectMimeType(e)}),"function"==typeof t.loadSource&&await t.loadSource(e),this.stateManager.getValue("autoplay")&&await this.play()}catch(t){this.errorHandler.handle(t,{operation:"load",source:e})}}async play(){this.checkDestroyed();try{this.logger.debug("Play requested"),this.eventBus.emit("playback:play",void 0)}catch(e){this.errorHandler.handle(e,{operation:"play"})}}pause(){this.checkDestroyed();try{this.logger.debug("Pause requested"),this.seekingWhilePlaying=!1,null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:pause",void 0)}catch(e){this.errorHandler.handle(e,{operation:"pause"})}}seek(e){this.checkDestroyed();try{this.logger.debug("Seek requested",{time:e});this.stateManager.getValue("playing")&&(this.seekingWhilePlaying=!0),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:seeking",{time:e}),this.stateManager.set("currentTime",e),this.seekingWhilePlaying&&(this.seekResumeTimeout=setTimeout(()=>{this.seekingWhilePlaying&&this.stateManager.getValue("playing")&&(this.logger.debug("Resuming playback after seek"),this.seekingWhilePlaying=!1,this.eventBus.emit("playback:play",void 0)),this.seekResumeTimeout=null},300))}catch(t){this.errorHandler.handle(t,{operation:"seek",time:e})}}setVolume(e){this.checkDestroyed();const t=Math.max(0,Math.min(1,e));this.stateManager.set("volume",t),this.eventBus.emit("volume:change",{volume:t,muted:this.stateManager.getValue("muted")})}setMuted(e){this.checkDestroyed(),this.stateManager.set("muted",e),this.eventBus.emit("volume:mute",{muted:e})}setPlaybackRate(e){this.checkDestroyed(),this.stateManager.set("playbackRate",e),this.eventBus.emit("playback:ratechange",{rate:e})}setAutoplay(e){this.checkDestroyed(),this.stateManager.set("autoplay",e),this.logger.debug("Autoplay set",{autoplay:e})}on(e,t){return this.checkDestroyed(),this.eventBus.on(e,t)}once(e,t){return this.checkDestroyed(),this.eventBus.once(e,t)}getPlugin(e){return this.checkDestroyed(),this.pluginManager.getPlugin(e)}registerPlugin(e){this.checkDestroyed(),this.pluginManager.register(e)}getState(){return this.checkDestroyed(),this.stateManager.snapshot()}getQualities(){if(this.checkDestroyed(),!this._currentProvider)return[];const e=this._currentProvider;return"function"==typeof e.getLevels?e.getLevels():[]}setQuality(e){if(this.checkDestroyed(),!this._currentProvider)return void this.logger.warn("No provider available for quality change");const t=this._currentProvider;"function"==typeof t.setLevel&&(t.setLevel(e),this.eventBus.emit("quality:change",{quality:-1===e?"auto":`level-${e}`,auto:-1===e}))}getCurrentQuality(){if(this.checkDestroyed(),!this._currentProvider)return-1;const e=this._currentProvider;return"function"==typeof e.getCurrentLevel?e.getCurrentLevel():-1}async requestFullscreen(){this.checkDestroyed();try{this.container.requestFullscreen?await this.container.requestFullscreen():this.container.webkitRequestFullscreen&&await this.container.webkitRequestFullscreen(),this.stateManager.set("fullscreen",!0),this.eventBus.emit("fullscreen:change",{fullscreen:!0})}catch(e){this.logger.error("Fullscreen request failed",{error:e})}}async exitFullscreen(){this.checkDestroyed();try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen&&await document.webkitExitFullscreen(),this.stateManager.set("fullscreen",!1),this.eventBus.emit("fullscreen:change",{fullscreen:!1})}catch(e){this.logger.error("Exit fullscreen failed",{error:e})}}async toggleFullscreen(){this.fullscreen?await this.exitFullscreen():await this.requestFullscreen()}requestAirPlay(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.showPicker?e.showPicker():this.logger.warn("AirPlay plugin not available")}async requestChromecast(){this.checkDestroyed();const e=this.pluginManager.getPlugin("chromecast");e&&"function"==typeof e.requestSession?await e.requestSession():this.logger.warn("Chromecast plugin not available")}stopCasting(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.stop&&e.stop();const t=this.pluginManager.getPlugin("chromecast");t&&"function"==typeof t.stopSession&&t.stopSession()}seekToLive(){this.checkDestroyed();if(!this.stateManager.getValue("live"))return void this.logger.warn("Not a live stream");if(this._currentProvider){const e=this._currentProvider;if("function"==typeof e.getLiveInfo){const t=e.getLiveInfo();if(void 0!==t?.liveSyncPosition)return void this.seek(t.liveSyncPosition)}}const e=this.stateManager.getValue("duration");e>0&&this.seek(e)}destroy(){this.destroyed||(this.logger.info("Destroying player"),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("player:destroy",void 0),this.pluginManager.destroyAll(),this.eventBus.destroy(),this.stateManager.destroy(),this.destroyed=!0,this.logger.info("Player destroyed"))}get playing(){return this.stateManager.getValue("playing")}get paused(){return this.stateManager.getValue("paused")}get currentTime(){return this.stateManager.getValue("currentTime")}get duration(){return this.stateManager.getValue("duration")}get volume(){return this.stateManager.getValue("volume")}get muted(){return this.stateManager.getValue("muted")}get playbackRate(){return this.stateManager.getValue("playbackRate")}get bufferedAmount(){return this.stateManager.getValue("bufferedAmount")}get currentProvider(){return this._currentProvider}get fullscreen(){return this.stateManager.getValue("fullscreen")}get live(){return this.stateManager.getValue("live")}get autoplay(){return this.stateManager.getValue("autoplay")}checkDestroyed(){if(this.destroyed)throw new Error("Cannot call methods on destroyed player")}detectMimeType(e){const t=e.split(".").pop()?.toLowerCase();switch(t){case"m3u8":return"application/x-mpegURL";case"mpd":return"application/dash+xml";case"mp4":default:return"video/mp4";case"webm":return"video/webm";case"ogg":return"video/ogg"}}}function p(e){if(e.name)return e.name;if(e.height){const t={2160:"4K",1440:"1440p",1080:"1080p",720:"720p",480:"480p",360:"360p",240:"240p",144:"144p"},r=Object.keys(t).map(Number).sort((t,r)=>Math.abs(t-e.height)-Math.abs(r-e.height))[0];return Math.abs(r-e.height)<=20?t[r]:`${e.height}p`}return e.bitrate?function(e){if(e>=1e6)return`${(e/1e6).toFixed(1)} Mbps`;if(e>=1e3)return`${Math.round(e/1e3)} Kbps`;return`${e} bps`}(e.bitrate):"Unknown"}var m="networkError",v="mediaError",y="muxError";function E(e){switch(e){case m:return"network";case v:return"media";case y:return"mux";default:return"other"}}function T(e,t,r){const i=[],s=(t,r)=>{e.on(t,r),i.push({event:t,handler:r})};return s("hlsManifestParsed",(i,s)=>{t.logger.debug("HLS manifest parsed",{levels:s.levels.length});const n=s.levels.map((t,r)=>({id:`level-${r}`,label:p(t),width:t.width,height:t.height,bitrate:t.bitrate,active:r===e.currentLevel}));t.setState("qualities",n),t.emit("quality:levels",{levels:n.map(e=>({id:e.id,label:e.label}))}),r.onManifestParsed?.(s.levels)}),s("hlsLevelSwitched",(i,s)=>{const n=e.levels[s.level],a=r.getIsAutoQuality?.()??e.autoLevelEnabled;if(t.logger.debug("HLS level switched",{level:s.level,height:n?.height,auto:a}),n){const e=a?`Auto (${p(n)})`:p(n);t.setState("currentQuality",{id:a?"auto":`level-${s.level}`,label:e,width:n.width,height:n.height,bitrate:n.bitrate,active:!0})}t.emit("quality:change",{quality:n?p(n):"auto",auto:a}),r.onLevelSwitched?.(s.level)}),s("hlsFragBuffered",()=>{t.setState("buffering",!1),r.onBufferUpdate?.()}),s("hlsFragLoading",()=>{t.setState("buffering",!0)}),s("hlsLevelLoaded",(e,i)=>{void 0!==i.details?.live&&(t.setState("live",i.details.live),r.onLiveUpdate?.())}),s("hlsError",(e,i)=>{const s=function(e){return{type:E(e.type),details:e.details||"Unknown error",fatal:e.fatal||!1,url:e.url,reason:e.reason,response:e.response}}(i);t.logger.warn("HLS error",{error:s}),r.onError?.(s)}),()=>{for(const{event:t,handler:r}of i)e.off(t,r);i.length=0}}function S(e,t){const r=[],i=(t,i)=>{e.addEventListener(t,i),r.push({event:t,handler:i})};i("playing",()=>{t.setState("playing",!0),t.setState("paused",!1),t.setState("playbackState","playing")}),i("pause",()=>{t.setState("playing",!1),t.setState("paused",!0),t.setState("playbackState","paused")}),i("ended",()=>{t.setState("playing",!1),t.setState("ended",!0),t.setState("playbackState","ended"),t.emit("playback:ended",void 0)}),i("timeupdate",()=>{t.setState("currentTime",e.currentTime),t.emit("playback:timeupdate",{currentTime:e.currentTime})}),i("durationchange",()=>{t.setState("duration",e.duration||0),t.emit("media:loadedmetadata",{duration:e.duration||0})}),i("waiting",()=>{t.setState("waiting",!0),t.setState("buffering",!0),t.emit("media:waiting",void 0)}),i("canplay",()=>{t.setState("waiting",!1),t.setState("playbackState","ready"),t.emit("media:canplay",void 0)}),i("canplaythrough",()=>{t.setState("buffering",!1),t.emit("media:canplaythrough",void 0)}),i("progress",()=>{if(e.buffered.length>0){const r=e.buffered.end(e.buffered.length-1),i=e.duration>0?r/e.duration:0;t.setState("bufferedAmount",i),t.setState("buffered",e.buffered),t.emit("media:progress",{buffered:i})}}),i("seeking",()=>{t.setState("seeking",!0)}),i("seeked",()=>{t.setState("seeking",!1),t.emit("playback:seeked",{time:e.currentTime})}),i("volumechange",()=>{t.setState("volume",e.volume),t.setState("muted",e.muted),t.emit("volume:change",{volume:e.volume,muted:e.muted})}),i("ratechange",()=>{t.setState("playbackRate",e.playbackRate),t.emit("playback:ratechange",{rate:e.playbackRate})}),i("loadedmetadata",()=>{t.setState("duration",e.duration),t.setState("mediaType",e.videoWidth>0?"video":"audio")}),i("error",()=>{const r=e.error;r&&(t.logger.error("Video element error",{code:r.code,message:r.message}),t.emit("media:error",{error:new Error(r.message||"Video playback error")}))}),i("enterpictureinpicture",()=>{t.setState("pip",!0),t.logger.debug("PiP: entered (standard)")}),i("leavepictureinpicture",()=>{t.setState("pip",!1),t.logger.debug("PiP: exited (standard)"),e.paused&&!t.getState("playing")||e.play().catch(()=>{})});const s=e;return"webkitPresentationMode"in e&&i("webkitpresentationmodechanged",()=>{const r=s.webkitPresentationMode,i="picture-in-picture"===r;t.setState("pip",i),t.logger.debug(`PiP: mode changed to ${r} (webkit)`),"inline"===r&&e.paused&&e.play().catch(()=>{})}),()=>{for(const{event:t,handler:i}of r)e.removeEventListener(t,i);r.length=0}}var b=null,L=null;function A(){if("undefined"==typeof document)return!1;return""!==document.createElement("video").canPlayType("application/vnd.apple.mpegurl")}function R(){return b?b.isSupported():"undefined"!=typeof window&&!(!window.MediaSource&&!window.WebKitMediaSource)}var k={debug:!1,autoStartLoad:!0,startPosition:-1,lowLatencyMode:!1,maxBufferLength:30,maxMaxBufferLength:600,backBufferLength:30,enableWorker:!0,maxNetworkRetries:3,maxMediaRetries:2,retryDelayMs:1e3,retryBackoffFactor:2};function D(e){const t={...k,...e};let r=null,i=null,s=null,n=!1,a=null,o=null,l=null,d=!0,h=0,u=0,c=null,f=0,g=0;const m=()=>{if(s)return s;const e=r?.container.querySelector("video");return e?(s=e,s):(s=document.createElement("video"),s.style.cssText="width:100%;height:100%;display:block;object-fit:contain;background:#000",s.preload="metadata",s.controls=!1,s.playsInline=!0,r?.container.appendChild(s),s)},v=()=>{o?.(),o=null,l?.(),l=null,c&&(clearTimeout(c),c=null),i&&(i.destroy(),i=null),a=null,n=!1,d=!0,h=0,u=0,f=0,g=0},y=e=>{const r=t.retryDelayMs??1e3,i=t.retryBackoffFactor??2;return r*Math.pow(i,e)},E=(e,t)=>{const i=t?`HLS error: ${e.details} (max retries exceeded)`:`HLS error: ${e.details}`;r?.logger.error(i,{type:e.type,details:e.details}),r?.setState("playbackState","error"),r?.setState("buffering",!1),r?.emit("error",{code:"MEDIA_ERROR",message:i,fatal:!0,timestamp:Date.now()})},D=e=>{if(!b||!i)return;const s=Date.now();if(s-g>5e3?(f=1,g=s):f++,f>=10)return r?.logger.error(`Too many errors (${f} in 5000ms), giving up`),E(e,!0),o?.(),o=null,i.destroy(),void(i=null);if(e.fatal)switch(r?.logger.error("Fatal HLS error",{type:e.type,details:e.details}),e.type){case"network":{const s=t.maxNetworkRetries??3;if(h>=s)return r?.logger.error(`Network error recovery failed after ${h} attempts`),void E(e,!0);h++;const n=y(h-1);r?.logger.info(`Attempting network error recovery (attempt ${h}/${s}) in ${n}ms`),r?.emit("error:network",{error:new Error(e.details)}),c&&clearTimeout(c),c=setTimeout(()=>{i&&i.startLoad()},n);break}case"media":{const s=t.maxMediaRetries??2;if(u>=s)return r?.logger.error(`Media error recovery failed after ${u} attempts`),void E(e,!0);u++;const n=y(u-1);r?.logger.info(`Attempting media error recovery (attempt ${u}/${s}) in ${n}ms`),r?.emit("error:media",{error:new Error(e.details)}),c&&clearTimeout(c),c=setTimeout(()=>{i&&i.recoverMediaError()},n);break}default:E(e,!1)}},w=async e=>{const t=m();return n=!0,r&&(l=S(t,r)),new Promise((i,s)=>{const n=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a),r?.setState("source",{src:e,type:"application/x-mpegURL"}),r?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),i()},a=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a);const e=t.error;s(new Error(e?.message||"Failed to load HLS source"))};t.addEventListener("loadedmetadata",n),t.addEventListener("error",a),t.src=e,t.load()})},_=async e=>{await async function(){return b||L||(L=(async()=>{try{const e=await Promise.resolve().then(()=>pa);if(!(b=e.default).isSupported())throw new Error("hls.js is not supported in this browser");return b}catch(e){throw L=null,new Error(`Failed to load hls.js: ${e instanceof Error?e.message:"Unknown error"}`)}})())}();const s=m();return n=!1,i=function(e){if(!b)throw new Error("hls.js is not loaded. Call loadHlsJs() first.");return new b(e)}({debug:t.debug,autoStartLoad:t.autoStartLoad,startPosition:t.startPosition,startLevel:-1,lowLatencyMode:t.lowLatencyMode,maxBufferLength:t.maxBufferLength,maxMaxBufferLength:t.maxMaxBufferLength,backBufferLength:t.backBufferLength,enableWorker:t.enableWorker,fragLoadingMaxRetry:1,manifestLoadingMaxRetry:1,levelLoadingMaxRetry:1,fragLoadingRetryDelay:500,manifestLoadingRetryDelay:500,levelLoadingRetryDelay:500}),r&&(l=S(s,r)),new Promise((t,n)=>{if(!i||!r)return void n(new Error("HLS not initialized"));let a=!1;o=T(i,r,{onManifestParsed:()=>{a||(a=!0,r?.setState("source",{src:e,type:"application/x-mpegURL"}),r?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),t())},onLevelSwitched:()=>{},onError:e=>{D(e),e.fatal&&!a&&"network"!==e.type&&"media"!==e.type&&(a=!0,n(new Error(e.details)))},getIsAutoQuality:()=>d}),i.attachMedia(s),i.loadSource(e)})};return{id:"hls-provider",name:"HLS Provider (Light)",version:"1.0.0",type:"provider",description:"HLS playback provider using hls.js/light (smaller bundle)",canPlay(e){if(!A()&&!R())return!1;const t=e.toLowerCase();return!!t.split("?")[0].split("#")[0].endsWith(".m3u8")||(!!t.includes("application/x-mpegurl")||!!t.includes("application/vnd.apple.mpegurl"))},async init(e){r=e,r.logger.info("HLS plugin (light) initialized");const t=r.on("playback:play",async()=>{if(s)try{await s.play()}catch(e){r?.logger.error("Play failed",e)}}),a=r.on("playback:pause",()=>{s?.pause()}),o=r.on("playback:seeking",({time:e})=>{if(!s)return;const t=Math.max(0,Math.min(e,s.duration||0));s.currentTime=t}),l=r.on("volume:change",({volume:e})=>{s&&(s.volume=e)}),h=r.on("volume:mute",({muted:e})=>{s&&(s.muted=e)}),u=r.on("playback:ratechange",({rate:e})=>{s&&(s.playbackRate=e)}),c=r.on("quality:select",({quality:e,auto:t})=>{if(i&&!n)if(t||"auto"===e)d=!0,i.currentLevel=-1,r?.logger.debug("Quality: auto selection enabled"),r?.setState("currentQuality",{id:"auto",label:"Auto",width:0,height:0,bitrate:0,active:!0});else{d=!1;const t=parseInt(e.replace("level-",""),10);!isNaN(t)&&t>=0&&t<i.levels.length&&(i.nextLevel=t,r?.logger.debug(`Quality: queued switch to level ${t}`))}else r?.logger.warn("Quality selection not available")});r.onDestroy(()=>{t(),a(),o(),l(),h(),u(),c()})},async destroy(){r?.logger.info("HLS plugin (light) destroying"),v(),s?.parentNode&&s.parentNode.removeChild(s),s=null,r=null},async loadSource(e){if(!r)throw new Error("Plugin not initialized");if(r.logger.info("Loading HLS source (light)",{src:e}),v(),a=e,r.setState("playbackState","loading"),r.setState("buffering",!0),R())r.logger.info("Using hls.js/light for HLS playback"),await _(e);else{if(!A())throw new Error("HLS playback not supported in this browser");r.logger.info("Using native HLS playback (hls.js not supported)"),await w(e)}r.setState("playbackState","ready"),r.setState("buffering",!1)},getCurrentLevel:()=>n||!i?-1:i.currentLevel,setLevel(e){!n&&i?i.currentLevel=e:r?.logger.warn("Quality selection not available in native HLS mode")},getLevels(){return n||!i?[]:(e=i.levels,i.currentLevel,e.map((e,t)=>({index:t,width:e.width||0,height:e.height||0,bitrate:e.bitrate||0,label:p(e),codec:e.codecSet})));var e},getHlsInstance:()=>i,isNativeHLS:()=>n,getLiveInfo(){if(n||!i)return null;return r?.getState("live")||!1?{isLive:!0,latency:i.latency||0,targetLatency:i.targetLatency||3,drift:i.drift||0}:null},async switchToNative(){if(n)return void r?.logger.debug("Already using native HLS");if(!A())return void r?.logger.warn("Native HLS not supported in this browser");if(!a)return void r?.logger.warn("No source loaded");r?.logger.info("Switching to native HLS for AirPlay");const e=r?.getState("playing")||!1,t=s?.currentTime||0,i=a;if(v(),await w(i),s&&t>0&&(s.currentTime=t),e&&s)try{await s.play()}catch(o){r?.logger.debug("Could not auto-resume after switch")}r?.logger.info("Switched to native HLS")},async switchToHlsJs(){if(!n)return void r?.logger.debug("Already using hls.js");if(!R())return void r?.logger.warn("hls.js not supported in this browser");if(!a)return void r?.logger.warn("No source loaded");r?.logger.info("Switching back to hls.js");const e=r?.getState("playing")||!1,t=s?.currentTime||0,i=a;if(v(),await _(i),s&&t>0&&(s.currentTime=t),e&&s)try{await s.play()}catch(o){r?.logger.debug("Could not auto-resume after switch")}r?.logger.info("Switched to hls.js")}}}var w={play:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',pause:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/></svg>',replay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>',volumeHigh:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',volumeLow:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',volumeMute:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/></svg>',fullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>',exitFullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/></svg>',pip:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z"/></svg>',settings:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>',chromecast:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',chromecastConnected:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',airplay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 22h12l-6-6-6 6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',spinner:'<svg viewBox="0 0 24 24" fill="currentColor" class="sp-spin"><path d="M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8z"/></svg>'};function _(e,t,r){const i=document.createElement(e);if(t)for(const[s,n]of Object.entries(t))"className"===s?i.className=n:i.setAttribute(s,n);return i}function x(e,t,r){const i=_("button",{className:`sp-control ${e}`,"aria-label":t,type:"button"});return i.innerHTML=r,i}function C(e){return e.querySelector("video")}function I(e){if(!isFinite(e)||isNaN(e))return"0:00";const t=Math.abs(e),r=Math.floor(t/3600),i=Math.floor(t%3600/60),s=Math.floor(t%60),n=e<0?"-":"";return r>0?`${n}${r}:${P(i)}:${P(s)}`:`${n}${i}:${P(s)}`}function P(e){return e<10?`0${e}`:`${e}`}function M(e){return e<=0?"LIVE":`-${I(e)}`}var O=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=x("sp-play","Play",w.play),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){const e=this.api.getState("playing");let t,r;this.api.getState("ended")?(t=w.replay,r="Replay"):e?(t=w.pause,r="Pause"):(t=w.play,r="Play"),this.el.innerHTML=t,this.el.setAttribute("aria-label",r)}toggle(){const e=C(this.api.container);if(!e)return;const t=this.api.getState("ended"),r=this.api.getState("playing");t?(e.currentTime=0,e.play().catch(()=>{})):r?e.pause():e.play().catch(()=>{})}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},F=class{constructor(e){this.isDragging=!1,this.lastSeekTime=0,this.seekThrottleMs=100,this.wasPlayingBeforeDrag=!1,this.onMouseDown=e=>{e.preventDefault();const t=C(this.api.container);this.wasPlayingBeforeDrag=!!t&&!t.paused,this.isDragging=!0,this.el.classList.add("sp-progress--dragging"),this.lastSeekTime=0,this.seek(e.clientX,!0)},this.onDocMouseMove=e=>{this.isDragging&&(this.seek(e.clientX),this.updateVisualPosition(e.clientX))},this.onMouseUp=e=>{if(this.isDragging&&(this.seek(e.clientX,!0),this.isDragging=!1,this.el.classList.remove("sp-progress--dragging"),this.wasPlayingBeforeDrag)){const e=C(this.api.container);if(e&&e.paused){const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t)}}},this.onMouseMove=e=>{this.updateTooltip(e.clientX)},this.onMouseLeave=()=>{this.isDragging||(this.tooltip.style.opacity="0")},this.onKeyDown=e=>{const t=C(this.api.container);if(!t)return;const r=this.api.getState("duration")||0;switch(e.key){case"ArrowLeft":e.preventDefault(),t.currentTime=Math.max(0,t.currentTime-5);break;case"ArrowRight":e.preventDefault(),t.currentTime=Math.min(r,t.currentTime+5);break;case"Home":e.preventDefault(),t.currentTime=0;break;case"End":e.preventDefault(),t.currentTime=r}},this.api=e,this.wrapper=_("div",{className:"sp-progress-wrapper"}),this.el=_("div",{className:"sp-progress"});const t=_("div",{className:"sp-progress__track"});this.buffered=_("div",{className:"sp-progress__buffered"}),this.filled=_("div",{className:"sp-progress__filled"}),this.handle=_("div",{className:"sp-progress__handle"}),this.tooltip=_("div",{className:"sp-progress__tooltip"}),this.tooltip.textContent="0:00",t.appendChild(this.buffered),t.appendChild(this.filled),t.appendChild(this.handle),this.el.appendChild(t),this.el.appendChild(this.tooltip),this.wrapper.appendChild(this.el),this.el.setAttribute("role","slider"),this.el.setAttribute("aria-label","Seek"),this.el.setAttribute("aria-valuemin","0"),this.el.setAttribute("tabindex","0"),this.wrapper.addEventListener("mousedown",this.onMouseDown),this.wrapper.addEventListener("mousemove",this.onMouseMove),this.wrapper.addEventListener("mouseleave",this.onMouseLeave),this.el.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.wrapper}show(){this.wrapper.classList.add("sp-progress-wrapper--visible")}hide(){this.wrapper.classList.remove("sp-progress-wrapper--visible")}update(){const e=this.api.getState("currentTime")||0,t=this.api.getState("duration")||0,r=this.api.getState("buffered");if(t>0){const i=e/t*100;if(this.filled.style.width=`${i}%`,this.handle.style.left=`${i}%`,r&&r.length>0){const e=r.end(r.length-1)/t*100;this.buffered.style.width=`${e}%`}this.el.setAttribute("aria-valuemax",String(Math.floor(t))),this.el.setAttribute("aria-valuenow",String(Math.floor(e))),this.el.setAttribute("aria-valuetext",I(e))}}getTimeFromPosition(e){const t=this.el.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*(this.api.getState("duration")||0)}updateTooltip(e){const t=this.el.getBoundingClientRect(),r=Math.max(0,Math.min(1,(e-t.left)/t.width)),i=this.getTimeFromPosition(e);this.tooltip.textContent=I(i),this.tooltip.style.left=100*r+"%"}updateVisualPosition(e){const t=this.el.getBoundingClientRect(),r=Math.max(0,Math.min(1,(e-t.left)/t.width));this.filled.style.width=100*r+"%",this.handle.style.left=100*r+"%"}seek(e,t=!1){const r=C(this.api.container);if(!r)return;const i=Date.now();if(!t&&this.isDragging&&i-this.lastSeekTime<this.seekThrottleMs)return;this.lastSeekTime=i;const s=this.getTimeFromPosition(e);r.currentTime=s}destroy(){this.wrapper.removeEventListener("mousedown",this.onMouseDown),this.wrapper.removeEventListener("mousemove",this.onMouseMove),this.wrapper.removeEventListener("mouseleave",this.onMouseLeave),document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.wrapper.remove()}},N=class{constructor(e){this.api=e,this.el=_("div",{className:"sp-time"}),this.el.setAttribute("aria-live","off")}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("currentTime")||0,r=this.api.getState("duration")||0;if(e){const e=this.api.getState("seekableRange");if(e){const r=e.end-t;this.el.textContent=M(r)}else this.el.textContent=M(0)}else this.el.textContent=`${I(t)} / ${I(r)}`}destroy(){this.el.remove()}},B=class{constructor(e){this.isDragging=!1,this.onMouseDown=e=>{e.preventDefault(),this.isDragging=!0,this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onDocMouseMove=e=>{this.isDragging&&this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onMouseUp=()=>{this.isDragging=!1},this.onKeyDown=e=>{const t=C(this.api.container);if(!t)return;switch(e.key){case"ArrowUp":case"ArrowRight":e.preventDefault(),this.setVolume(t.volume+.1);break;case"ArrowDown":case"ArrowLeft":e.preventDefault(),this.setVolume(t.volume-.1)}},this.api=e,this.el=_("div",{className:"sp-volume"}),this.btn=_("button",{className:"sp-control sp-volume__btn","aria-label":"Mute",type:"button"}),this.btn.innerHTML=w.volumeHigh,this.btn.onclick=()=>this.toggleMute();const t=_("div",{className:"sp-volume__slider-wrap"});this.slider=_("div",{className:"sp-volume__slider"}),this.slider.setAttribute("role","slider"),this.slider.setAttribute("aria-label","Volume"),this.slider.setAttribute("aria-valuemin","0"),this.slider.setAttribute("aria-valuemax","100"),this.slider.setAttribute("tabindex","0"),this.level=_("div",{className:"sp-volume__level"}),this.slider.appendChild(this.level),t.appendChild(this.slider),this.el.appendChild(this.btn),this.el.appendChild(t),this.slider.addEventListener("mousedown",this.onMouseDown),this.slider.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.el}update(){const e=this.api.getState("volume")??1,t=this.api.getState("muted")??!1;let r,i;t||0===e?(r=w.volumeMute,i="Unmute"):e<.5?(r=w.volumeLow,i="Mute"):(r=w.volumeHigh,i="Mute"),this.btn.innerHTML=r,this.btn.setAttribute("aria-label",i);const s=t?0:e;this.level.style.width=100*s+"%",this.slider.setAttribute("aria-valuenow",String(Math.round(100*s)))}toggleMute(){const e=C(this.api.container);e&&(e.muted=!e.muted)}setVolume(e){const t=C(this.api.container);if(!t)return;const r=Math.max(0,Math.min(1,e));t.volume=r,r>0&&t.muted&&(t.muted=!1)}getVolumeFromPosition(e){const t=this.slider.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))}destroy(){document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.el.remove()}},$=class{constructor(e){this.api=e,this.el=_("div",{className:"sp-live"}),this.el.innerHTML='<div class="sp-live__dot"></div><span>LIVE</span>',this.el.setAttribute("role","button"),this.el.setAttribute("aria-label","Seek to live"),this.el.setAttribute("tabindex","0"),this.el.onclick=()=>this.seekToLive(),this.el.onkeydown=e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.seekToLive())}}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("liveEdge");this.el.style.display=e?"":"none",t?this.el.classList.remove("sp-live--behind"):this.el.classList.add("sp-live--behind")}seekToLive(){const e=C(this.api.container);if(!e)return;const t=this.api.getState("seekableRange");t&&(e.currentTime=t.end)}destroy(){this.el.remove()}},U=class{constructor(e){this.isOpen=!1,this.lastQualitiesJson="",this.api=e,this.el=_("div",{className:"sp-quality"}),this.btn=x("sp-quality__btn","Quality",w.settings),this.btnLabel=_("span",{className:"sp-quality__label"}),this.btnLabel.textContent="Auto",this.btn.appendChild(this.btnLabel),this.btn.addEventListener("click",e=>{e.stopPropagation(),this.toggle()}),this.menu=_("div",{className:"sp-quality-menu"}),this.menu.setAttribute("role","menu"),this.menu.addEventListener("click",e=>{e.stopPropagation()}),this.el.appendChild(this.btn),this.el.appendChild(this.menu),this.closeHandler=e=>{this.el.contains(e.target)||this.close()},document.addEventListener("click",this.closeHandler)}render(){return this.el}update(){const e=this.api.getState("qualities")||[],t=this.api.getState("currentQuality");this.el.style.display=e.length>0?"":"none",this.btnLabel.textContent=t?.label||"Auto";const r=JSON.stringify(e.map(e=>e.id)),i=t?.id||"auto";r!==this.lastQualitiesJson&&(this.lastQualitiesJson=r,this.rebuildMenu(e)),this.updateActiveStates(i)}rebuildMenu(e){this.menu.innerHTML="";const t=this.createMenuItem("Auto","auto");this.menu.appendChild(t);const r=[...e].sort((e,t)=>t.height-e.height);for(const i of r){if("auto"===i.id)continue;const e=this.createMenuItem(i.label,i.id);this.menu.appendChild(e)}}updateActiveStates(e){this.menu.querySelectorAll(".sp-quality-menu__item").forEach(t=>{const r=t.getAttribute("data-quality-id")===e;t.classList.toggle("sp-quality-menu__item--active",r)})}createMenuItem(e,t){const r=_("div",{className:"sp-quality-menu__item"});r.setAttribute("role","menuitem"),r.setAttribute("data-quality-id",t);const i=_("span",{className:"sp-quality-menu__label"});return i.textContent=e,r.appendChild(i),r.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.selectQuality(t)}),r}selectQuality(e){this.api.emit("quality:select",{quality:e,auto:"auto"===e}),this.close()}toggle(){this.isOpen?this.close():this.open()}open(){this.isOpen=!0,this.menu.classList.add("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","true")}close(){this.isOpen=!1,this.menu.classList.remove("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","false")}destroy(){document.removeEventListener("click",this.closeHandler),this.el.remove()}};var G=class{constructor(e,t){this.api=e,this.type=t,this.supported="chromecast"===t?function(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent;return/Chrome/.test(e)&&!/Edge|Edg/.test(e)}():"undefined"!=typeof HTMLVideoElement&&"function"==typeof HTMLVideoElement.prototype.webkitShowPlaybackTargetPicker;const r="chromecast"===t?w.chromecast:w.airplay,i="chromecast"===t?"Cast":"AirPlay";this.el=x(`sp-cast sp-cast--${t}`,i,r),this.el.addEventListener("click",()=>this.handleClick()),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(this.supported)if("chromecast"===this.type){const e=this.api.getState("chromecastAvailable"),t=this.api.getState("chromecastActive");this.el.style.display="",this.el.disabled=!e&&!t,this.el.classList.toggle("sp-cast--active",!!t),this.el.classList.toggle("sp-cast--unavailable",!e&&!t),t?(this.el.innerHTML=w.chromecastConnected,this.el.setAttribute("aria-label","Stop casting")):(this.el.innerHTML=w.chromecast,this.el.setAttribute("aria-label",e?"Cast":"No Cast devices found"))}else{const e=this.api.getState("airplayActive");this.el.style.display="",this.el.disabled=!1,this.el.classList.toggle("sp-cast--active",!!e),this.el.classList.remove("sp-cast--unavailable"),this.el.setAttribute("aria-label",e?"Stop AirPlay":"AirPlay")}else this.el.style.display="none"}handleClick(){"chromecast"===this.type?this.handleChromecast():this.handleAirPlay()}handleChromecast(){const e=this.api.getPlugin("chromecast");e&&(e.isConnected()?e.endSession():e.requestSession().catch(()=>{}))}async handleAirPlay(){const e=this.api.getPlugin("airplay");if(e)await e.showPicker();else{const e=C(this.api.container);e?.webkitShowPlaybackTargetPicker?.()}}destroy(){this.el.remove()}},H=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e;const t=document.createElement("video");this.supported="pictureInPictureEnabled"in document||"webkitSetPresentationMode"in t,this.el=x("sp-pip","Picture-in-Picture",w.pip),this.el.addEventListener("click",this.clickHandler),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(!this.supported)return;const e=this.api.getState("pip");this.el.setAttribute("aria-label",e?"Exit Picture-in-Picture":"Picture-in-Picture"),this.el.classList.toggle("sp-pip--active",!!e)}async toggle(){const e=C(this.api.container);if(e)try{document.pictureInPictureElement===e||"picture-in-picture"===e.webkitPresentationMode?(document.pictureInPictureElement?await document.exitPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("inline"),this.api.logger.debug("PiP: exited")):(e.requestPictureInPicture?await e.requestPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("picture-in-picture"),this.api.logger.debug("PiP: entered"))}catch(t){this.api.logger.warn("PiP: failed",{error:t.message})}else this.api.logger.warn("PiP: video element not found")}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},V=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=x("sp-fullscreen","Fullscreen",w.fullscreen),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){this.api.getState("fullscreen")?(this.el.innerHTML=w.exitFullscreen,this.el.setAttribute("aria-label","Exit fullscreen")):(this.el.innerHTML=w.fullscreen,this.el.setAttribute("aria-label","Fullscreen"))}async toggle(){const e=this.api.container,t=C(e);try{document.fullscreenElement?await document.exitFullscreen():e.requestFullscreen?await e.requestFullscreen():t?.webkitEnterFullscreen&&t.webkitEnterFullscreen()}catch{}}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},K=class{constructor(){this.el=_("div",{className:"sp-spacer"})}render(){return this.el}update(){}destroy(){this.el.remove()}},q=["play","volume","time","live-indicator","spacer","quality","chromecast","airplay","pip","fullscreen"];function j(e,...t){for(const r of t){const t=e.getAttribute(r);if(null!==t)return t}return null}function W(e){const t={},r=j(e,"data-src","src","href");r&&(t.src=r);const i=j(e,"data-autoplay","autoplay");null!==i&&(t.autoplay="false"!==i);const s=j(e,"data-muted","muted");null!==s&&(t.muted="false"!==s);const n=j(e,"data-controls","controls");null!==n&&(t.controls="false"!==n);const a=j(e,"data-keyboard","keyboard");null!==a&&(t.keyboard="false"!==a);const o=j(e,"data-loop","loop");null!==o&&(t.loop="false"!==o);const l=j(e,"data-poster","poster");l&&(t.poster=l);const d=j(e,"data-brand-color","data-color","color");d&&(t.brandColor=d);const h=e.getAttribute("data-primary-color");h&&(t.primaryColor=h);const u=e.getAttribute("data-background-color");u&&(t.backgroundColor=u);const c=e.getAttribute("data-width");c&&(t.width=c);const f=e.getAttribute("data-height");f&&(t.height=f);const g=e.getAttribute("data-aspect-ratio");g&&(t.aspectRatio=g);const p=e.getAttribute("data-class");p&&(t.className=p);const m=e.getAttribute("data-hide-delay");if(m){const e=parseInt(m,10);isNaN(e)||(t.hideDelay=e)}const v=e.getAttribute("data-playback-rate");if(v){const e=parseFloat(v);isNaN(e)||(t.playbackRate=e)}const y=e.getAttribute("data-start-time");if(y){const e=parseFloat(y);isNaN(e)||(t.startTime=e)}return t}function Y(e){const t=e.split(":").map(Number),r=t[0],i=t[1];return 2===t.length&&void 0!==r&&void 0!==i&&!isNaN(r)&&!isNaN(i)&&r>0?i/r*100:56.25}function z(e,t){t.className&&e.classList.add(...t.className.split(" ")),t.width&&(e.style.width=t.width),t.height?e.style.height=t.height:t.aspectRatio&&(e.style.position="relative",e.style.paddingBottom=`${Y(t.aspectRatio)}%`,e.style.height="0")}async function X(e,t){if(!t.src)return console.error("[Scarlett Player] No source URL provided"),null;try{z(e,t);const r={};t.brandColor&&(r.accentColor=t.brandColor),t.primaryColor&&(r.primaryColor=t.primaryColor),t.backgroundColor&&(r.backgroundColor=t.backgroundColor);const i={};Object.keys(r).length>0&&(i.theme=r),void 0!==t.hideDelay&&(i.hideDelay=t.hideDelay);const s=[D()];!1!==t.controls&&s.push(function(e={}){let t,r=null,i=null,s=null,n=null,a=null,o=[],l=null,d=null,h=!0;const u=e.controls||q,c=e.hideDelay??3e3,f=e=>{switch(e){case"play":return new O(t);case"volume":return new B(t);case"progress":default:return null;case"time":return new N(t);case"live-indicator":return new $(t);case"quality":return new U(t);case"chromecast":return new G(t,"chromecast");case"airplay":return new G(t,"airplay");case"pip":return new H(t);case"fullscreen":return new V(t);case"spacer":return new K}},g=()=>{o.forEach(e=>e.update()),s?.update();const e=t?.getState("waiting"),r=t?.getState("seeking"),i=t?.getState("playbackState"),a="loading"===i,l=e||r&&!t?.getState("paused")||a;n?.classList.toggle("sp-buffering--visible",!!l)},p=()=>{h||(h=!0,r?.classList.add("sp-controls--visible"),r?.classList.remove("sp-controls--hidden"),i?.classList.add("sp-gradient--visible"),s?.show(),t?.setState("controlsVisible",!0)),v()},m=()=>{const e=t?.getState("paused");e||(h=!1,r?.classList.remove("sp-controls--visible"),r?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),s?.hide(),t?.setState("controlsVisible",!1))},v=()=>{l&&clearTimeout(l),l=setTimeout(m,c)},y=()=>{p()},E=()=>{m()},T=e=>{if(!t.container.contains(document.activeElement))return;const r=t.container.querySelector("video");if(r)switch(e.key){case" ":case"k":e.preventDefault(),r.paused?r.play():r.pause();break;case"m":e.preventDefault(),r.muted=!r.muted;break;case"f":e.preventDefault(),document.fullscreenElement?document.exitFullscreen():t.container.requestFullscreen?.();break;case"ArrowLeft":e.preventDefault(),r.currentTime=Math.max(0,r.currentTime-5),p();break;case"ArrowRight":e.preventDefault(),r.currentTime=Math.min(r.duration||0,r.currentTime+5),p();break;case"ArrowUp":e.preventDefault(),r.volume=Math.min(1,r.volume+.1),p();break;case"ArrowDown":e.preventDefault(),r.volume=Math.max(0,r.volume-.1),p()}};return{id:"ui-controls",name:"UI Controls",type:"ui",version:"1.0.0",async init(l){t=l,a=document.createElement("style"),a.textContent="\n/* ============================================\n Container & Base\n ============================================ */\n.sp-container {\n position: relative;\n width: 100%;\n height: 100%;\n background: #000;\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n}\n\n.sp-container video {\n width: 100%;\n height: 100%;\n display: block;\n object-fit: contain;\n}\n\n.sp-container:focus {\n outline: none;\n}\n\n/* ============================================\n Gradient Overlay\n ============================================ */\n.sp-gradient {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 160px;\n background: linear-gradient(\n to top,\n rgba(0, 0, 0, 0.8) 0%,\n rgba(0, 0, 0, 0.4) 50%,\n transparent 100%\n );\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.25s ease;\n z-index: 5;\n}\n\n.sp-gradient--visible {\n opacity: 1;\n}\n\n/* ============================================\n Controls Container\n ============================================ */\n.sp-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n align-items: center;\n padding: 0 12px 12px;\n gap: 4px;\n opacity: 0;\n transform: translateY(4px);\n transition: opacity 0.25s ease, transform 0.25s ease;\n z-index: 10;\n}\n\n.sp-controls--visible {\n opacity: 1;\n transform: translateY(0);\n}\n\n.sp-controls--hidden {\n opacity: 0;\n transform: translateY(4px);\n pointer-events: none;\n}\n\n/* ============================================\n Progress Bar (Above Controls)\n ============================================ */\n.sp-progress-wrapper {\n position: absolute;\n bottom: 48px;\n left: 12px;\n right: 12px;\n height: 20px;\n display: flex;\n align-items: center;\n cursor: pointer;\n z-index: 10;\n opacity: 0;\n transition: opacity 0.25s ease;\n}\n\n.sp-progress-wrapper--visible {\n opacity: 1;\n}\n\n.sp-progress {\n position: relative;\n width: 100%;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n transition: height 0.15s ease;\n}\n\n.sp-progress-wrapper:hover .sp-progress,\n.sp-progress--dragging {\n height: 5px;\n}\n\n.sp-progress__track {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n border-radius: inherit;\n overflow: hidden;\n}\n\n.sp-progress__buffered {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: rgba(255, 255, 255, 0.4);\n border-radius: inherit;\n transition: width 0.1s linear;\n}\n\n.sp-progress__filled {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: var(--sp-accent, #e50914);\n border-radius: inherit;\n}\n\n.sp-progress__handle {\n position: absolute;\n top: 50%;\n width: 14px;\n height: 14px;\n background: var(--sp-accent, #e50914);\n border-radius: 50%;\n transform: translate(-50%, -50%) scale(0);\n transition: transform 0.15s ease;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__handle,\n.sp-progress--dragging .sp-progress__handle {\n transform: translate(-50%, -50%) scale(1);\n}\n\n/* Progress Tooltip */\n.sp-progress__tooltip {\n position: absolute;\n bottom: calc(100% + 8px);\n padding: 6px 10px;\n background: rgba(20, 20, 20, 0.95);\n color: #fff;\n font-size: 12px;\n font-weight: 500;\n font-variant-numeric: tabular-nums;\n border-radius: 4px;\n white-space: nowrap;\n transform: translateX(-50%);\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.15s ease;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__tooltip {\n opacity: 1;\n}\n\n/* ============================================\n Control Buttons\n ============================================ */\n.sp-control {\n background: none;\n border: none;\n color: rgba(255, 255, 255, 0.9);\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: color 0.15s ease, transform 0.15s ease, background 0.15s ease;\n flex-shrink: 0;\n}\n\n.sp-control:hover {\n color: #fff;\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-control:active {\n transform: scale(0.92);\n}\n\n.sp-control:focus-visible {\n outline: 2px solid var(--sp-accent, #e50914);\n outline-offset: 2px;\n}\n\n.sp-control:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n transform: none;\n}\n\n.sp-control:disabled:hover {\n background: none;\n}\n\n.sp-control svg {\n width: 24px;\n height: 24px;\n fill: currentColor;\n display: block;\n}\n\n.sp-control--small svg {\n width: 20px;\n height: 20px;\n}\n\n/* ============================================\n Spacer\n ============================================ */\n.sp-spacer {\n flex: 1;\n min-width: 0;\n}\n\n/* ============================================\n Time Display\n ============================================ */\n.sp-time {\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n color: rgba(255, 255, 255, 0.9);\n white-space: nowrap;\n padding: 0 4px;\n letter-spacing: 0.02em;\n}\n\n/* ============================================\n Volume Control\n ============================================ */\n.sp-volume {\n display: flex;\n align-items: center;\n position: relative;\n}\n\n.sp-volume__slider-wrap {\n width: 0;\n overflow: hidden;\n transition: width 0.2s ease;\n}\n\n.sp-volume:hover .sp-volume__slider-wrap,\n.sp-volume:focus-within .sp-volume__slider-wrap {\n width: 64px;\n}\n\n.sp-volume__slider {\n width: 64px;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n cursor: pointer;\n position: relative;\n margin: 0 8px 0 4px;\n}\n\n.sp-volume__level {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: #fff;\n border-radius: inherit;\n transition: width 0.1s ease;\n}\n\n/* ============================================\n Live Indicator\n ============================================ */\n.sp-live {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 11px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--sp-accent, #e50914);\n cursor: pointer;\n padding: 6px 10px;\n border-radius: 4px;\n transition: background 0.15s ease, opacity 0.15s ease;\n}\n\n.sp-live:hover {\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-live__dot {\n width: 8px;\n height: 8px;\n background: currentColor;\n border-radius: 50%;\n animation: sp-pulse 2s ease-in-out infinite;\n}\n\n.sp-live--behind {\n opacity: 0.6;\n}\n\n.sp-live--behind .sp-live__dot {\n animation: none;\n}\n\n@keyframes sp-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.4; }\n}\n\n/* ============================================\n Quality / Settings Menu\n ============================================ */\n.sp-quality {\n position: relative;\n}\n\n.sp-quality__btn {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.sp-quality__label {\n font-size: 12px;\n font-weight: 500;\n opacity: 0.9;\n}\n\n.sp-quality-menu {\n position: absolute;\n bottom: calc(100% + 8px);\n right: 0;\n background: rgba(20, 20, 20, 0.95);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border-radius: 8px;\n padding: 8px 0;\n min-width: 150px;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);\n opacity: 0;\n visibility: hidden;\n transform: translateY(8px);\n transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s;\n z-index: 20;\n}\n\n.sp-quality-menu--open {\n opacity: 1;\n visibility: visible;\n transform: translateY(0);\n}\n\n.sp-quality-menu__item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 16px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.8);\n cursor: pointer;\n transition: background 0.1s ease, color 0.1s ease;\n}\n\n.sp-quality-menu__item:hover {\n background: rgba(255, 255, 255, 0.1);\n color: #fff;\n}\n\n.sp-quality-menu__item--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-quality-menu__check {\n width: 16px;\n height: 16px;\n fill: currentColor;\n margin-left: 8px;\n opacity: 0;\n}\n\n.sp-quality-menu__item--active .sp-quality-menu__check {\n opacity: 1;\n}\n\n/* ============================================\n Cast Button States\n ============================================ */\n.sp-cast--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-cast--unavailable {\n opacity: 0.4;\n}\n\n/* ============================================\n Buffering Indicator\n ============================================ */\n.sp-buffering {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 15;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.2s ease;\n}\n\n.sp-buffering--visible {\n opacity: 1;\n}\n\n.sp-buffering svg {\n width: 48px;\n height: 48px;\n fill: rgba(255, 255, 255, 0.9);\n filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));\n}\n\n@keyframes sp-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n}\n\n.sp-spin {\n animation: sp-spin 0.8s linear infinite;\n}\n\n/* ============================================\n Reduced Motion\n ============================================ */\n@media (prefers-reduced-motion: reduce) {\n .sp-gradient,\n .sp-controls,\n .sp-progress-wrapper,\n .sp-progress,\n .sp-progress__handle,\n .sp-progress__tooltip,\n .sp-control,\n .sp-volume__slider-wrap,\n .sp-quality-menu,\n .sp-buffering {\n transition: none;\n }\n\n .sp-live__dot,\n .sp-spin {\n animation: none;\n }\n}\n\n/* ============================================\n CSS Custom Properties (Theming)\n ============================================ */\n:root {\n --sp-accent: #e50914;\n --sp-color: #fff;\n --sp-bg: rgba(0, 0, 0, 0.8);\n --sp-control-height: 48px;\n --sp-icon-size: 24px;\n}\n",document.head.appendChild(a),e.theme&&this.setTheme(e.theme);const h=t.container;if(h){"static"===getComputedStyle(h).position&&(h.style.position="relative"),i=document.createElement("div"),i.className="sp-gradient sp-gradient--visible",h.appendChild(i),n=document.createElement("div"),n.className="sp-buffering",n.innerHTML=w.spinner,n.setAttribute("aria-hidden","true"),h.appendChild(n),s=new F(t),h.appendChild(s.render()),s.show(),r=document.createElement("div"),r.className="sp-controls sp-controls--visible",r.setAttribute("role","toolbar"),r.setAttribute("aria-label","Video controls");for(const e of u){const t=f(e);t&&(o.push(t),r.appendChild(t.render()))}h.appendChild(r),h.addEventListener("mousemove",y),h.addEventListener("mouseenter",y),h.addEventListener("mouseleave",E),h.addEventListener("touchstart",y,{passive:!0}),h.addEventListener("click",y),document.addEventListener("keydown",T),d=t.subscribeToState(g),document.addEventListener("fullscreenchange",g),g(),h.hasAttribute("tabindex")||h.setAttribute("tabindex","0"),t.logger.debug("UI controls plugin initialized")}else t.logger.error("UI plugin: container not found")},async destroy(){l&&(clearTimeout(l),l=null),d?.(),d=null,t?.container&&(t.container.removeEventListener("mousemove",y),t.container.removeEventListener("mouseenter",y),t.container.removeEventListener("mouseleave",E),t.container.removeEventListener("touchstart",y),t.container.removeEventListener("click",y)),document.removeEventListener("keydown",T),document.removeEventListener("fullscreenchange",g),o.forEach(e=>e.destroy()),o=[],s?.destroy(),s=null,r?.remove(),r=null,i?.remove(),i=null,n?.remove(),n=null,a?.remove(),a=null,t?.logger.debug("UI controls plugin destroyed")},show(){p()},hide(){h=!1,r?.classList.remove("sp-controls--visible"),r?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),s?.hide(),t?.setState("controlsVisible",!1)},setTheme(e){const r=t?.container||document.documentElement;e.primaryColor&&r.style.setProperty("--sp-color",e.primaryColor),e.accentColor&&r.style.setProperty("--sp-accent",e.accentColor),e.backgroundColor&&r.style.setProperty("--sp-bg",e.backgroundColor),e.controlBarHeight&&r.style.setProperty("--sp-control-height",`${e.controlBarHeight}px`),e.iconSize&&r.style.setProperty("--sp-icon-size",`${e.iconSize}px`)},getControlBar:()=>r}}(i));const n=await async function(e){const t=new g(e);return await t.init(),t}({container:e,src:t.src,autoplay:t.autoplay||!1,muted:t.muted||!1,poster:t.poster,loop:t.loop||!1,plugins:s}),a=e.querySelector("video");return a&&(t.playbackRate&&(a.playbackRate=t.playbackRate),t.startTime&&(a.currentTime=t.startTime)),n}catch(r){return console.error("[Scarlett Player] Failed to create player:",r),null}}async function Q(e){if(e.hasAttribute("data-scarlett-initialized"))return null;const t=W(e);e.setAttribute("data-scarlett-initialized","true");const r=await X(e,t);return r||e.removeAttribute("data-scarlett-initialized"),r}const J=["[data-scarlett-player]","[data-sp]","[data-video-player]",".scarlett-player"];async function Z(){const e=J.join(", "),t=document.querySelectorAll(e),r=Array.from(t).map(e=>Q(e));await Promise.all(r),t.length>0&&console.log(`[Scarlett Player] Initialized ${t.length} player(s) (light build)`)}async function ee(e){let t=null;if("string"==typeof e.container){if(t=document.querySelector(e.container),!t)return console.error(`[Scarlett Player] Container not found: ${e.container}`),null}else t=e.container;return X(t,{...e})}const te={create:ee,initAll:Z,version:"0.1.0-light"};"undefined"!=typeof window&&(window.ScarlettPlayer=te),"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Z()}):Z());const re=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ie=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=se},se=Number.MAX_SAFE_INTEGER||9007199254740991;let ne=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ae=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),oe=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var le="manifest",de="level",he="audioTrack",ue="subtitleTrack",ce={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class fe{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ge{constructor(e,t,r,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fe(e),this.fast_=new fe(t),this.defaultTTFB_=i,this.ttfb_=new fe(e)}update(e,t){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new fe(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new fe(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new fe(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function pe(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function me(){return me=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},me.apply(null,arguments)}function ve(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function ye(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(r),!0).forEach(function(t){pe(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ve(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}class Ee{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${e}]:`;this.trace=Te,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}}const Te=function(){},Se={trace:Te,debug:Te,log:Te,warn:Te,info:Te,error:Te};function be(){return me({},Se)}function Le(e,t,r){return t[e]?t[e].bind(t):function(e,t){const r=self.console[e];return r?r.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Te}(e,r)}const Ae=be();const Re=Ae;function ke(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var De,we;var _e=we?De:(we=1,De={}),xe=ke(_e);function Ce(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ie(e,t=!1){if("undefined"!=typeof TextDecoder){const r=new TextDecoder("utf-8").decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let i,s,n,a="",o=0;for(;o<r;){if(i=e[o++],0===i&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:s=e[o++],a+=String.fromCharCode((31&i)<<6|63&s);break;case 14:s=e[o++],n=e[o++],a+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&n)}}return a}function Pe(e){let t="";for(let r=0;r<e.length;r++){let i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Me(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Oe,Fe={exports:{}};var Ne,Be,$e,Ue,Ge,He=(Oe||(Oe=1,Ne=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Be=/^(?=([^\/?#]*))\1([^]*)$/,$e=/(?:\/|^)\.(?=\/)/g,Ue=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,Fe.exports=Ge={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=Ge.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=Ge.normalizePath(i.path),Ge.buildURLFromParts(i)}var s=Ge.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=Ge.normalizePath(s.path),Ge.buildURLFromParts(s)):t;var n=Ge.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Be.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=Ge.normalizePath(d)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=r.alwaysNormalize?Ge.normalizePath(s.path):s.path),Ge.buildURLFromParts(o)},parseURL:function(e){var t=Ne.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace($e,"");e.length!==(e=e.replace(Ue,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),Fe.exports);class Ve{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Ke="audio",qe="video",je="audiovideo";class We{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const r=Qe(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let i;i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Ke]:null,[qe]:null,[je]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Ve),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=He.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ke]=null,e[qe]=null,e[je]=null}}function Ye(e){return"initSegment"!==e.sn}class ze extends We{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(re(e)&&re(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const r=this._decryptdata=t[e[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=re(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),r=e.length;if(r>1||1===r&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){re(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Ye(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var r;const i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,i,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:s,partial:n}}}class Xe extends We{constructor(e,t,r,i,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Qe(e,t){const r=Object.getPrototypeOf(e);if(r){const e=Object.getOwnPropertyDescriptor(r,t);return e||Qe(r,t)}}const Je=Math.pow(2,32)-1,Ze=[].push,et={video:1,audio:2,id3:3,text:4};function tt(e){return String.fromCharCode.apply(null,e)}function rt(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function it(e,t){const r=nt(e,t);return r<0?4294967296+r:r}function st(e,t){let r=it(e,t);return r*=Math.pow(2,32),r+=it(e,t+4),r}function nt(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function at(e,t){const r=[];if(!t.length)return r;const i=e.byteLength;for(let s=0;s<i;){const n=it(e,s),a=n>1?s+n:i;if(tt(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{const i=at(e.subarray(s+8,a),t.slice(1));i.length&&Ze.apply(r,i)}s=a}return r}function ot(e){const t=[],r=e[0];let i=8;const s=it(e,i);i+=4;let n=0,a=0;0===r?(n=it(e,i),a=it(e,i+4),i+=8):(n=st(e,i),a=st(e,i+8),i+=16),i+=2;let o=e.length+a;const l=rt(e,i);i+=2;for(let d=0;d<l;d++){let r=i;const n=it(e,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return Re.warn("SIDX has hierarchical references (not supported)"),null;const l=it(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,r+=4,i=r}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:t}}function lt(e){const t=[],r=at(e,["moov","trak"]);for(let i=0;i<r.length;i++){const e=r[i],s=at(e,["tkhd"])[0];if(s){let r=s[0];const i=it(s,0===r?12:20),n=at(e,["mdia","mdhd"])[0];if(n){r=n[0];const s=it(n,0===r?12:20),a=at(e,["mdia","hdlr"])[0];if(a){const r=tt(a.subarray(8,12)),n={soun:Ke,vide:qe}[r],o=dt(at(e,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:s,type:n,stsd:o},t[n]=ye({timescale:s,id:i},o)):t[i]={timescale:s,type:r,stsd:o}}}}}return at(e,["moov","mvex","trex"]).forEach(e=>{const r=it(e,4),i=t[r];i&&(i.default={duration:it(e,12),flags:it(e,20)})}),t}function dt(e){const t=e.subarray(8),r=t.subarray(86),i=tt(t.subarray(4,8));let s,n=i;const a="enca"===i||"encv"===i;if(a){const e=at(t,[i])[0];at(e.subarray("enca"===i?28:78),["sinf"]).forEach(e=>{const t=at(e,["schm"])[0];if(t){const r=tt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=at(e,["frma"])[0];t&&(n=tt(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=at(r,["avcC"])[0];e&&e.length>3&&(n+="."+ct(e[1])+ct(e[2])+ct(e[3]),s=ht("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const e=at(t,[i])[0],r=at(e.subarray(28),["esds"])[0];if(r&&r.length>7){let e=4;if(3!==r[e++])break;e=ut(r,e),e+=2;const t=r[e++];if(128&t&&(e+=2),64&t&&(e+=r[e++]),4!==r[e++])break;e=ut(r,e);const i=r[e++];if(64!==i)break;if(n+="."+ct(i),e+=12,5!==r[e++])break;e=ut(r,e);const s=r[e++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&r[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=at(r,["hvcC"])[0];if(e&&e.length>12){const t=e[1],r=["","A","B","C"][t>>6],i=31&t,s=it(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+r+i,n+="."+function(e){let t=0;for(let r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let e=l.length;e--;){const t=l[e];if(t||d){d="."+t.toString(16).toUpperCase()+d}}n+=d}s=ht("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ht(n,r)||n;break;case"vp09":{const e=at(r,["vpcC"])[0];if(e&&e.length>6){const t=e[4],r=e[5],i=e[6]>>4&15;n+="."+ft(t)+"."+ft(r)+"."+ft(i)}break}case"av01":{const e=at(r,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&o?l?12:10:o?10:8,h=(16&e[2])>>4,u=(8&e[2])>>3,c=(4&e[2])>>2,f=3&e[2],g=1,p=1,m=1,v=0;n+="."+t+"."+ft(i)+a+"."+ft(d)+"."+h+"."+u+c+f+"."+ft(g)+"."+ft(p)+"."+ft(m)+"."+v,s=ht("dav1",r)}break}}return{codec:n,encrypted:a,supplemental:s}}function ht(e,t){const r=at(t,["dvvC"]),i=r.length?r[0]:at(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return e+"."+ft(t)+"."+ft(r)}}function ut(e,t){const r=t+5;for(;128&e[t++]&&t<r;);return t}function ct(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function ft(e){return(e<10?"0":"")+e}function gt(e,t){at(e,["moov","trak"]).forEach(e=>{const r=at(e,["mdia","minf","stbl","stsd"])[0];if(!r)return;const i=r.subarray(8);let s=at(i,["enca"]);const n=s.length>0;n||(s=at(i,["encv"])),s.forEach(e=>{at(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const r=function(e){const t=at(e,["schm"])[0];if(t){const r=tt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=at(e,["schi","tenc"])[0];if(t)return t}}}(e);r&&t(r,n)})})})}function pt(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function mt(e,t){const r=[],i=t.samples,s=t.timescale,n=t.id;let a=!1;return at(i,["moof"]).map(o=>{const l=o.byteOffset-8;at(o,["traf"]).map(o=>{const d=at(o,["tfdt"]).map(e=>{const t=e[0];let r=it(e,4);return 1===t&&(r*=Math.pow(2,32),r+=it(e,8)),r/s})[0];return void 0!==d&&(e=d),at(o,["tfhd"]).map(d=>{const h=it(d,4),u=16777215&it(d,0);let c=0;const f=!!(16&u);let g=0;const p=!!(32&u);let m=8;h===n&&(!!(1&u)&&(m+=8),!!(2&u)&&(m+=4),!!(8&u)&&(c=it(d,m),m+=4),f&&(g=it(d,m),m+=4),p&&(m+=4),"video"===t.type&&(a=vt(t.codec)),at(o,["trun"]).map(n=>{const o=n[0],d=16777215&it(n,0),h=!!(1&d);let u=0;const f=!!(4&d),p=!!(256&d);let m=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const b=it(n,4);let L=8;h&&(u=it(n,L),L+=4),f&&(L+=4);let A=u+l;for(let l=0;l<b;l++){if(p?(m=it(n,L),L+=4):m=c,v?(y=it(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?it(n,L):nt(n,L),L+=4),t.type===qe){let t=0;for(;t<y;){const n=it(i,A);if(A+=4,yt(a,i[A])){Et(i.subarray(A,A+n),a?2:1,e+S/s,r)}A+=n,t+=n+4}}e+=m/s}}))})})}),r}function vt(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function yt(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Et(e,t,r,i){const s=Tt(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(o<e)n+=o;else if(o>e){Re.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=rt(s,t);if(t+=2,49===e){const e=it(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=s[t++]}i.push({type:e,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o>16){const e=[];for(let r=0;r<16;r++){const i=s[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==r&&5!==r&&7!==r&&9!==r||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let r=0;r<n;r++)l[r]=s[t++];i.push({payloadType:a,pts:r,uuid:e.join(""),userData:Ie(l),userDataBytes:l})}}}function Tt(e){const t=e.byteLength,r=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;const s=t-r.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=e[a];return n}const St=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),bt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Lt(e,t){const r=bt[t];return!!r&&!!r[e.slice(0,4)]}function At(e,t,r=!0){return!e.split(",").some(e=>!Rt(e,t,r))}function Rt(e,t,r=!0){var i;const s=Ce(r);return null!=(i=null==s?void 0:s.isTypeSupported(kt(e,t)))&&i}function kt(e,t){return`${t}/mp4;codecs=${e}`}function Dt(e){if(e){const t=e.substring(0,4);return bt.video[t]}return 2}function wt(e){const t=St();return e.split(",").reduce((e,r)=>{const i=t&&vt(r)?9:bt.video[r];return i?(2*i+e)/(e?3:2):(bt.audio[r]+e)/(e?2:1)},0)}const _t={};const xt=/flac|opus|mp4a\.40\.34/i;function Ct(e,t=!0){return e.replace(xt,e=>function(e,t=!0){if(_t[e])return _t[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<r.length;s++){var i;if(Rt(r[s],"audio",t))return _t[e]=r[s],r[s];if("mp3"===r[s]&&null!=(i=Ce(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function It(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Pt(e,"audio")||Pt(e,"video")))return e;if(t){const r=t.split(",");if(r.length>1){if(e)for(let t=r.length;t--;)if(r[t].substring(0,4)===e.substring(0,4))return r[t];return r[0]}}return t||e}function Pt(e,t){return Lt(e,t)&&Rt(e,t)}function Mt(e){if(e.startsWith("av01.")){const t=e.split("."),r=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=r[e-4];return t.join(".")}return e}function Ot(e){const t=Ce(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function Ft(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Nt=["NONE","TYPE-0","TYPE-1",null];const Bt=["SDR","PQ","HLG"];var $t={No:"",Yes:"YES",v2:"v2"};function Ut(e){const{canSkipUntil:t,canSkipDateRanges:r,age:i}=e;return t&&i<t/2?r?$t.v2:$t.Yes:$t.No}class Gt{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Ht{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=null==(t=e.supplemental)?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Vt(this._audioGroups,e)}hasSubtitleGroup(e){return Vt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Vt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Kt(e,t){let r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||Bt.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;r=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}const qt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(r,i)=>{if(e&&(i=e(r,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}})(t));function jt(e,t){Re.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Wt(e){return e.reduce((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Yt(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}class zt extends Ee{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:r,partCurrent:i,hls:s}=this,{autoLevelEnabled:n,media:a}=s;if(!r||!a)return;const o=performance.now(),l=i?i.stats:r.stats,d=i?i.duration:r.duration,h=o-l.loading.start,u=s.minAutoLevel,c=r.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||c<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==c,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=s.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*y)*1e3))return;const E=m?m.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,b=this.getBwEstimate(),L=s.levels,A=L[c],R=Math.max(l.loaded,Math.round(d*(r.bitrate||A.averageBitrate)/8));let k=S?h-T:h;k<1&&S&&(k=Math.min(h,8*l.loaded/b));const D=S?1e3*l.loaded/k:0,w=v/1e3,_=D?(R-l.loaded)/D:8*R/b+w;if(_<=E)return;const x=D?8*D:b,C=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),I=this.hls.config.abrBandWidthUpFactor;let P,M=Number.POSITIVE_INFINITY;for(P=c-1;P>u;P--){const e=L[P].maxBitrate,t=!L[P].details||C;if(M=this.getTimeToLoadFrag(w,x,d*e,t),M<Math.min(E,d+w))break}if(M>=_)return;if(M>10*d)return;S?this.bwEstimator.sample(h-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(h);const O=L[P].maxBitrate;this.getBwEstimate()*I>O&&this.resetEstimator(O);const F=this.findBestLevel(O,u,P,0,E,1,1);F>-1&&(P=F),this.warn(`Fragment ${r.sn}${i?" part "+i.index:""} of level ${c} is loading too slowly;\n Fragment duration: ${r.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${_.toFixed(3)} s\n Estimated load time for down switch fragment: ${M.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${re(b)?0|b:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${P} @ ${0|O} bps`),s.nextLoadLevel=s.nextAutoLevel=P,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===P&&P>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${P>0?"and switching down":""}\n Fragment duration: ${r.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,P>u){let t=this.findBestLevel(this.hls.levels[u].bitrate,u,P,0,e,1,1);-1===t&&(t=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||_>2*M?N():this.timer=self.setInterval(N,1e3*M),s.trigger(oe.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ge(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ae.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:r,partCurrent:i}=this;if(e&&r&&e.sn===r.sn&&e.level===r.level){const t=performance.now(),r=i?i.stats:e.stats,s=t-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),r.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{loading:i}=t.stats,s=i.end-i.first;re(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const i=r?r.stats:t.stats;if(t.type===ce.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+i.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:r,id:t.type};this.onFragBuffered(oe.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:i}=t,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ce.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,t,e,0,i,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:i,config:s,minAutoLevel:n}=r,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=s.abrBandWidthFactor,h=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,d,h);if(e>=0)return this.rebufferNotice=-1,e}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1}}const c=this.findBestLevel(o,n,i,l,u,d,h);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=r.levels[n],g=r.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,i,s,n,a){var o;const l=i+s,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:c}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===p||-1===d;let T,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:A}=m;this.audioTracksByGroup||(this.audioTracksByGroup=Wt(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((e,t,r)=>{if(!t.codecSet)return e;const i=t.audioGroups;let s=e[t.codecSet];s||(e[t.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,t.bitrate);const n=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,e},{})}(f,0,t,r)),s=function(e,t,r,i,s){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==s?void 0:s.videoCodec,d=a&&2===parseInt(a);let h=!1,u=!1,c=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Kt(t,s);for(let L=n.length;L--;){const t=e[n[L]];h||(h=t.channels[2]>0),c=Math.min(c,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),E.filter(e=>t.videoRanges[e]>0).length>0&&(u=!0)}c=re(c)?c:0,f=re(f)?f:0;const T=Math.max(1080,c),S=Math.max(30,f);g=re(g)?g:r,r=Math.max(g,r),u||(t=void 0);const b=n.length>1;return{codecSet:n.reduce((t,i)=>{const s=e[i];if(i===t)return t;if(v=u?E.filter(e=>s.videoRanges[e]>0):[],b){if(s.minBitrate>r)return jt(i,`min bitrate of ${s.minBitrate} > current estimate of ${r}`),t;if(!s.hasDefaultAudio)return jt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return jt(i,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!s.channels[a])return jt(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||d)&&h&&0===s.channels[2])return jt(i,"no renditions with stereo sound found"),t;if(s.minHeight>T)return jt(i,`min resolution of ${s.minHeight} > maximum of ${T}`),t;if(s.minFramerate>S)return jt(i,`min framerate of ${s.minFramerate} > maximum of ${S}`),t;if(!v.some(e=>s.videoRanges[e]>0))return jt(i,`no variants with VIDEO-RANGE of ${qt(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return jt(i,`video codec preference "${l}" not found`),t;if(s.maxScore<m)return jt(i,`max score of ${s.maxScore} < selected max of ${m}`),t}return t&&(wt(i)>=wt(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,m=s.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(i,S,e,L,A),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:h}=s;R=d,T=n,S=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),this.log(`picked start tier ${qt(s)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=c?c.duration:u?u.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let x=r;x>=t;x--){var _;const t=f[x],o=x>h;if(!t)continue;if((T&&t.codecSet!==T||S&&t.videoRange!==S||o&&b>t.frameRate||!o&&b>0&&b<t.frameRate||null!=(_=t.supportedResult)&&null!=(_=_.decodingInfoResults)&&_.some(e=>!1===e.smooth))&&(!E||x!==R)){w.push(x);continue}const u=t.details,g=(c?null==u?void 0:u.partTarget:null==u?void 0:u.averagetargetduration)||k;let m;m=o?a*e:n*e;const v=k&&i>=2*k&&0===s?t.averageBitrate:t.maxBitrate,L=this.getTimeToLoadFrag(D,m,v*g,void 0===u);if(m>=v&&(x===d||0===t.loadError&&0===t.fragmentError)&&(L<=D||!re(L)||y&&!this.bitrateTestDelay||L<l)){const e=this.forcedAutoLevel;return x===p||-1!==e&&e===p||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${x} adjustedbw(${Math.round(m)})-bitrate=${Math.round(m-v)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${L.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=x),x}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}}const Xt=function(e,t){let r=0,i=e.length-1,s=null,n=null;for(;r<=i;){s=(r+i)/2|0,n=e[s];const a=t(n);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function Qt(e,t,r=0,i=0,s=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-r;i>0&&i<15e-7&&(r+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Jt(r,i,n)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),r);return e.start<=i}return!1}(n,e,Math.min(s,i))))return n;const a=Xt(t,Jt.bind(null,r,i));return!a||a===e&&n?n:a}function Jt(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Zt(e,t,r){const i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function er(e){switch(e.details){case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_TIMEOUT:case ae.LEVEL_LOAD_TIMEOUT:case ae.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function tr(e){return e.details.startsWith("key")}function rr(e){return tr(e)&&!!e.frag&&!e.frag.decryptdata}function ir(e,t){const r=er(t);return e.default[(r?"timeout":"error")+"Retry"]}function sr(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function nr(e){return ye(ye({},e),{errorRetry:null,timeoutRetry:null})}function ar(e,t,r,i){if(!e)return!1;const s=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return or(e)||!!e&&(e<400||e>499)}(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}function or(e){return 0===e&&!1===navigator.onLine}var lr={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},dr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class hr extends Ee{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.ERROR,this.onError,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.ERROR,this.onError,this),e.off(oe.ERROR,this.onErrorOut,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===ce.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;const i=e.audioGroups;if(i){return this.hls.allAudioTracks.filter(e=>i.indexOf(e.groupId)>=0).some(e=>{var r;return null==(r=e.details)?void 0:r.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const i=this.hls,s=t.context;switch(t.details){case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ae.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=ur());case ae.FRAG_GAP:case ae.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=lr.SendAlternateToPenaltyBox);case ae.LEVEL_EMPTY_ERROR:case ae.LEVEL_PARSING_ERROR:{var n;const e=t.parent===ce.MAIN?t.level:i.loadLevel;t.details===ae.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case ae.AUDIO_TRACK_LOAD_ERROR:case ae.AUDIO_TRACK_LOAD_TIMEOUT:case ae.SUBTITLE_LOAD_ERROR:case ae.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const e=i.loadLevelObj;if(e&&(s.type===he&&e.hasAudioGroup(s.groupId)||s.type===ue&&e.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=lr.SendAlternateToPenaltyBox,void(t.errorAction.flags=dr.MoveAllAlternatesMatchingHost)}return;case ae.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:lr.SendAlternateToPenaltyBox,flags:dr.MoveAllAlternatesMatchingHDCP});case ae.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ae.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ae.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:lr.SendAlternateToPenaltyBox,flags:dr.MoveAllAlternatesMatchingKey});case ae.BUFFER_ADD_CODEC_ERROR:case ae.REMUX_ALLOC_ERROR:case ae.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:i.loadLevel);return;case ae.INTERNAL_EXCEPTION:case ae.BUFFER_APPENDING_ERROR:case ae.BUFFER_FULL_ERROR:case ae.LEVEL_SWITCH_ERROR:case ae.BUFFER_STALLED_ERROR:case ae.BUFFER_SEEK_OVER_HOLE:case ae.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=ur())}t.type===ne.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ur())}getPlaylistRetryOrSwitchAction(e,t){const r=ir(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(ar(r,i,er(e),e.response))return{action:lr.RetryRequest,flags:dr.None,retryConfig:r,retryCount:i};const s=this.getLevelSwitchAction(e,t);return r&&(s.retryConfig=r,s.retryCount=i),s}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=ir(tr(e)?n:s,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(i&&(e.details!==ae.FRAG_GAP&&i.fragmentError++,!rr(e))){if(ar(a,o,er(e),e.response))return{action:lr.RetryRequest,flags:dr.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const i=this.hls.levels[t];if(i){var s,n;const t=e.details;i.loadError++,t===ae.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:u,maxAutoLevel:c}=r;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);const f=null==(s=e.frag)?void 0:s.type,g=(f===ce.AUDIO&&t===ae.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>i.audioCodec!==e),p="video"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t),{type:m,groupId:v}=null!=(n=e.context)?n:{};for(let r=d.length;r--;){const s=(r+h)%d.length;if(s!==h&&s>=u&&s<=c&&0===d[s].loadError){var a,o;const r=d[s];if(t===ae.FRAG_GAP&&f===ce.MAIN&&e.frag){const t=d[s].details;if(t){const r=Qt(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(m===he&&r.hasAudioGroup(v)||m===ue&&r.hasSubtitleGroup(v))continue;if(f===ce.AUDIO&&null!=(a=i.audioGroups)&&a.some(e=>r.hasAudioGroup(e))||f===ce.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(e=>r.hasSubtitleGroup(e))||g&&i.audioCodec===r.audioCodec||p&&i.codecSet===r.codecSet||!g&&i.codecSet!==r.codecSet)continue}l=s;break}}if(l>-1&&r.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:lr.SendAlternateToPenaltyBox,flags:dr.None,nextAutoLevel:l}}return{action:lr.SendAlternateToPenaltyBox,flags:dr.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case lr.DoNothing:break;case lr.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ae.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:i}=r,s=r.nextAutoLevel;switch(i){case dr.None:this.switchLevel(e,s);break;case dr.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(e.frag),s=t.levels[i],n=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=Nt[Nt.indexOf(n)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case dr.MoveAllAlternatesMatchingKey:{const t=e.decryptdata;if(t){const i=this.hls.levels,s=i.length;for(let r=s;r--;){var n,a;if(this.variantHasKey(i[r],t))this.log(`Banned key found in level ${r} (${i[r].bitrate}bps) or audio group "${null==(n=i[r].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${Pe(t.keyId||[])}`),i[r].fragmentError++,i[r].loadError++,this.log(`Removing level ${r} with key error (${e.error})`),this.hls.removeLevel(r)}const o=e.frag;if(this.hls.levels.length<s)r.resolved=!0;else if(o&&o.type!==ce.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ae.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=Ft(e.mimeType),r=this.hls.levels;for(let i=r.length;i--;)r[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}}function ur(e){const t={action:lr.DoNothing,flags:dr.None};return e&&(t.resolved=!0),t}const cr=/^(\d+)x(\d+)$/,fr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class gr{constructor(e,t){"string"==typeof e&&(e=gr.parseAttrList(e,t)),me(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=cr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const i={};for(fr.lastIndex=0;null!==(r=fr.exec(e));){const s=r[1].trim();let n=r[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o));else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Re.warn(`${e}: attribute ${s} is missing quotes`)}i[s]=n}return i}}function pr(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function mr(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class vr{constructor(e,t,r=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:r,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){Re.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=me(new gr({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);re(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Re.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(re(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&re(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class yr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return!!this.fragments.length&&re(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Er(e,t){return e.length===t.length&&!e.some((e,r)=>e!==t[r])}function Tr(e,t){return!e&&!t||!(!e||!t)&&Er(e,t)}var Sr=0,br=1;function Lr(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Ar(e){switch(e){case"AES-128":case"AES-256":return Sr;case"AES-256-CTR":return br;default:throw new Error(`invalid full segment method ${e}`)}}let Rr={};class kr{static clearKeyUriToKeyIdMap(){Rr={}}static setKeyIdForUri(e,t){Rr[e]=t}static addKeyIdForUri(e){const t=Object.keys(Rr).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),Rr[e]=r,r}constructor(e,t,r,i=[1],s=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Lr(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Me(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Er(e.keyFormatVersions,this.keyFormatVersions)&&Tr(e.iv,this.iv)&&Tr(e.keyId,this.keyId)}isSupported(){if(this.method){if(Lr(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Lr(this.method)){let t=this.iv;t||("number"!=typeof e&&(Re.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(e));return new kr(this.method,this.uri,"identity",this.keyFormatVersions,t)}return this}}const Dr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,wr=/#EXT-X-MEDIA:(.*)/g,_r=/^#EXT(?:INF|-X-TARGETDURATION):/m,xr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Cr=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ir{static findGroup(e,t){for(let r=0;r<e.length;r++){const i=e[r];if(i.id===t)return i}}static resolve(e,t){return He.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return _r.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(Dr.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let s;for(;null!=(s=Dr.exec(e));)if(s[1]){var n;const e=new gr(s[1],r),a=s[2],o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Ir.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Nr(e.CODECS,o);const d=e["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},Nr(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),r.levels.push(o)}else if(s[3]){const e=s[3],i=s[4];switch(e){case"SESSION-DATA":{const e=new gr(i,r),t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=Or(i,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Re.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const e=new gr(i,r);r.contentSteering={uri:Ir.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=Fr(i)}}const a=i.length>0&&i.length<r.levels.length;return r.levels=a?i:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let i;const s={},n=r.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(wr.lastIndex=0;null!==(i=wr.exec(e));){const e=new gr(i[1],r),n=e.TYPE;if(n){const r=a[n],i=s[n]||[];s[n]=i;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,u=e.CHARACTERISTICS,c=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?Ir.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=r&&r.length){const e=Ir.findGroup(r,f.groupId)||r[0];Br(f,e,"audioCodec"),Br(f,e,"textCodec")}i.push(f)}}return s}static parseLevelPlaylist(e,t,r,i,s,n){var a;const o={url:t},l=new yr(t),d=l.fragments,h=[];let u,c,f,g,p=null,m=0,v=0,y=0,E=0,T=0,S=null,b=new ze(i,o),L=-1,A=!1,R=null;if(xr.lastIndex=0,l.m3u8=e,l.hasVariableRefs=!1,"#EXTM3U"!==(null==(a=xr.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=xr.exec(e));){A&&(A=!1,b=new ze(i,o),b.playlistOffset=y,b.setStart(y),b.sn=m,b.cc=E,T&&(b.bitrate=T),b.level=r,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),R&&(b.setByteRange(R),R=null)));const e=u[1];if(e){b.duration=parseFloat(e);const t=(" "+u[2]).slice(1);b.title=t||null,b.tagList.push(t?["INF",e,t]:["INF",e])}else if(u[3]){if(re(b.duration)){b.playlistOffset=y,b.setStart(y),f&&Gr(b,f,l),b.sn=m,b.level=r,b.cc=E,d.push(b);const e=(" "+u[3]).slice(1);b.relurl=e,$r(b,S,h),S=b,y+=b.duration,m++,v=0,A=!0}}else{if(u=u[0].match(Cr),!u){Re.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<u.length&&void 0===u[c];c++);const e=(" "+u[c]).slice(1),s=(" "+u[c+1]).slice(1),n=u[c+2]?(" "+u[c+2]).slice(1):null;switch(e){case"BYTERANGE":S?b.setByteRange(s,S):b.setByteRange(s);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=s,b.tagList.push(["PROGRAM-DATE-TIME",s]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&Hr(l,e,u),l.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Hr(l,e,u):d.length>0&&Vr(l,e,u),m=l.startSN=parseInt(s);break;case"SKIP":{l.skippedSegments&&Hr(l,e,u);const t=new gr(s,l),r=t.decimalInteger("SKIPPED-SEGMENTS");if(re(r)){l.skippedSegments+=r;for(let e=r;e--;)d.push(null);m+=r}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Hr(l,e,u),l.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==l.version&&Hr(l,e,u),l.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":l.live||Hr(l,e,u),l.live=!1;break;case"#":(s||n)&&b.tagList.push(n?[s,n]:[s]);break;case"DISCONTINUITY":E++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([e]);break;case"BITRATE":b.tagList.push([e,s]),T=1e3*parseInt(s),re(T)?b.bitrate=T:T=0;break;case"DATERANGE":{const e=new gr(s,l),t=new vr(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Re.warn(`Ignoring invalid DATERANGE tag: "${s}"`),b.tagList.push(["EXT-X-DATERANGE",s]);break}case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Hr(l,e,u):d.length>0&&Vr(l,e,u),l.startCC=E=parseInt(s);break;case"KEY":{const e=Or(s,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=me({},f)),f[e.keyFormat]=e)}else Re.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${s}" (light build)`);break}case"START":l.startTimeOffset=Fr(s);break;case"MAP":{const e=new gr(s,l);if(b.duration){const t=new ze(i,o);Ur(t,e,r,f),p=t,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const t=b.byteRangeEndOffset;if(t){const e=b.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;Ur(b,e,r,f),p=b,A=!0}p.cc=E;break}case"SERVER-CONTROL":g&&Hr(l,e,u),g=new gr(s),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Hr(l,e,u);const t=new gr(s);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,r=v++,i=new gr(s,l),n=new Xe(i,b,o,r,t);e.push(n),b.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new gr(s,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new gr(s,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Re.warn(`line parsed but not handled: ${u}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&($r(b,S,h),b.cc=E,l.fragmentHint=b,f&&Gr(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=d.length,D=d[0],w=d[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&w){l.averagetargetduration=y/k;const e=w.sn;l.endSN="initSegment"!==e?e:0,l.live||(w.endList=!0),L>0&&(!function(e,t){let r=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(d,L),D&&h.unshift(D))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&D&&Pr(h,l),l.endCC=E,l}}function Pr(e,t){let r=e.length;if(!r){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),r++}}const i=e[r-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=r;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const r=Mr(t,d,e,i,s);if(-1!==r){l.tagAnchor=t.fragments[r].ref;break}}}}function Mr(e,t,r,i,s){const n=r[i];if(n){const o=n.programDateTime;if(t>=o||0===i){var a;if(t<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){const s=r[i].sn-e.startSN;if(s<0)return-1;const n=e.fragments;if(n.length>r.length){for(let a=(r[i+1]||n[n.length-1]).sn-e.startSN;a>s;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return s}}}return-1}function Or(e,t,r){var i,s;const n=new gr(e,r),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&Re.error(`Invalid IV: ${n.IV}`);const u=o?Ir.resolve(o,t):"",c=(d||"1").split("/").map(Number).filter(Number.isFinite);return new kr(a,u,h,c,l,n.KEYID)}function Fr(e){const t=new gr(e).decimalFloatingPoint("TIME-OFFSET");return re(t)?t:null}function Nr(e,t){let r=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const i=r.filter(t=>Lt(t,e));i.length&&(t[`${e}Codec`]=i.map(e=>e.split("/")[0]).join(","),r=r.filter(e=>-1===i.indexOf(e)))}),t.unknownCodecs=r}function Br(e,t,r){const i=t[r];i&&(e[r]=i)}function $r(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ur(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Gr(e,t,r){e.levelkeys=t;const{encryptedFragments:i}=r;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||i.push(e)}function Hr(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function Vr(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function Kr(e,t){const r=t.startPTS;if(re(r)){let i,s=0;t.sn>e.sn?(s=r-e.start,i=e):(s=e.start-r,i=t),i.duration!==s&&i.setDuration(s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function qr(e,t,r,i,s,n,a){i-r<=0&&(a.warn("Fragment should have a positive duration",t),i=r+t.duration,n=s+t.duration);let o=r,l=i;const d=t.startPTS,h=t.endPTS;if(re(d)){const u=Math.abs(d-r);e&&u>e.totalduration?a.warn(`media timestamps and playlist times differ by ${u}s for level ${t.level} ${e.url}`):re(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,o=Math.max(r,d),r=Math.min(r,d),s=void 0!==t.startDTS?Math.min(s,t.startDTS):s,l=Math.min(i,h),i=Math.max(i,h),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const u=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=s,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const c=t.sn;if(!e||c<e.startSN||c>e.endSN)return 0;let f;const g=c-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)Kr(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Kr(p[f],p[f+1]);return e.fragmentHint&&Kr(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function jr(e,t,r){if(e===t)return;let i=null;const s=e.fragments;for(let h=s.length-1;h>=0;h--){const e=s[h].initSegment;if(e){i=e;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){const i=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=s;d<=n;d++){const s=l[a+d];let n=o[d];if(i&&!n&&s&&(n=t.fragments[d]=s),s&&n){r(s,n,d,o);const i=s.relurl,a=n.relurl;if(i&&ei(i,a))return void(t.playlistParsingError=Wr(`media sequence mismatch ${n.sn}:`,e,t,s,n));if(s.cc!==n.cc)return void(t.playlistParsingError=Wr(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,e,t,s,n))}}}(e,t,(e,r,s,a)=>{if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){const i=e.cc-r.cc;for(let e=s;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}re(e.startPTS)&&re(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(n=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){const{dateRanges:i,recentlyRemovedDateranges:s}=t,n=me({},e);s&&s.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(e=>{const t=n[e],s=new vr(i[e].attr,t);s.isValid?(n[e]=s,t||(s.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${qt(i[e].attr)}"`)}),n}(e.dateRanges,t,r));const i=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&$r(o[e],o[e-1],i);Pr(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const r=Xr(e,t.startSN-1);t.startCC=null!=(l=null==r?void 0:r.cc)?l:a[0].cc}!function(e,t,r){if(e&&t){let i=0;for(let s=0,n=e.length;s<=n;s++){const n=e[s],a=t[s+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):i--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?qr(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,r):Yr(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function Wr(e,t,r,i,s){return new Error(`${e} ${s.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function Yr(e,t,r=!0){const i=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=i>=0;let a=0;if(n&&i<s.length)a=s[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&r)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}!function(e,t){if(t){const r=e.fragments;for(let i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,a)}function zr(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const i=e.fragments,s=4;if(i.length&&r*s>t){const e=1e3*i[i.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}function Xr(e,t,r){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function Qr(e,t,r){return e?Jr(e.partList,t,r):null}function Jr(e,t,r){if(e)for(let i=e.length;i--;){const s=e[i];if(s.index===r&&s.fragment.sn===t)return s}return null}function Zr(e){e.forEach((e,t)=>{var r;null==(r=e.details)||r.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function ei(e,t){return!(e===t||!t)&&ti(e)!==ti(t)}function ti(e){return e.replace(/\?[^?]*$/,"")}class ri extends Ee{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const i=null==t?void 0:t.renditionReports;if(i){let n=-1;for(let r=0;r<i.length;r++){const a=i[r];let o;try{o=new self.URL(a.URI,t.url).href}catch(s){this.warn(`Could not construct new URL for Rendition Report: ${s}`),o=a.URI||""}if(o===e){n=r;break}o===e.substring(0,o.length)&&(n=r)}if(-1!==n){const e=i[n],s=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=r&&Ut(r);return new Gt(s,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,t,r){const{details:i,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const e=Math.max(o||0,0);i.appliedTimelineOffset=e,i.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(i.live||null!=r&&r.live){const o="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){jr(r,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void r.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:s})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=s.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,u=zr(i,1e3*(i.edge-h));if(i.requestScheduled+u<n?i.requestScheduled=n:i.requestScheduled+=u,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let c,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,s=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,d=s===a;-1!==l?d?(f=a+1,g=e?0:l):(f=s,g=e?l+1:i.maxPartIndex):f=a+1;const h=i.age,u=h+i.ageHeader;let p=Math.min(u-i.partTarget,1.5*i.targetduration);if(p>0){if(u>3*i.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=r&&r.tuneInGoal&&u-i.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${p} with playlist age: ${i.age}`),p=0;else{const e=Math.floor(p/i.targetduration);if(f+=e,void 0!==g){g+=Math.round(p%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}i.tuneInGoal=p}if(c=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g),e||!d)return i.requestScheduled=n,void this.loadingPlaylist(o,c)}else(i.canBlockReload||i.canSkipUntil)&&(c=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g));c&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=s.loading.first+Math.max(u-2*a,u/2)),this.scheduleLoading(o,c,i)}else this.clearTimer()}scheduleLoading(e,t,r){const i=r||e.details;if(!i)return void this.loadingPlaylist(e,t);const s=self.performance.now(),n=i.requestScheduled;if(s>=n)return void this.loadingPlaylist(e,t);const a=n-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,r,i){let s=Ut(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,s=$t.No),new Gt(r,i,s)}checkRetry(e){const t=e.details,r=er(e),i=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(s===lr.RetryRequest||!i.resolved&&s===lr.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=sr(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}var ii="NOT_LOADED",si="APPENDING",ni="PARTIAL",ai="OK";class oi{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let i=r.length;i--;){const t=r[i];if(!t)break;if(t.start<=e&&e<=t.end&&t.loaded)return t}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((null==a?void 0:a.body.type)===t&&(!r||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,i,s){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||s))return void(a.body.type===r&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(a.body),r}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const r=e.frag,i=di(r),s=this.fragments[i];if(!s||s.buffered&&r.gap)return;const n=!r.relurl;Object.keys(t).forEach(i=>{const a=r.elementaryStreams[i];if(!a)return;const o=t[i],l=n||!0===a.partial;s.range[i]=this.getBufferedTimes(r,e.part,l,o)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),li(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=hi(r,t=>t.fragment.sn>=e))}fragBuffered(e,t){const r=di(e);let i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,r,i){const s={time:[],partial:r},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let d=0;d<i.length;d++){const e=i.start(d)-this.bufferPadding,t=i.end(d)+this.bufferPadding;if(l>=e&&o<=t){s.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(n<t&&a>e){const e=Math.max(n,i.start(d)),t=Math.min(a,i.end(d));t>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:t}))}else if(a<=e)break}return s}getPartialFragment(e){let t,r,i,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&li(d)&&(r=d.body.start-a,i=d.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(s=d.body,n=t)))}),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||li(t))}getState(e){const t=di(e),r=this.fragments[t];return r?r.buffered?li(r)?ni:ai:si:ii}isTimeBuffered(e,t,r){let i,s;for(let n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,e>=i&&t<=s)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const r=t.frag,i=t.part?null:t,s=di(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:i,timeRanges:s,type:n}=t;if("initSegment"===r.sn)return;const a=r.type;if(i){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(i)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=di(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let i=r.length;i--;){const s=t[r[i]];if((null==s?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==r||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)})}removeFragment(e){const t=di(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=hi(r,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function li(e){var t,r,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial)}function di(e){return`${e.type}_${e.level}_${e.sn}`}function hi(e,t){return e.filter(e=>{const r=t(e);return r||e.clearElementaryStreamInfo(),r})}class ui{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case Sr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case br:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class ci{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),r=new Uint32Array(4);for(let i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=c[f],p=c[o],m=c[p];let v=257*c[r]^16843008*r;i[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[r]=v<<24|v>>>8,d[r]=v<<16|v>>>16,h[r]=v<<8|v>>>24,u[r]=v,f?(f=o^c[c[c[m^o]]],g^=c[c[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,i=0;for(;i<t.length&&r;)r=t[i]===this.key[i],i++;if(r)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],p=c[2],m=c[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=t[a]:(y=v,a%s===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=u[a/s|0]<<24):s>6&&a%s===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-s]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^p[h[y>>>8&255]]^m[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const i=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(r);let c=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,E,T,S,b,L,A,R,k,D,w,_,x,C;const I=this.networkToHostOrderSwap;for(;t<m.length;){for(k=I(m[t]),D=I(m[t+1]),w=I(m[t+2]),_=I(m[t+3]),b=k^s[0],L=_^s[1],A=w^s[2],R=D^s[3],x=4,C=1;C<i;C++)y=o[b>>>24]^l[L>>16&255]^d[A>>8&255]^h[255&R]^s[x],E=o[L>>>24]^l[A>>16&255]^d[R>>8&255]^h[255&b]^s[x+1],T=o[A>>>24]^l[R>>16&255]^d[b>>8&255]^h[255&L]^s[x+2],S=o[R>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&A]^s[x+3],b=y,L=E,A=T,R=S,x+=4;y=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^s[x],E=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^s[x+1],T=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^s[x+2],S=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^s[x+3],v[t]=I(y^c),v[t+1]=I(S^f),v[t+2]=I(T^g),v[t+3]=I(E^p),c=k,f=D,g=w,p=_,t+=4}return v.buffer}}class fi{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=function(e){switch(e){case Sr:return"AES-CBC";case br:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class gi{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(r){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,i){return this.useSoftware?new Promise((s,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}softwareDecrypt(e,t,r,i){const{currentIV:s,currentResult:n,remainderData:a}=this;if(i!==Sr||16!==t.byteLength)return Re.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=pt(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ci),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,r,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new fi(this.subtle,t,i)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ui(this.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)}).catch(s=>(Re.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,r,i)))}onWebCryptoError(e,t,r,i){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Re.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const pi=Math.pow(2,17);class mi{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new Ei({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(yi(e));e.gap=!1}const l=this.loader=s?new s(i):new n(i),d=vi(e);e.loader=l;const h=nr(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:pi};e.stats=l.stats;const c={onSuccess:(t,r,i,s)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,i,s,n)=>{this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ye({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,r,i)=>{this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,r,i)=>{this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:i,stats:t}))}};t&&(c.onProgress=(r,i,s,n)=>t({frag:e,part:null,payload:s,networkDetails:n})),l.load(d,u,c)})}loadPart(e,t,r){this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(yi(e,t));const l=this.loader=s?new s(i):new n(i),d=vi(e,t);e.loader=l;const h=nr(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:pi};t.stats=l.stats,l.load(d,u,{onSuccess:(i,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:i.data,networkDetails:o};r(d),a(d)},onError:(r,i,s,n)=>{this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ye({url:d.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:n}))},onAbort:(r,i,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,i,s)=>{this.resetLoader(e,l),o(new Ei({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:r}))}})})}updateStatsFromPart(e,t){const r=e.stats,i=t.stats,s=i.total;if(r.loaded+=i.loaded,s){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(r.loaded/s),i),a=(i-n)*Math.round(r.loaded/n);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const n=r.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function vi(e,t=null){const r=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,n=r.byteRangeEndOffset;if(re(s)&&re(n)){var a;let t=s,r=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-s;e%16&&(r=n+(16-e%16)),0!==s&&(i.resetIV=!0,t=s-16)}i.rangeStart=t,i.rangeEnd=r}var o;return i}function yi(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:ne.MEDIA_ERROR,details:ae.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Ei(i)}class Ei extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ti extends Ee{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Si{constructor(e,t,r,i=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=s,this.partial=n}}const bi={length:0,start:()=>0,end:()=>0};class Li{static isBuffered(e,t){if(e){const r=Li.getBuffered(e);for(let e=r.length;e--;)if(t>=r.start(e)&&t<=r.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=Li.getBuffered(e);return Li.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const i=Li.bufferedRanges(e);if(i.length)return Li.bufferedInfo(i,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let i=-1,s=[];if(r)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(i=d);const n=s.length;if(n){const t=s[n-1].end;e[d].start-t<r?e[d].end>t&&(s[n-1].end=e[d].end):s.push(e[d])}else s.push(e[d])}else s=e;let n,a=0,o=t,l=t;for(let d=0;d<s.length;d++){const e=s[d].start,h=s[d].end;if(-1===i&&t>=e&&t<=h&&(i=d),t+r>=e&&t<h)o=e,l=h,a=l-t;else if(t+r<e){n=e;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||bi}catch(t){return Re.log("failed to get media.buffered",t),bi}}}function Ai(e,t){for(let i=0,s=e.length;i<s;i++){var r;if((null==(r=e[i])?void 0:r.cc)===t)return e[i]}return null}function Ri(e,t){const r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function ki(e,t){const r=t.fragments;for(let i=0,s=r.length;i<s;i++)Ri(r[i],e);t.fragmentHint&&Ri(t.fragmentHint,e),t.alignedSliding=!0}function Di(e,t){e&&(!function(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const r=Math.min(t.endCC,e.endCC),i=Ai(t.fragments,r),s=Ai(e.fragments,r);if(!i||!s)return;Re.log(`Aligning playlist at start of dicontinuity sequence ${r}`);ki(i.start-s.start,e)}(t,e),t.alignedSliding||function(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,i=t.fragments;if(!r.length||!i.length)return;let s,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=Ai(i,a),n=Ai(r,a));s&&n||(s=i[Math.floor(i.length/2)],n=Ai(r,s.cc)||r[Math.floor(r.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;ki((l-o)/1e3-(n.start-s.start),e)}(t,e),t.alignedSliding||t.skippedSegments||Yr(e,t,!1))}function wi(e,t,r){_i(e,t,r),e.addEventListener(t,r)}function _i(e,t,r){e.removeEventListener(t,r)}const xi=function(e){let t="";const r=e.length;for(let i=0;i<r;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t},Ci="STOPPED",Ii="IDLE",Pi="KEY_LOADING",Mi="FRAG_LOADING",Oi="FRAG_LOADING_WAITING_RETRY",Fi="PARSING",Ni="PARSED",Bi="ENDED",$i="ERROR",Ui="WAITING_LEVEL";class Gi extends Ti{constructor(e,t,r,i,s){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Ci,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:r,mediaBuffer:i,state:s}=this,n=r?r.currentTime:0,a=Li.bufferInfo(i||r,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${re(n)?n.toFixed(3):n}, state: ${s}, ${o?"out of":"in"} buffer`),this.state===Bi)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,i=t.start-r,s=t.start+t.duration+r;if(o||s<a.start||i>a.end){const e=n>s;(n<i||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(r){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===Ii&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new mi(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new gi(e.config)}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Ci)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Ci}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;const s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=Li.bufferedInfo(s,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return Li.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;wi(r,"seeking",this.onMediaSeeking),wi(r,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Ci&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),_i(i,"seeking",this.onMediaSeeking),_i(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Ci,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,r=e.frag;this.fragContextChanged(r)?(t===Mi||!this.fragCurrent&&t===Fi)&&(this.fragmentTracker.removeFragment(r),this.state=Ii):("payload"in e&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level}`),this.hls.trigger(oe.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Ci&&this.state!==$i&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===si){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===ni&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:r};this.hls.trigger(oe.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:r,payload:i}=e,s=r.decryptdata;if(i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&Lr(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Ar(s.method)).catch(e=>{throw t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(i=>{const s=self.performance.now();return t.trigger(oe.FRAG_DECRYPTED,{frag:r,payload:i,stats:{tstart:n,tdecrypt:s}}),e.payload=i,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==Ci&&this.state!==$i&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Ci&&(this.state=Ii),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var r,i;const s=e.tracks;if(s&&!t.encrypted&&(null!=(r=s.audio)&&r.encrypted||null!=(i=s.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,r=new Error("EME not supported (light build)");return this.warn(r.message),!e||e.mediaKeys?!1:(this.hls.trigger(oe.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_KEYS,fatal:!0,error:r,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?xi(Li.getBuffered(r)):"(detached)"})`),Ye(e)){var i;if(e.type!==ce.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Ii)}const t=null==(i=this.levels)?void 0:i[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Ii}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:i,partsLoaded:s}=e,n=!s||0===s.length||s.some(e=>!e),a=new Si(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,i){var s;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Pi,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(oe.KEY_LOADED,e),this.state===Pi&&(this.state=Ii),e}),this.hls.trigger(oe.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Ye(e)&&(!o||e.sn!==o.sn)){const r=this.shouldLoadParts(t.details,e.end);r!==this.loadingParts&&(this.log(`LL-Part loading ${r?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=r)}if(r=Math.max(e.start,r||0),this.loadingParts&&Ye(e)){const s=n.partList;if(s&&i){r>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,r);if(o>-1){const l=s[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${s.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Mi,d=a?a.then(r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,i)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,i).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}var l;if(Ye(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),re(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Mi;const d=this.config.progressive&&e.type!==ce.SUBTITLE;let h;return h=d&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,i)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,d?i:void 0),a]).then(([e])=>(!d&&i&&i(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,r,i){return new Promise((s,n)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,i).then(i=>{o[t.index]=i;const n=i.part;this.hls.trigger(oe.FRAG_LOADED,i);const a=Qr(r.details,e.sn,t.index+1)||Jr(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});d(a)}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ae.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ne.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(oe.ERROR,t)}else this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Fi)return void(this.fragCurrent||this.state===Ci||this.state===$i||(this.state=Ii));const{frag:r,part:i,level:s}=t,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(r,i,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const s=e.partList[0];if(s.fragment.type===ce.SUBTITLE)return!1;if(t>=s.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:i,sn:s,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Qr(o,s,n):null,d=l?l.fragment:Xr(o,s,r);return d?(r&&r!==d&&(d.stats=r.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,r,i,s){if(this.state!==Fi)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=pt(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:r,chunkMeta:i,offset:d,parent:t.type,data:o};if(this.hls.trigger(oe.BUFFER_APPENDING,h),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Li.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,i=Li.bufferInfo(t,r,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,i.end-n),r+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const i=this.getLoadPosition();if(!re(i))return null;const s=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,s)}getFwdBufferInfoAtPos(e,t,r,i){const s=Li.bufferInfo(e,t,i);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,r);if(n&&(s.nextStart<=n.end||n.gap)){const r=Math.max(Math.min(s.nextStart,n.end)-t,i);return Li.bufferInfo(e,t,r)}}return s}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e,t=ce.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,i=r.length;if(!i)return null;const{config:s}=this,n=r[0].start,a=s.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const r=s.initialLiveManifestSize;if(i<r)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${r})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const r=this.hls.startPosition,i=this.hls.liveSyncPosition,s=o?(-1!==r&&r>=n?r:i)||o.start:e;this.log(`Setting startPosition to ${s} to match start frag at live edge. mainStart: ${r} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=s}}else e<=n&&(o=r[0]);if(!o){const r=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,r,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const e=o.sn-t.startSN;d=this.filterReplacedPrimary(r[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===ai||r===ni&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,i,s){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&r.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==e&&r.len+e.len>=s){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(e,t){return e?(this.config,e):e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let i=-1,s=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&r<o.start)break;const l=o.loaded;l?i=-1:(s||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),i=a),s=l}return i}loadedEndOfParts(e,t){let r;for(let i=e.length;i--;){if(r=e[i],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let i=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!re(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const s=e[i];if(Zt(t,r,s))return s}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];r.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:s}=e;let n;return s&&(i=i.concat(s)),Xt(i,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=r?1:e.start>r?-1:0)),n||null}return null}(e,r.cc,r.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,r){const{config:i}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=r;const{fragmentHint:o}=r,{maxFragLookUpTolerance:l}=i,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let u;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var c;u=Qt(s,n,e,e<this.lastCurrentTime||e>t-l||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const e=u.sn-r.startSN,t=this.fragmentTracker.getState(u);if((t===ai||t===ni&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!h||d[0].fragment.sn>u.sn||!r.live)){if(u.level===s.level){const t=n[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==ai?t:null}}}return u}alignPlaylists(e,t,r){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,n=!t,a=e.alignedSliding&&re(s);if(n||!a&&!s){Di(r,e);const s=e.fragmentStart;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),s}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const i=this.timelineOffset;if(-1===r){const s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&re(n)?(r=t+n,n<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${n} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}getLoadPosition(){var e;const{media:t}=this;let r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ye(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Oi)||(this.state=Ii)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var s;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const n=t.details===ae.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a)return void(this.state=$i);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,u=!!h,c=u&&o===lr.RetryRequest,f=u&&!a.resolved&&l===dr.MoveAllAlternatesMatchingHost,g=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!c&&f&&Ye(i)&&!i.endList&&g&&!rr(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((c||f)&&d<h.maxNumRetry){var p;const r=or(null==(p=t.response)?void 0:p.code),s=sr(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=Oi,a.resolved=!0,r)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${s}ms`)}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);n||o===lr.RemoveAlternatePermanently||(a.resolved=!0)}else this.state=o===lr.SendAlternateToPenaltyBox?Ui:$i;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!or(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ii)}reduceLengthAndFlushBuffer(e){if(this.state===Fi||this.state===Ni){const t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===ce.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ci&&(this.state=Ii)}afterBufferFlushed(e,t,r){if(!e)return;const i=Li.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===Bi&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ci&&(this.state=Ii)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,i){const s=r.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i?0:qr(s,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(oe.LEVEL_PTS_UPDATED,{details:s,level:r,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var n;const t=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===r.fragmentError||t&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ni,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(oe.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ce.MAIN?"level":"track"}fragInfo(e,t=!0,r){var i,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN).toFixed(3)}-${(null!=(s=t&&!r?e.endPTS:(r||e).end)?s:NaN).toFixed(3)}]${r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class Hi{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(i){var r;if(s.onError(i),null===this.queues||null===this.tracks)return;const t=null==(r=this.tracks[e])?void 0:r.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?`SourceBuffer${i.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const Vi=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ki="HlsJsTrackRemovedError";class qi extends Error{constructor(e){super(e),this.name=Ki}}class ji extends Ee{constructor(e,t){var r;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:r}=this;e&&this.log("Media source opened"),t&&r&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(oe.MEDIA_ATTACHED,{media:t,mediaSource:r}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(r=Ce(e.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.BUFFER_RESET,this.onBufferReset,this),e.on(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.BUFFER_EOS,this.onBufferEos,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.FRAG_PARSED,this.onFragParsed,this),e.on(oe.FRAG_CHANGED,this.onFragChanged,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.BUFFER_RESET,this.onBufferReset,this),e.off(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.BUFFER_EOS,this.onBufferEos,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.FRAG_PARSED,this.onFragParsed,this),e.off(oe.FRAG_CHANGED,this.onFragChanged,this),e.off(oe.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?me(r,i.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(r[t]=me({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const i=Ce(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),e)this._objectUrl=r.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{r.removeAttribute("src");const t=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||t&&n instanceof t,Wi(r),function(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,e),r.load()}catch(s){r.src=e}else r.src=e}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(r=e.constructor)?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const r=this.tracks,i=t.tracks,s=i?Object.keys(i):null,n=s?s.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&s&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${qt(r,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${qt(i,(e,t)=>"initSegment"===e?void 0:t)}}`),!function(e,t){const r=Object.keys(e),i=Object.keys(t),s=r.length,n=i.length;return!s||!n||s===n&&!r.some(e=>-1===i.indexOf(e))}(i,r)){t.mediaSource=null,t.tracks=void 0;const s=e.currentTime,n=this.details,a=Math.max(s,(null==n?void 0:n.fragments[0].start)||0);return a-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(r)}") start time: ${a} currentTime: ${s}`),this.onMediaDetaching(oe.MEDIA_DETACHING,{}),this.onMediaAttaching(oe.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,s.forEach(e=>{const t=e,r=i[t];if(r){const e=r.buffer;if(e){const i=this.fragmentTracker,s=r.id;if(i.hasFragments(s)||i.hasParts(s)){const r=Li.getBuffered(e);i.detectEvictedFragments(t,r,s,null,!0)}const n=Yi(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,r)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===s.readyState;try{const t=s.sourceBuffers;for(let r=t.length;r--;)e&&t[r].abort(),s.removeSourceBuffer(t[r]);e&&s.endOfStream()}catch(a){this.warn(`onMediaDetaching: ${a.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),r||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Wi(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(oe.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Yi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Hi(this.tracks)}onBufferCodecs(e,t){var r;const i=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&s.some(e=>!i[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach(e=>{var r,s;const n=t[e],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:u}=n;let c=i[e];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=f&&f.buffer?f:c,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;c||(c=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:h,id:a});const v=It(p,m),y=null==v?void 0:v.replace(Vi,"$1");let E=It(o,l);const T=null==(s=E)?void 0:s.replace(Vi,"$1");E&&v&&y!==T&&("audio"===e.slice(0,5)&&(E=Ct(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(c.pendingCodec||c.codec)&&(c.pendingCodec=E),c.container=d,this.appendChangeType(e,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const i=`${t};codecs=${r}`,s={label:`change-type=${i}`,execute:()=>{const s=this.tracks[e];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),s.codec=r,s.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,i=r+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,ce.MAIN))?void 0:t.gap))return;const s={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>i||null!=t&&t.buffer&&Li.isBuffered(t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,ce.MAIN))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:i,type:s,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,h=l.buffering[s],{sn:u,cc:c}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const m=r.audio;let v=!1;"audio"===s&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=r.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==u){const e=o||a,t=this.blockedAudioAppend;if("audio"!==s||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===s){const r=e.end;if(t){const e=t.frag.start;(r>e||r<this.lastVideoAppendEnd||Li.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=r}}else{const t=e.start+.05*e.duration,r=E.buffered,i=this.currentOp("video");r.length||i?!i&&!Li.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const T=(o||a).start,S={label:`append-${s}`,execute:()=>{var e;h.executeStart=self.performance.now();const t=null==(e=this.tracks[s])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,T,.1,s,u,c):void 0!==d&&re(d)&&this.updateTimestampOffset(t,d,1e-6,s,u,c)),this.appendExecutor(i,s)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach(([e,r])=>{e&&(t[e]=Li.getBuffered(r))}),this.appendErrors[s]=0,"audio"===s||"video"===s?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(oe.BUFFER_APPENDED,{type:s,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const r={type:ne.MEDIA_ERROR,parent:a.type,details:ae.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},i=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=ae.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)r.errorAction=ur(!0);else if(e.name===Ki&&0===this.sourceBufferCount)r.errorAction=ur(!0);else{const e=++this.appendErrors[s];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${i||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||i)&&(r.fatal=!0)}this.hls.trigger(oe.ERROR,r)}};this.log(`queuing "${s}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===ce.MAIN?"level":"track"} ${a.level} cc: ${c}`),this.append(S,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:r,startOffset:i,endOffset:s}=t;r?this.append(this.getFlushOp(r,i,s),r):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,i,s),e)})}onFragParsed(e,t){const{frag:r,part:i}=t,s=[],n=i?i.elementaryStreams:r.elementaryStreams;n[je]?s.push("audiovideo"):(n[Ke]&&s.push("audio"),n[qe]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(()=>{const e=self.performance.now();r.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:r.stats;this.hls.trigger(oe.FRAG_BUFFERED,{frag:r,part:i,stats:t,id:r.type})},s).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([e])=>{if(e){const r=this.tracks[e];t.type&&t.type!==e||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${e} buffer reached EOS`)))}});const i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ae.BUFFER_APPEND_ERROR&&t.frag){var r;const e=null==(r=t.errorAction)?void 0:r.nextAutoLevel;re(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||null===t)return;if(!this.sourceBufferCount)return;const i=e.config,s=r.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(re(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}const o=i.frontBufferFlushThreshold;if(re(o)&&o>0){const e=Math.max(i.maxBufferLength,o),t=Math.max(e,n),r=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,r)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([e,t])=>{if(t){const s=Li.getBuffered(t);if(s.length>0&&r>s.start(0)){var i;this.hls.trigger(oe.BACK_BUFFER_REACHED,{bufferEnd:r});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(oe.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:e})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([t,i])=>{if(i){const s=Li.getBuffered(i),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(r>a||e>=a&&e<=o)return;this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const s=null==(e=this.overrides)?void 0:e.duration;if(s)return re(s)?{duration:s}:null;const n=this.media.duration;return i>(re(r.duration)?r.duration:0)&&i>n||!re(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:r}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==e&&(re(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==r&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${r}.`),i.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${qt(r)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const i=this.tracks[t];e[t]={buffer:r,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(oe.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const e=this.getTrackCodec(o,a),n=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${qt(o)}`);try{const e=r.addSourceBuffer(n),i=Yi(a),s=[a,e];t[i]=s,o.buffer=e}catch(s){var i;return this.error(`error while trying to add sourceBuffer: ${s.message}`),this.shiftAndExecuteNext(a),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[a],void this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:s,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let i=e.codec;r&&("video"===t||"audiovideo"===t)&&At(r,"video")&&(i=function(e,t){const r=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Lt(t[e],"video")||r.push(t[e])}return t&&r.push(t),r.join(",")}(i,r));const s=It(i,e.levelCodec);return s?"audio"===t.slice(0,5)?Ct(s,this.appendSource):s:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const r=t.removedRanges;null!=r&&r.length&&this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${i}`,t),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const s=this.currentOp(e);s&&s.onError(i)}updateTimestampOffset(e,t,r,i,s,n){const a=t-e.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:i,mediaSource:s}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!s||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=re(i.duration)?i.duration:1/0,l=re(s.duration)?s.duration:1/0,d=Math.max(0,t),h=Math.min(r,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new qi(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,i=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(t=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;r&&!r.updating&&this.shiftAndExecuteNext(e)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const i=this.tracks[e];if(!i)return;const s=i.buffer;if(!s)return;const n=r.bind(this,e);i.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(e=>{r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}function Wi(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Yi(e){return"audio"===e?1:0}class zi{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&re(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter((t,r)=>this.isLevelAllowed(t)&&r<=e);return this.clientRect=null,zi.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;const i=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let s=e.length-1;const n=Math.max(t,r);for(let a=0;a<e.length;a+=1){const t=e[a];if((t.width>=n||t.height>=n)&&i(t,e[a+1])){s=a;break}}return s}}class Xi extends Ee{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===lr.SendAlternateToPenaltyBox&&r.flags===dr.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this._pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:r,pathwayId:i,type:n}=t.context;r&&e?s=this.getPathwayForGroupId(r,n,s):i&&(s=i)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==s),t.details!==ae.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${qt(i)} penalized: ${qt(this.penalizedPathways)}`):r.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(e=>{i-r[e]>3e5&&delete r[e]});for(let s=0;s<e.length;s++){const i=e[s];if(i in r)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Zr(t),this.hls.trigger(oe.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===he&&i[s].hasAudioGroup(e)||t===ue&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},i={};e.forEach(e=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===s))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new gr(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(r[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Ji(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Ht({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let r=1;r<e.audioGroups.length;r++)d.addGroupId("audio",`${e.audioGroups[r]}_clone_${s}`);if(e.subtitleGroups)for(let r=1;r<e.subtitleGroups.length;r++)d.addGroupId("text",`${e.subtitleGroups[r]}_clone_${s}`);return d});t.push(...o),Qi(this.audioTracks,r,a,s),Qi(this.subtitleTracks,i,a,s)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new r(t);try{i=new self.URL(e)}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,r,s)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(oe.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,r,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,s)},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const r=null==(t=this.hls)?void 0:t.media;!r||r.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}}function Qi(e,t,r,i){e&&Object.keys(t).forEach(s=>{const n=e.filter(e=>e.groupId===s).map(e=>{const n=me({},e);return n.details=void 0,n.attrs=new gr(n.attrs),n.url=n.attrs.URI=Ji(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=i,n});e.push(...n)})}function Ji(e,t,r,i){const{HOST:s,PARAMS:n,[r]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class Zi{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,s=r-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(oe.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(oe.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var es,ts={exports:{}};var rs=(es||(es=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,s=[];if(0===this._eventsCount)return s;for(i in e=this._events)t.call(e,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,s,n,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,i),!0;case 4:return h.fn.call(h.context,t,i,s),!0;case 5:return h.fn.call(h.context,t,i,s,n),!0;case 6:return h.fn.call(h.context,t,i,s,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,i);break;case 4:h[d].fn.call(h[d].context,t,i,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(e,t,r){return n(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,s){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||s&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==t||s&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(ts)),ts.exports),is=ke(rs);class ss{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:function(e,t){const r=new Uint8Array(t);let i=0;for(let s=0;s<e.length;s++){const t=e[s];r.set(t,i),i+=t.length}return r}(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function ns(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function as(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function os(e,t){let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r}function ls(e,t){const r=t;let i=0;for(;as(e,t);){i+=10;i+=os(e,t+6),ns(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function ds(e,t){return 255===e[t]&&240==(246&e[t+1])}function hs(e,t){return 1&e[t+1]?7:9}function us(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function cs(e,t){return t+1<e.length&&ds(e,t)}function fs(e,t){if(cs(e,t)){const r=hs(e,t);if(t+r>=e.length)return!1;const i=us(e,t);if(i<=r)return!1;const s=t+i;return s===e.length||cs(e,s)}return!1}function gs(e,t,r,i,s){if(!e.samplerate){const n=function(e,t,r,i){const s=t[r+2],n=s>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(s>>6&3),o=t[r+3]>>6&3|(1&s)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const u=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return Re.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:u,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(t,r,i,s);if(!n)return;me(e,n)}}function ps(e){return 9216e4/e}function ms(e,t,r,i,s){const n=i+s*ps(e.samplerate),a=function(e,t){const r=hs(e,t);if(t+r<=e.length){const i=us(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);let o;if(a){const{frameLength:i,headerLength:s}=a,l=s+i,d=Math.max(0,r+l-t.length);d?(o=new Uint8Array(l-s),o.set(t.subarray(r+s,t.length),0)):o=t.subarray(r+s,r+l);const h={unit:o,pts:n};return d||e.samples.push(h),{sample:h,length:l,missing:d}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function vs(e,t){return as(e,t)&&os(e,t+6)+10<=e.length-t}function ys(e,t=0,r=1/0){return function(e,t,r,i){const s=(n=e,n instanceof ArrayBuffer?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,d=(o+t)/a,h=Math.floor(Math.max(0,Math.min(d,l))),u=Math.floor(Math.min(h+Math.max(r,0),l));var c;return new i(s,h,u-h)}(e,t,r,Uint8Array)}function Es(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=e.data.subarray(1).indexOf(0);if(-1===r)return;const i=Ie(ys(e.data,1,r)),s=e.data[2+r],n=e.data.subarray(3+r).indexOf(0);if(-1===n)return;const a=Ie(ys(e.data,3+r,n));let o;var l;return o="--\x3e"===i?Ie(ys(e.data,4+r+n)):(l=e.data.subarray(4+r+n))instanceof ArrayBuffer?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,t.mimeType=i,t.pictureType=s,t.description=a,t.data=o,t}function Ts(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=Ie(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=Ie(e.data.subarray(t),!0);t+=r.length+1;const i=Ie(e.data.subarray(t));return{key:e.type,info:r,data:i}}const t=Ie(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Es(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=Ie(e.data.subarray(t),!0);t+=r.length+1;const i=Ie(e.data.subarray(t));return{key:e.type,info:r,data:i}}const t=Ie(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Ss(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=os(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function bs(e){let t=0;const r=[];for(;as(e,t);){const i=os(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const s=t+i;for(;t+10<s;){const i=Ss(e.subarray(t)),s=Ts(i);s&&r.push(s),t+=i.size+10}ns(e,t)&&(t+=10)}return r}function Ls(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function As(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Rs(e){const t=bs(e);for(let r=0;r<t.length;r++){const e=t[r];if(Ls(e))return As(e)}}let ks=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Ds(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ws{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=pt(this.cachedData,e),this.cachedData=null);let r,i=ls(e,0),s=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?Rs(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&re(o))&&(this.basePTS=_s(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ks.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(n,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,r=s):s=l}else vs(e,s)?(i=ls(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ks.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const t=e.slice(r);this.cachedData?this.cachedData=pt(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:Ds(),id3Track:a,textTrack:Ds()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ds(),id3Track:this._id3Track,textTrack:Ds()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const _s=(e,t,r)=>{if(re(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};let xs=null;const Cs=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Is=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ps=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ms=[0,1,1,4];function Os(e,t,r,i,s){if(r+24>t.length)return;const n=Fs(t,r);if(n&&r+n.frameLength<=t.length){const a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Fs(e,t){const r=e[t+1]>>3&3,i=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Cs[14*(3===r?3-i:3===i?3:4)+s-1],d=Is[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,u=Ps[r][i],c=Ms[i],f=8*u*c,g=Math.floor(u*l/d+a)*c;if(null===xs){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);xs=e?parseInt(e[1]):0}return!!xs&&xs<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Ns(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Bs(e,t){return t+1<e.length&&Ns(e,t)}function $s(e,t){if(t+1<e.length&&Ns(e,t)){const r=4,i=Fs(e,t);let s=r;null!=i&&i.frameLength&&(s=i.frameLength);const n=t+s;return n===e.length||Bs(e,n)}return!1}const Us=/\/emsg[-/]ID3/i;function Gs(e,t){return re(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Hs{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new gi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Sr)}decryptAacSample(e,t,r){const i=e[t].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then(s=>{const n=new Uint8Array(s);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)r.set(e.subarray(s,s+16),i);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)e.set(r.subarray(i,i+16),s);return e}decryptAvcSample(e,t,r,i,s){const n=Tt(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,i)}).catch(i)}decryptAvcSamples(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();const s=e[t].units;for(;!(r>=s.length);r++){const n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,r,i,n),this.decrypter.isSync())))return}}}}class Vs{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,i=r.length;if(!i)return void t.dropped++;{const t=r[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,r){const i=t.byteLength;let s=e.naluState||0;const n=s,a=[];let o,l,d,h=0,u=-1,c=0;for(-1===s&&(u=0,c=this.getNALuType(t,0),s=0,h=1);h<i;)if(o=t[h++],s)if(1!==s)if(o)if(1===o){if(l=h-s-1,u>=0){const e={data:t.subarray(u,l),type:c};a.push(e)}else{const r=this.getLastNalUnit(e.samples);r&&(n&&h<=4-n&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-n)),l>0&&(r.data=pt(r.data,t.subarray(0,l)),r.state=0))}h<i?(d=this.getNALuType(t,h),u=h,c=d,s=0):s=-1}else s=0;else s=3;else s=o?0:2;else s=o?0:1;if(u>=0&&s>=0){const e={data:t.subarray(u,i),type:c,state:s};a.push(e)}if(0===a.length){const r=this.getLastNalUnit(e.samples);r&&(r.data=pt(r.data,t))}return e.naluState=s,a}}class Ks{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");i.set(e.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&Re.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class qs extends Vs{parsePES(e,t,r,i){const s=this.parseNALu(e,r.data,i);let n,a=this.VideoSample,o=!1;r.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(i=>{var s,l;switch(i.type){case 1:{let t=!1;n=!0;const s=i.data;if(o&&s.length>4){const e=this.readSliceType(s);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Et(i.data,1,r.pts,t.samples);break;case 7:{var h,u;n=!0,o=!0;const t=i.data,r=this.readSPS(t);if(!e.sps||e.width!==r.width||e.height!==r.height||(null==(h=e.pixelRatio)?void 0:h[0])!==r.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==r.pixelRatio[1]){e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let s="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),s+=t}e.codec=s}break}case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Ks(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r,i=8,s=8;for(let n=0;n<e;n++)0!==s&&(r=t.readEG(),s=(i+r+256)%256),i=0===s?i:s}readSPS(e){const t=new Ks(e);let r,i,s,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),h=t.readBits.bind(t),u=t.readUEG.bind(t),c=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=u();if(3===e&&f(1),p(),p(),f(1),c())for(i=3!==e?8:12,s=0;s<i;s++)c()&&m(s<6?16:64,t)}p();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),r=u(),s=0;s<r;s++)g();p(),f(1);const E=u(),T=u(),S=h(1);0===S&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());let b=[1,1];if(c()&&c()){switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}const js=188;class Ws{constructor(e,t,r,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.videoParser=null}static probe(e,t){const r=Ws.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(e){const t=e.length;let r=Math.min(940,t-js)+1,i=0;for(;i<r;){let s=!1,n=-1,a=0;for(let o=i;o<t;o+=js){if(71!==e[o]||t-o!==js&&71!==e[o+js]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+18612,e.length-js)+1)),s||(s=0===Ys(e,o)),s&&a>1&&(0===n&&a>2||o+js>r))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:et[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ws.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ws.createTrack("audio",i),this._id3Track=Ws.createTrack("id3"),this._txtTrack=Ws.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,i=!1){let s;r||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=pt(this.remainderData,e)).length,this.remainderData=null),y<js&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,Ws.syncOffset(e));y-=(y-E)%js,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let b=E;b<y;b+=js)if(71===e[b]){const t=!!(64&e[b+1]),i=Ys(e,b);let y;if((48&e[b+3])>>4>1){if(y=b+5+e[b+4],y===b+js)continue}else y=b+4;switch(i){case d:t&&(h&&(s=Zs(h,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,s,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(y,b+js)),h.size+=b+js-y);break;case u:if(t){if(f&&(s=Zs(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(y,b+js)),f.size+=b+js-y);break;case c:t&&(g&&(s=Zs(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(y,b+js)),g.size+=b+js-y);break;case 0:t&&(y+=e[y]+1),v=this._pmtId=zs(e,y);break;case v:{t&&(y+=e[y]+1);const i=Xs(e,y,this.typeSupported,r,this.observer,this.logger);d=i.videoPid,d>0&&(n.pid=d,n.segmentCodec=i.segmentVideoCodec),u=i.audioPid,u>0&&(a.pid=u,a.segmentCodec=i.segmentAudioCodec),c=i.id3Pid,c>0&&(o.pid=c),null===p||m||(this.logger.warn(`MPEG-TS PMT found at ${b} after unknown PID '${p}'. Backtracking to sync byte @${E} to parse all TS packets.`),p=null,b=E-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=i}}else T++;T>0&&Qs(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:i,textTrack:s}=e,n=r.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=Zs(n,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,s,l,!0),r.pesData=null)):r.pesData=n,a&&(l=Zs(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Zs(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,r){const i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new Hs(this.observer,this.config,t);return this.decrypt(i,s)}readyVideoParser(e){null===this.videoParser&&"avc"===e&&(this.videoParser=new qs)}decrypt(e,t){return new Promise(r=>{const{audioTrack:i,videoTrack:s}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{r(e)}):r(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{r(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let r=0;const i=this.aacOverFlow;let s,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,s=i.sample.unit.byteLength;if(-1===t)o=pt(i.sample.unit,o);else{const n=s-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),r=i.missing}}for(s=r,n=o.length;s<n-1&&!cs(o,s);s++);if(s!==r){let e;const t=s<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",Qs(this.observer,new Error(e),t,this.logger),!t)return}if(gs(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=ps(e.samplerate);a=i.sample.pts+t}}let l,d=0;for(;s<n;){if(l=ms(e,o,s,a,d),s+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;s<n-1&&!cs(o,s);s++);}}parseMPEGPES(e,t){const r=t.data,i=r.length;let s=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(Bs(r,n)){const t=Os(e,r,n,a,s);if(!t)break;n+=t.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=me({},t,{type:this._videoTrack?ks.emsg:ks.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function Ys(e,t){return((31&e[t+1])<<8)+e[t+2]}function zs(e,t){return(31&e[t+10])<<8|e[t+11]}function Xs(e,t,r,i,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Ys(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Js("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){Js("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Js("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&l>0){let r=t+5,i=l;for(;i>2;){if(106===e[r])n.warn("AC-3 in M2TS support not included in build");const t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return Qs(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return Qs(s,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}t+=l+5}return a}function Qs(e,t,r,i){i.warn(`parsing error: ${t.message}`),e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Js(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Zs(e,t){let r,i,s,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=pt(l[0],l[1]),l.splice(1,1);r=l[0];if(1===(r[0]<<16)+(r[1]<<8)+r[2]){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;const d=r[7];192&d&&(n=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&d?(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=r[8];let h=s+9;if(e.size<=h)return null;e.size-=h;const u=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){r=l[e];let t=r.byteLength;if(h){if(h>t){h-=t;continue}r=r.subarray(h),t-=h,h=0}u.set(r,o),o+=t}return i&&(i-=s+3),{data:u,pts:n,dts:a,len:i}}return null}class en{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const tn=Math.pow(2,32)-1;class rn{static init(){let e;for(e in rn.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},rn.types)rn.types.hasOwnProperty(e)&&(rn.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);rn.HDLR_TYPES={video:t,audio:r};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);rn.STTS=rn.STSC=rn.STCO=s,rn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rn.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);rn.FTYP=rn.box(rn.types.ftyp,n,o,n,a),rn.DINF=rn.box(rn.types.dinf,rn.box(rn.types.dref,i))}static box(e,...t){let r=8,i=t.length;const s=i;for(;i--;)r+=t[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),i=0,r=8;i<s;i++)n.set(t[i],r),r+=t[i].byteLength;return n}static hdlr(e){return rn.box(rn.types.hdlr,rn.HDLR_TYPES[e])}static mdat(e){return rn.box(rn.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(tn+1)),i=Math.floor(t%(tn+1));return rn.box(rn.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return rn.box(rn.types.mdia,rn.mdhd(e.timescale||0,e.duration||0),rn.hdlr(e.type),rn.minf(e))}static mfhd(e){return rn.box(rn.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rn.box(rn.types.minf,rn.box(rn.types.smhd,rn.SMHD),rn.DINF,rn.stbl(e)):rn.box(rn.types.minf,rn.box(rn.types.vmhd,rn.VMHD),rn.DINF,rn.stbl(e))}static moof(e,t,r){return rn.box(rn.types.moof,rn.mfhd(e),rn.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=rn.trak(e[t]);return rn.box.apply(null,[rn.types.moov,rn.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(rn.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=rn.trex(e[t]);return rn.box.apply(null,[rn.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(tn+1)),i=Math.floor(t%(tn+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return rn.box(rn.types.mvhd,s)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let i,s;for(i=0;i<t.length;i++)s=t[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return rn.box(rn.types.sdtp,r)}static stbl(e){return rn.box(rn.types.stbl,rn.stsd(e),rn.box(rn.types.stts,rn.STTS),rn.box(rn.types.stsc,rn.STSC),rn.box(rn.types.stsz,rn.STSZ),rn.box(rn.types.stco,rn.STCO))}static avc1(e){let t,r,i,s=[],n=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],i=r.byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],i=r.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));const a=rn.box(rn.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return rn.box(rn.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,rn.box(rn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rn.box(rn.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return rn.box(rn.types.mp4a,rn.audioStsd(e),rn.box(rn.types.esds,rn.esds(e)))}static mp3(e){return rn.box(rn.types[".mp3"],rn.audioStsd(e))}static ac3(e){return rn.box(rn.types["ac-3"],rn.audioStsd(e),rn.box(rn.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return rn.box(rn.types.stsd,rn.STSD,rn.mp4a(e));if("mp3"===t&&"mp3"===e.codec)return rn.box(rn.types.stsd,rn.STSD,rn.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return rn.box(rn.types.stsd,rn.STSD,rn.avc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,r=(e.duration||0)*(e.timescale||0),i=e.width||0,s=e.height||0,n=Math.floor(r/(tn+1)),a=Math.floor(r%(tn+1));return rn.box(rn.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const r=rn.sdtp(e),i=e.id,s=Math.floor(t/(tn+1)),n=Math.floor(t%(tn+1));return rn.box(rn.types.traf,rn.box(rn.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),rn.box(rn.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),rn.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,rn.box(rn.types.trak,rn.tkhd(e),rn.mdia(e))}static trex(e){const t=e.id;return rn.box(rn.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],i=r.length,s=12+16*i,n=new Uint8Array(s);let a,o,l,d,h,u;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=r[a],l=o.duration,d=o.size,h=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return rn.box(rn.types.trun,n)}static initSegment(e){rn.types||rn.init();const t=rn.moov(e);return pt(rn.FTYP,t)}static hvc1(e){return new Uint8Array}}rn.types=void 0,rn.HDLR_TYPES=void 0,rn.STTS=void 0,rn.STSC=void 0,rn.STCO=void 0,rn.STSZ=void 0,rn.VMHD=void 0,rn.SMHD=void 0,rn.STSD=void 0,rn.FTYP=void 0,rn.DINF=void 0;function sn(e,t=!1){return function(e,t,r=1,i=!1){const s=e*t*r;return i?Math.round(s):s}(e,1e3,1/9e4,t)}function nn(e){const{baseTime:t,timescale:r,trackId:i}=e;return`${t/r} (${t}/${r}) trackId: ${i}`}let an,on=null,ln=null;function dn(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class hn extends Ee{constructor(e,t,r,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===on){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);on=e?parseInt(e[1]):0}if(null===ln){const e=navigator.userAgent.match(/Safari\/(\d+)/i);ln=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?nn(t):t} > ${e?nn(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const r=e[0].pts,i=e.reduce((e,i)=>{let s=i.pts,n=s-e;return n<-4294967296&&(t=!0,s=un(s,r),n=s-e),n>0?e:s},r);return t&&this.debug("PTS rollover detected"),i}remux(e,t,r,i,s,n,a,o){let l,d,h,u,c,f,g=s,p=s;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=a&&y>0||y>1;if((!m||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,b,L,A;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(b=e.pixelRatio)?void 0:b[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(A=e.pixelRatio)?void 0:A[1]))||!e&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,s,n));const r=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const r=this.getVideoStartPts(t.samples),i=(un(e.samples[0].pts,r)-r)/t.inputTimeScale;g+=Math.max(0,i),p+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,s,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,v||T||o===ce.AUDIO?p:void 0),T){const i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,p,r,i)}}else T&&(l=this.remuxVideo(t,p,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=cn(r,s,this._initPTS,this._initDTS)),i.samples.length&&(u=fn(i,s,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:u,id3:c}}computeInitPts(e,t,r,i){const s=Math.round(r*t);let n=un(e,s);if(n<s+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-n)/t} ${i}`);n<s+t;)n+=8589934592;return n-s}generateIS(e,t,r,i){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,u,c=!l||i,f="audio/mp4",g=-1;if(c&&(d=h=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):rn.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(g=e.id,u=e.inputTimeScale,l&&u===l.timescale?c=!1:d=h=this.computeInitPts(s[0].pts,u,r,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:rn.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(g=t.id,u=t.inputTimeScale,l&&u===l.timescale)c=!1;else{const e=this.getVideoStartPts(n),t=un(n[0].dts,e),i=this.computeInitPts(t,u,r,"video"),s=this.computeInitPts(e,u,r,"video");h=Math.min(h,i),d=Math.min(d,s)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${r} ${d/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${d/u} (${d}/${u}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:u,trackId:g},this._initDTS={baseTime:h,timescale:u,trackId:g}):d=u=void 0,{tracks:o,initPTS:d,timescale:u,trackId:g}}remuxVideo(e,t,r,i){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*s/l.timescale;let h,u,c=this.nextVideoTs,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===c){const e=d+t*s,i=n[0].pts-un(n[0].dts,n[0].pts);on&&null!==c&&Math.abs(e-i-(c+d))<15e3?r=!0:c=e-i-d}const y=c+d;for(let O=0;O<o;O++){const e=n[O];e.pts=un(e.pts,y),e.dts=un(e.dts,y),e.dts<n[O>0?O-1:O].dts&&(v=!0)}v&&n.sort(function(e,t){const r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),h=n[0].dts,u=n[n.length-1].dts;const E=u-h,T=E?Math.round(E/(o-1)):g||e.inputTimeScale/30;if(r){const r=h-y,i=r>T,s=r<-1;if((i||s)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${sn(r,!0)} ms (${r}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${sn(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!s||y>=n[0].pts||on)){h=y;const e=n[0].pts-r;if(i)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let i=0;i<n.length&&!(n[i].dts>e&&t);i++){const e=n[i].pts;if(n[i].dts-=r,n[i].pts-=r,i<n.length-1){const r=n[i+1].pts;t=r<=n[i].pts==r<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${sn(e,!0)}/${sn(h,!0)}, delta: ${sn(r,!0)} ms`)}}h=Math.max(0,h);let S=0,b=0,L=h;for(let O=0;O<o;O++){const e=n[O],t=e.units,r=t.length;let i=0;for(let s=0;s<r;s++)i+=t[s].data.length;b+=i,S+=r,e.length=i,e.dts<L?(e.dts=L,L+=T/4|0||1):L=e.dts,p=Math.min(e.pts,p),m=Math.max(e.pts,m)}u=n[o-1].dts;const A=b+4*S+8;let R;try{R=new Uint8Array(A)}catch(M){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:A,reason:`fail allocating video mdat ${A}`})}const k=new DataView(R.buffer);k.setUint32(0,A),R.set(rn.types.mdat,4);let D=!1,w=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let O=0;O<o;O++){const e=n[O],t=e.units;let r,l=0;for(let i=0,s=t.length;i<s;i++){const e=t[i],r=e.data,s=e.data.byteLength;k.setUint32(f,s),f+=4,R.set(r,f),f+=s,l+=4+s}if(O<o-1)g=n[O+1].dts-e.dts,r=n[O+1].pts-e.pts;else{const t=this.config,a=O>0?e.dts-n[O-1].dts:T;if(r=O>0?e.pts-n[O-1].pts:T,t.stretchShortVideoTrack&&null!==this.nextAudioTs){const r=Math.floor(t.maxBufferHole*s),n=(i?p+i*s:this.nextAudioTs+d)-e.pts;n>r?(g=n-a,g<0?g=a:D=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const h=Math.round(e.pts-e.dts);w=Math.min(w,g),x=Math.max(x,g),_=Math.min(_,r),C=Math.max(C,r),a.push(dn(e.key,g,l,h))}if(a.length)if(on){if(on<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ln&&C-_<x-w&&T/x<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=h;for(let t=0,r=a.length;t<r;t++){const i=e+a[t].duration,s=e+a[t].cts;if(t<r-1){const e=i+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:T;a[t].cts=0,e=i}}g=D||!g?T:g;const I=u+g;this.nextVideoTs=c=I-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const P={data1:rn.moof(e.sequenceNumber++,h,me(e,{samples:a})),data2:R,startPTS:(p-d)/s,endPTS:(m+g-d)/s,startDTS:(h-d)/s,endDTS:c/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,P}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,r,i,s){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,h="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],c=void 0!==s;let f=e.samples,g=h?0:8,p=this.nextAudioTs||-1;const m=d.baseTime*n/d.timescale,v=m+t*n;if(this.isAudioContiguous=r=r||f.length&&p>0&&(i&&Math.abs(v-(p+m))<9e3||Math.abs(un(f[0].pts,v)-(p+m))<20*l),f.forEach(function(e){e.pts=un(e.pts,v)}),!r||p<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${n})`),!f.length)return;p=0===s?0:i&&!c?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,i=p+m;r<f.length;r++){const s=f[r],a=s.pts,o=a-i,d=Math.abs(1e3*o/n);if(o<=-t*l&&c)0===r&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=p=a-m,i=a);else if(o>=t*l&&d<1e4&&c){let t=Math.round(o/l);for(i=a-t*l;i<0&&t&&l;)t--,i+=l;0===r&&(this.nextAudioTs=p=i-m),this.warn(`Injecting ${t} audio frames @ ${((i-m)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=en.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=s.unit.subarray()),f.splice(r,0,{unit:t,pts:i}),i+=l,r++}}s.pts=i,i+=l}}let y,E=null,T=null,S=0,b=f.length;for(;b--;)S+=f[b].unit.byteLength;for(let x=0,C=f.length;x<C;x++){const t=f[x],i=t.unit;let s=t.pts;if(null!==T){u[x-1].duration=Math.round((s-T)/a)}else{if(r&&"aac"===e.segmentCodec&&(s=p+m),E=s,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(_){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:_,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!h){new DataView(y.buffer).setUint32(0,S),y.set(rn.types.mdat,4)}}y.set(i,g);const n=i.byteLength;g+=n,u.push(dn(!0,o,n,0)),T=s}const L=u.length;if(!L)return;const A=u[u.length-1];p=T-m,this.nextAudioTs=p+a*A.duration;const R=h?new Uint8Array(0):rn.moof(e.sequenceNumber++,E/a,me({},e,{samples:u}));e.samples=[];const k=(E-m)/n,D=this.nextAudioTs/n,w={data1:R,data2:y,startPTS:k,endPTS:D,startDTS:k,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,w}}function un(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function cn(e,t,r,i){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let o=0;o<s;o++){const s=e.samples[o];s.pts=un(s.pts-r.baseTime*n/r.timescale,t*n)/n,s.dts=un(s.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function fn(e,t,r){const i=e.samples.length;if(!i)return;const s=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=un(i.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function gn(e,t,r=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function pn(e,t,r){const i=e.codec;if(i&&i.length>4)return i;if(t===Ke){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Ct(i,!1)}return r.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return r.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{an=self.performance.now.bind(self.performance)}catch(ma){an=Date.now}const mn=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,i){const s=this.videoTrack=Ds("video",1),n=this.audioTrack=Ds("audio",1),a=this.txtTrack=Ds("text",1);if(this.id3Track=Ds("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=lt(e);if(o.video){const{id:e,timescale:t,codec:r,supplemental:i}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=r,s.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;n.id=e,n.timescale=t,n.codec=r}a.id=et.text,s.sampleDuration=0,s.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let r=0;r<t;){const i=it(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)}demux(e,t){this.timeOffset=t;let r=e;const i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=pt(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=at(e,["moof"]);if(r.length<2)return t.remainder=e,t;const i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=r;const n=this.extractID3Track(i,t);return s.samples=mt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return r.samples=mt(e,t),{videoTrack:t,audioTrack:Ds(),id3Track:i,textTrack:Ds()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const i=at(e.samples,["emsg"]);i&&i.forEach(e=>{const i=function(e){const t=e[0];let r="",i="",s=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==tt(e.subarray(d,d+1));)r+=tt(e.subarray(d,d+1)),d+=1;for(r+=tt(e.subarray(d,d+1)),d+=1;"\0"!==tt(e.subarray(d,d+1));)i+=tt(e.subarray(d,d+1)),d+=1;i+=tt(e.subarray(d,d+1)),d+=1,s=it(e,12),n=it(e,16),o=it(e,20),l=it(e,24),d=28}else if(1===t){d+=4,s=it(e,d),d+=4;const t=it(e,d);d+=4;const n=it(e,d);for(d+=4,a=2**32*t+n,ie(a)||(a=Number.MAX_SAFE_INTEGER,Re.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=it(e,d),d+=4,l=it(e,d),d+=4;"\0"!==tt(e.subarray(d,d+1));)r+=tt(e.subarray(d,d+1)),d+=1;for(r+=tt(e.subarray(d,d+1)),d+=1;"\0"!==tt(e.subarray(d,d+1));)i+=tt(e.subarray(d,d+1)),d+=1;i+=tt(e.subarray(d,d+1)),d+=1}return{schemeIdUri:r,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(Us.test(i.schemeIdUri)){const e=Gs(i,t);let s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=i.payload;r.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:ks.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Gs(i,t);r.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:ks.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends Ee{constructor(e,t,r,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:n}=this.initData=lt(e);if(t)!function(e,t){if(!e||!t)return;const r=t.keyId;r&&t.isCommonEncryption&&gt(e,(e,t)=>{const i=e.subarray(8,24);i.some(e=>0!==e)||(Re.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Pe(i)} -> ${Pe(r)}`),e.set(r,8))})}(e,t);else{const e=s||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}s&&(r=pn(s,Ke,this)),n&&(i=pn(n,qe,this));const a={};s&&n?a.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:s?a.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,r,i,s,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};re(d)||(d=this.lastEndTime=s||0);const u=t.samples;if(!u.length)return h;const c={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,r){const i={},s=at(e,["moof","traf"]);for(let n=0;n<s.length;n++){const e=s[n],a=at(e,["tfhd"])[0],o=it(a,4),l=t[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=i[o],h=at(e,["tfdt"])[0];if(h){const e=h[0];let t=it(h,4);1===e&&(t===Je?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=Je+1,t+=it(h,8))),re(t)&&(!re(d.start)||t<d.start)&&(d.start=t)}const u=l.default,c=it(a,0)|(null==u?void 0:u.flags);let f=(null==u?void 0:u.duration)||0;8&c&&(f=it(a,2&c?12:8));const g=at(e,["trun"]);let p=d.start||0,m=0,v=f;for(let t=0;t<g.length;t++){const e=g[t],r=it(e,4),i=d.sampleCount;d.sampleCount+=r;const s=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],h=8&e[2];let u=8,c=r;for(s&&(u+=4),n&&r&&(1&e[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=i),u+=4,a?(v=it(e,u),u+=4):v=f,o&&(u+=4),h&&(u+=4),p+=v,m+=v,c--);c--;)a?(v=it(e,u),u+=4):v=f,o&&(u+=4),l&&(1&e[u+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(c+1),d.keyFrameStart=p),u+=4),h&&(u+=4),p+=v,m+=v;!m&&f&&(m+=f*r)}d.duration+=m}if(!Object.keys(i).some(e=>i[e].duration)){let t=1/0,r=0;const s=at(e,["sidx"]);for(let e=0;e<s.length;e++){const i=ot(s[e]);if(null!=i&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);const e=i.references.reduce((e,t)=>e+t.info.duration||0,0);r=Math.max(r,e+i.earliestPresentationTime/i.timescale)}}r&&re(r)&&Object.keys(i).forEach(e=>{i[e].duration||(i[e].duration=r*i[e].timescale-i[e].start)})}return i}(u,f,this),p=f.audio?g[f.audio.id]:null,m=f.video?g[f.video.id]:null,v=gn(m,1/0),y=gn(p,1/0),E=gn(m,0,!0),T=gn(p,0,!0);let S=s,b=0;const L=p&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),A=L?p:m;if(A){const e=A.timescale,t=A.start-s*e,r=L?f.audio.id:f.video.id;S=A.start/e,b=L?T-y:E-v,!n&&l||!function(e,t,r,i){if(null===e)return!0;const s=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-r)>s}(l,S,s,b)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${S-s} (${t}/${e}) trackId: ${r}`),l=null,c.initPTS=t,c.timescale=e,c.trackId=r)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);l?(c.initPTS=l.baseTime,c.timescale=l.timescale,c.trackId=l.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=S,c.timescale=1,c.trackId=-1),this.initPTS=l={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});const R=S-l.baseTime/l.timescale,k=R+b;b>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const D=!!f.audio,w=!!f.video;let _="";D&&(_+="audio"),w&&(_+="video");const x={data1:u,startPTS:R,startDTS:R,endPTS:k,endDTS:k,type:_,hasAudio:D,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=D&&!w?x:void 0,h.video=w?x:void 0;const C=null==m?void 0:m.sampleCount;if(C){const e=m.keyFrameIndex,t=-1!==e;x.nb=C,x.dropped=0===e||this.isVideoContiguous?0:t?e:C,x.independent=t,x.firstKeyFrame=e,t&&m.keyFrameStart&&(x.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return h.initSegment=c,h.id3=cn(r,s,l,l),i.samples.length&&(h.text=fn(i,s,l)),h}}},{demux:Ws,remux:hn},{demux:class extends ws{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,i){super.resetInitSegment(e,t,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=ls(e,0);let i=(null==r?void 0:r.length)||0;if($s(e,i))return!1;for(let s=e.length;i<s;i++)if(fs(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&ds(e,t)&&us(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){gs(e,this.observer,t,r,e.manifestCodec);const i=ms(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:hn},{demux:class extends ws{resetInitSegment(e,t,r,i){super.resetInitSegment(e,t,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ls(e,0);let r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Rs(t)&&((e,t)=>{let r=0,i=5;t+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],t+=1,i-=o}return r})(e,r)<=16)return!1;for(let i=e.length;r<i;r++)if($s(e,r))return Re.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Ns(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return Os(e,t,r,this.basePTS,this.frameIndex)}},remux:hn}];class vn{constructor(e,t,r,i,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.id=s,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,i){const s=r.transmuxing;s.executeStart=an();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:c,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,E=function(e,t){let r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(n,t);if(E&&Lr(E.method)){const e=this.getDecrypter(),t=Ar(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,t).then(e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t}),this.decryptionPromise;{let i=e.softwareDecrypt(n,E.key.buffer,E.iv.buffer,t);if(r.part>-1){const t=e.flush();i=t?t.buffer:t}if(!i)return s.executeEnd=an(),yn(r);n=new Uint8Array(i)}}const T=this.needsProbing(d,h);if(T){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=an(),yn(r)}(d||h||f||T)&&this.resetInitSegment(y,g,p,v,t),(d||f||T)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(n,E,c,u,r);this.asyncResult=En(S);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=an(),S}flush(e){const t=e.transmuxing;t.executeStart=an();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(r){const t=r.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=an();const r=[yn(e)];return this.asyncResult?Promise.resolve(r):r}const d=o.flush(a);return En(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,r){const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===ce.MAIN?"level":"track"} ${r.level}`);const d=this.remuxer.remux(i,s,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=an()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,i,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,i,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,s):this.transmuxUnencrypted(e,r,i,s),n}transmuxUnencrypted(e,t,r,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,r,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,r,i,s){return this.demuxer.demuxSampleAes(e,t,r).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:i}=this;let s;for(let h=0,u=mn.length;h<u;h++){var n;if(null!=(n=mn[h].demux)&&n.probe(e,this.logger)){s=mn[h];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.remux,d=s.demux;o&&o instanceof l||(this.remuxer=new l(r,t,i,this.logger)),a&&a instanceof d||(this.demuxer=new d(r,t,i,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new gi(this.config)),e}}const yn=e=>({remuxResult:{},chunkMeta:e});function En(e){return"then"in e&&e.then instanceof Function}class Tn{constructor(e,t,r,i,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class Sn{constructor(e,t,r,i,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n}}function bn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const Ln=/(\d+)-(\d+)\/(\d+)/;class An{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Rn,this.controller=new self.AbortController,this.stats=new Ve}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(me({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=o&&re(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout);(En(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var s;this.response=this.loader=r;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(a-i.loading.start)),!r.ok){const{status:e,statusText:t}=r;throw new kn(t||"fetch, bad network response",e,r)}i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Ln.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(re(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(r.headers)||i.total;const o=null==(s=this.callbacks)?void 0:s.onProgress;return o&&re(t.highWaterMark)?this.loadProgressively(r,i,e,t.highWaterMark,o):n?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(r=>{var s,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=r[a];l&&(i.loaded=i.total=l);const d={url:o.url,data:r,code:o.status},h=null==(s=this.callbacks)?void 0:s.onProgress;h&&!re(t.highWaterMark)&&h(i,e,r,o),null==(n=this.callbacks)||n.onSuccess(d,i,e,o)}).catch(t=>{var r;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const s=t&&t.code||0,n=t?t.message:null;null==(r=this.callbacks)||r.onError({code:s,text:n},e,t?t.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,i=0,s){const n=new ss,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&s(t,r,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(t,r,n.flush().buffer,e)):s(t,r,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function Rn(e,t){return new self.Request(e.url,t)}class kn extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const Dn=/^age:\s*[\d.]+\s*$/im;class wn{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ve,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(this.loader===r&&!this.stats.aborted)return s(r,t.url)}).catch(e=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",t.url,!0),s(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(e=>{var s;null==(s=this.callbacks)||s.onError({code:r.status,text:e.message},t,r,i)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=r.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&re(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const s=null!=l?l:t.response;if(null!=s){var n,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===t.responseType?s.byteLength:s.length;r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(r,e,s,t);const d={url:t.responseURL,data:s,code:i};return void(null==(a=this.callbacks)||a.onSuccess(d,r,e,t))}}const d=s.loadPolicy.errorRetry;var o;if(ar(d,r.retry,!1,{url:e.url,data:void 0,code:i}))this.retry(d);else Re.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,r)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(ar(e,this.stats.retry,!0))this.retry(e);else{var t;Re.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=sr(e,r.retry),r.retry++,Re.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Dn.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const _n={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},xn=ye(ye({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:wn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:zt,bufferController:ji,capLevelController:zi,errorController:hr,fpsController:Zi,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:_n},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:_n},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:xe,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:Xi,interstitialsController:void 0});function Cn(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Cn):Object.keys(e).reduce((t,r)=>(t[r]=Cn(e[r]),t),{}):e}class In extends Ti{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const r=this.media=t.media;wi(r,"playing",this.onMediaPlaying),wi(r,"waiting",this.onMediaWaiting),wi(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(_i(r,"playing",this.onMediaPlaying),_i(r,"waiting",this.onMediaWaiting),_i(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,i;const s=null==(r=this.hls)?void 0:r.config;if(!s)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1})));if(!Li.getBuffered(n).length)return void(this.nudgeRetry=0);const h=Li.bufferInfo(n,e,0),u=h.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){const t=Pn(this.hls.inFlightFragments,e),r=h.len>2,i=!u||t||u-e>2&&!c.getPartialFragment(e);if(r||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(h.len>0)&&!u)return;const t=Math.max(u,h.start||0)-e,r=!(null==f||!f.live)?2*f.targetduration:2,i=On(e,c);if(t>0&&(t<=r||i))return void(n.paused||this._trySkipBufferHole(i))}const g=s.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(oe.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const T=Li.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(T,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(oe.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){const r=Li.bufferedInfo(Li.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const r=Li.timeRangesToArray(i),s=Li.bufferedInfo(r,t,0).bufferedIndex;if(s>-1&&s<r.length-1){const t=Li.bufferedInfo(r,e,0).bufferedIndex,i=r[s].end,n=r[s+1].start;if((-1===t||t>s)&&n-i<1&&e-i<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(r.message),this.media.currentTime+=1e-6;let s=On(e,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);const a=Li.bufferInfo(this.media,e,0);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:s,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,r){var i,s;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(s=this.hls)?void 0:s.latestLevelDetails,d=On(r,n);if(d||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=e.buffered,u=this.adjacentTraversal(e,r);(h&&h.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||u))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,i=e.nextStart;if(r&&i){const e=r.getFragAtPos(t,ce.MAIN),s=r.getFragAtPos(i,ce.MAIN);if(e&&s)return s.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:i,stalled:s}=this;if(!i&&null!==s&&r&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${qt(e)})`);this.warn(i.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:i}=this,s=null==(t=this.hls)?void 0:t.config;if(!i||!r||!s)return 0;const n=i.currentTime,a=Li.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=s.maxBufferHole,d=a.len>0&&a.len<1&&i.readyState<3,h=o-n;if(h>0&&(t||d)){if(h>s.maxBufferHole){let t=!1;if(0===n){const e=r.getAppendedFrag(0,ce.MAIN);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Pn(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=On(i,r);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,i.currentTime=t,null==e||!e.gap){const r=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),i={type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?i.part=e:i.frag=e),this.hls.trigger(oe.ERROR,i)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:i}=this,s=null==t?void 0:t.config;if(!r||!s)return 0;const n=r.currentTime;if(this.nudgeRetry++,i<s.nudgeMaxRetry){const a=n+(i+1)*s.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),r.currentTime=a,t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const r=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(r.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Pn(e,t){const r=Mn(e.main);if(r&&r.start<=t)return r;const i=Mn(e.audio);return i&&i.start<=t?i:null}function Mn(e){if(!e)return null;switch(e.state){case Ii:case Ci:case Bi:case $i:return null}return e.frag}function On(e,t){return t.getAppendedFrag(e,ce.MAIN)||t.getPartialFragment(e)}function Fn(e,t){let r;try{r=new Event("addtrack")}catch(ma){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Nn(e,t,r,i){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,r){const i=[],s=function(e,t){if(t<=e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let i,s=0,n=r;for(;s<=n;)if(i=Math.floor((n+s)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&s<r))return i;s=i+1}return e[s].startTime-t<t-e[n].startTime?s:n}(e,t);if(s>-1)for(let n=s,a=e.length;n<a;n++){const s=e[n];if(s.startTime>=t&&s.endTime<=r)i.push(s);else if(s.startTime>r)return i}return i}(e.cues,t,r);for(let t=0;t<s.length;t++)i&&!i(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}function Bn(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function $n(e,t,r,i,s){let n=new e(t,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new e(t,r,qt(s?ye({type:s},i):i))}return n}const Un=(()=>{const e=Bn();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Gn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(oe.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&function(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Fn(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:i}=this.hls.config;if(!r&&!i)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Bn();if(n)for(let a=0;a<s.length;a++){const e=s[a].type;if(e===ks.emsg&&!r||!i)continue;const t=bs(s[a].data),o=s[a].pts;let l=o+s[a].duration;l>Un&&(l=Un);l-o<=0&&(l=o+.25);for(let r=0;r<t.length;r++){const i=t[r];if(!Ls(i)){this.updateId3CueEnds(o,e);const t=$n(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(e,t){var r;const i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===Un&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:i}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let e;e="audio"===i?e=>e.type===ks.audioId3&&o:"video"===i?e=>e.type===ks.emsg&&a:e=>e.type===ks.audioId3&&o||e.type===ks.emsg&&a,Nn(s,t,r,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:i,enableDateRangeMetadataCues:s,interstitialsController:n}=this.hls.config;if(!s)return;const a=Bn();if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let h=this.dateRangeCuesAppended;var u;if(o&&t)if(null!=(u=o.cues)&&u.length){const e=Object.keys(h).filter(e=>!d.includes(e));for(let t=e.length;t--;){var c;const r=e[t],i=null==(c=h[r])?void 0:c.cues;delete h[r],i&&Object.keys(i).forEach(e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(r){}}})}}else h=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==d.length&&re(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<d.length;e++){const t=d[e],r=l[t],i=r.startTime,s=h[t],n=(null==s?void 0:s.cues)||{};let o=(null==s?void 0:s.durationKnown)||!1,u=Un;const{duration:c,endDate:f}=r;if(f&&null!==c)u=i+c,o=!0;else if(r.endOnNext&&!o){const e=d.reduce((e,t)=>{if(t!==r.id){const i=l[t];if(i.class===r.class&&i.startDate>r.startDate&&(!e||r.startDate<e.startDate))return i}return e},null);e&&(u=e.startTime,o=!0)}const g=Object.keys(r.attr);for(let e=0;e<g.length;e++){const l=g[e];if(!pr(l))continue;const d=n[l];if(d)!o||null!=s&&s.durationKnown?Math.abs(d.startTime-i)>.01&&(d.startTime=i,d.endTime=u):d.endTime=u;else if(a){let e=r.attr[l];mr(l)&&(e=Me(e));const s=$n(a,i,u,{key:l,data:e},ks.dateRange);s&&(s.id=t,this.id3Track.addCue(s),n[l]=s)}}h[t]={cues:n,dateRange:r,durationKnown:o}}}}}class Hn{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=r-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,r));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*i);const d=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const r=this.levelDetails;if(null===r)return null;const i=r.edge,s=e-t-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===ae.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Vn extends ri{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,i=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:d,videoCodec:h}=e;d&&(e.audioCodec=d=Ct(d,r)||void 0),h&&(h=e.videoCodec=function(e){const t=e.split(",");for(let r=0;r<t.length;r++){const e=t[r].split(".");e.length>2&&"avc1"===e[0]&&(t[r]=`avc1.${parseInt(e[1]).toString(16)}${("000"+parseInt(e[2]).toString(16)).slice(-4)}`)}return t.join(",")}(h));const{width:u,height:c,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!u||!c)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:p,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=t,S=`${`${y||"."}-`}${e.bitrate}-${E}-${m}-${p}-${T}-${v}`;if(s[S])if(s[S].uri===e.url||e.attrs["PATHWAY-ID"])s[S].addGroupId("audio",t.AUDIO),s[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const r=this.createLevel(e);s[S]=r,i.push(r)}else{const t=this.createLevel(e);s[S]=t,n[S]=1,i.push(t)}}),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new Ht(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(e.message),t.supportedResult=_e.getUnsupportedResult(e,[])}return t}isAudioSupported(e){return At(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return At(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,i,s){var n;let a=[],o=[],l=e;const d=(null==(n=t.stats)?void 0:n.parsing)||{};if((r||i)&&s&&(l=l.filter(({videoCodec:e,videoRange:t,width:r,height:i})=>{return(!!e||!(!r||!i))&&(!!(s=t)&&Bt.indexOf(s)>-1);var s})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r=`one or more CODECS in variant not supported: ${qt(t.levels.map(e=>e.attrs.CODECS).filter((e,t,r)=>r.indexOf(e)===t))}`,this.warn(r),e+=` (${r})`);const i=new Error(e);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(d.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),Kn(a)),t.subtitles&&(o=t.subtitles,Kn(o));const h=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Bt.indexOf(e.videoRange)-Bt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const r=Dt(e.videoCodec),i=Dt(t.videoCodec);if(r!==i)return i-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const r=wt(e.codecSet),i=wt(t.codecSet);if(r!==i)return i-r}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let u=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let v=0;v<h.length;v++)if(h[v].pathwayId===l[0].pathwayId){u=h[v];break}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===u){var c;this._firstLevel=v;const e=u.bitrate,t=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${e}`),void 0===(null==(c=this.hls.userConfig)?void 0:c.abrEwmaDefaultEstimate)){const r=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);r>t&&t===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=r)}break}const f=s&&!i,g=this.hls.config,p=!(!g.audioStreamController||!g.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:i,altAudio:p&&!f&&a.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(oe.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,r===e&&i&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(oe.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=r}}onError(e,t){!t.fatal&&t.context&&t.context.type===de&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===ce.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const r=this._levels[t.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var r;const{level:i,details:s}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(r=t.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(oe.LEVEL_LOADING,{url:r,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const r=this._levels.filter((t,r)=>r!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Zr(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=r.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(oe.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(oe.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Kn(e){const t={};e.forEach(e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}const qn="1.6.15",jn={};let Wn=0;class Yn{constructor(e,t,r,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Wn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,r=this.hls;if(r&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,r.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===oe.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new is,this.observer.on(oe.FRAG_DECRYPTED,n),this.observer.on(oe.ERROR,n);const a=Ot(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const r=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(r.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=jn[e];if(t)return t.clientCount++,t;const r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return jn[e]=i,i}(s.workerPath)):(r.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=jn[qn];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return jn[qn]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:qt(s)})}catch(ma){r.warn(`Error setting up "${t}" Web Worker, fallback to inline`,ma),this.terminateWorker(),this.error=null,this.transmuxer=new vn(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new vn(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Wn++;const t=this.hls.config,r=Ot(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:qt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=jn[e||qn];if(t&&1===t.clientCount--){const{worker:r,objectURL:i}=t;delete jn[e||qn],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,r,i,s,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{instanceNo:c,transmuxer:f}=this,g=n?n.start:s.start,p=s.decryptdata,m=this.frag,v=!(m&&s.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),L=self.performance.now();(y||E||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),!n||!T&&b||(n.stats.parsing.start=L);const A=!(m&&(null==(h=s.initSegment)?void 0:h.url)===(null==(u=m.initSegment)?void 0:u.url)),R=new Sn(v,b,o,y,g,A);if(!b||v||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===ce.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${A}`);const e=new Tn(r,i,t,a,d);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,p,l,R);En(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const t=r.flush(e);En(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function zn(){return self.SourceBuffer||self.WebKitSourceBuffer}function Xn(){if(!Ce())return!1;const e=zn();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function Qn(){if(!Xn())return!1;const e=Ce();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(kt(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(kt(t,"audio"))))}class Jn extends Gi{constructor(e,t,r){super(e,t,r,"stream-controller",ce.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!re(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const r=this.getFwdBufferInfoAtPos(e,t,ce.MAIN,0);null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${r?r.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Ii,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Ci}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ui:{const{levels:e,level:t}=this,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=Ii;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ii;break}break}case Oi:this.checkRetryDate()}this.state===Ii&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==r||!r[s])return;const n=r[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(oe.BUFFER_EOS,e),void(this.state=Bi)}if(!this.buffering)return;e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===Ui||this.waitForLive(n))return this.level=s,this.state=Ui,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&Ye(c)&&this.fragmentTracker.getState(c)!==ai){var f;const e=(null!=(f=this.backtrackFragment)?f:c).sn-l.startSN,t=l.fragments[e-1];t&&c.cc===t.cc&&(c=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const e=this.audioOnly&&!this.altAudio?Ke:qe,t=(e===qe?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,ce.MAIN)}c=this.getNextFragmentLoopLoading(c,l,a,ce.MAIN,h)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(e,t,r){const i=this.fragmentTracker.getState(e);i===ii||i===ni?Ye(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ce.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;r=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else r=0;const n=this.getBufferedFrag(t.currentTime+r);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,i=Math.max(n.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Pi:case Mi:case Oi:case Fi:case Ni:this.state=Ii}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;wi(r,"playing",this.onMediaPlaying),wi(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(_i(r,"playing",this.onMediaPlaying),_i(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(oe.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,i=!1;for(let s=0;s<t.levels.length;s++){const e=t.levels[s].audioCodec;e&&(r=r||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&i&&!function(){var e;const t=zn();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Ii)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Ui)}onLevelLoaded(e,t){var r;const{levels:i,startFragRequested:s}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==Mi&&this.state!==Oi||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(r=l.details)&&r.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,h),this.hls.trigger(oe.LEVEL_UPDATED,{details:a,level:n}),this.state===Ui){if(this.waitForCdnTuneIn(a))return;this.state=Ii}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=Li.bufferInfo(r,i,0);if(null==(l=e.buffered)||!l.length)return void(r.currentTime=i);if(e.start<=s)return void(r.currentTime=i);const{nextStart:t}=Li.bufferedInfo(e.buffered,s,0);t&&(r.currentTime=t)}else r.currentTime=i}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:i,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=n[r.level];if(!a)return void this.warn(`Level ${r.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(t=r.initSegment)?void 0:t.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Yn(this.hls,ce.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new Si(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),m=this.initPTS[r.cc];c.push(s,h,u,l,r,i,o.totalduration,d,p,m)}onAudioTrackSwitching(e,t){const r=this.hls,i=0!==this.altAudio;if(Yt(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(oe.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(oe.AUDIO_TRACK_SWITCHED,t)}),void r.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(oe.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=Yt(t.url,this.hls);if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let i,s,n=!1;for(const a in r){const e=r[a];if("main"===e.id){if(s=a,i=e,"video"===a){const e=r[a];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:i}=t,s=r.type===ce.MAIN;if(s){if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ni&&(this.state=Ii));const e=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),Ye(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}const n=this.media;n&&(!this._hasEnoughToStart&&Li.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal)this.state=$i;else switch(t.details){case ae.FRAG_GAP:case ae.FRAG_PARSING_ERROR:case ae.FRAG_DECRYPT_ERROR:case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ce.MAIN,t);break;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:case ae.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ui||(null==(r=t.context)?void 0:r.type)!==de||(this.state=Ii);break;case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ae.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ae.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Ii,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ke||!this.altAudio){const e=(t===qe?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,ce.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const i=this.timelineOffset;i&&r&&(r+=i);const s=this.getLevelDetails(),n=Li.getBuffered(e),a=n.length?n.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),r+=o,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${a}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:r}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=Ii,this.startFragRequested=!1,this.bitrateTest=!1;const s=i.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(oe.FRAG_LOADED,e),i.bitrateTest=!1}).catch(t=>{this.state!==Ci&&this.state!==$i&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:i,chunkMeta:s}=e,n=this.getCurrentContext(s);if(!n)return void this.resetWhenMissingContext(s);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:u,initSegment:c}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Fi,c){const e=c.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(c,a))return;this._bufferInitSegment(l,e,i,s),r.trigger(oe.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=c.initPTS,n=c.timescale,o=this.initPTS[a.cc];if(re(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=c.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e},r.trigger(oe.INIT_PTS_FOUND,{frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,r=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===s.id&&!r&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!r)return void this.backtrack(a);r&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,s,t||r)}else{if(!t&&!r)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:r,endDTS:i}=g;o&&(o.elementaryStreams[Ke]={startPTS:e,endPTS:t,startDTS:r,endDTS:i}),a.setElementaryStreamInfo(Ke,e,t,r,i),this.bufferFragmentData(g,a,o,s)}if(f&&null!=u&&u.samples.length){const e={id:t,frag:a,details:f,samples:u.samples};r.trigger(oe.FRAG_PARSING_METADATA,e)}if(f&&h){const e={id:t,frag:a,details:f,samples:h.samples};r.trigger(oe.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Ye(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,i){if(this.state!==Fi)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:s,video:n,audiovideo:a}=t;if(s){const r=e.audioCodec;let i=It(s.codec,r);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),r&&r!==i&&this.log(`Swapping manifest audio codec "${r}" for "${i}"`),s.levelCodec=i,s.id=ce.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${i||""}/${r||""}/${s.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=ce.MAIN;const r=n.codec;if(4===(null==r?void 0:r.length))switch(r){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${r}]${n.codec!==r?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(oe.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(oe.BUFFER_APPENDING,{type:e,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ce.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Ii}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(Li.isBuffered(e,r)?t=this.getAppendedFrag(r):Li.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r||(this.fragPlaying=t,this.hls.trigger(oe.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(oe.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return re(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(re(t)){const e=this.getLevelDetails(),r=this.currentFrag||(e?Qt(null,e.fragments,t):null);if(r){const e=r.programDateTime;if(null!==e){const i=e+1e3*(t-r.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Zn extends Ee{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[r].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ae.KEY_LOAD_ERROR,r,i,s){return new Ei({type:ne.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:i})}loadClear(e,t,r){return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,i;const s=e.decryptdata;if(!s){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,r))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=ea(s);let o=this.keyIdToKeyInfo[a];if(null!=(r=o)&&r.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:r}=t;return s.key=r.decryptdata.key,{frag:e,keyInfo:r}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+Pe(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){const r=function(e){const t=[];return gt(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(r.length){let t=r[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${Pe(t)}`),kr.setKeyIdForUri(e.decryptdata.uri,t)):(t=kr.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Pe(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!Ye(t))return Promise.resolve(r);const s=this.emeController.loadKey(r);return(e.keyLoadPromise=s.then(t=>(e.mediaKeySessionContext=t,r))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,i=new(0,r.loader)(r);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,r,i)=>{const{frag:a,keyInfo:o}=r,l=ea(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,ae.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,r,i,s)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ae.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,ye({url:a.url,data:void 0},e)))},onTimeout:(e,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ae.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ae.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,d)})}resetLoader(e){const{frag:t,keyInfo:r,url:i}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null);const n=ea(r.decryptdata)||i;delete this.keyIdToKeyInfo[n],s&&s.destroy()}}function ea(e){return e.uri}function ta(e){const{type:t}=e;switch(t){case he:return ce.AUDIO;case ue:return ce.SUBTITLE;default:return ce.MAIN}}function ra(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class ia{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,i=t.loader,s=new(r||i)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:le,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:i,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:de,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=t;this.load({id:r,groupId:i,level:null,responseType:"text",type:he,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=t;this.load({id:r,groupId:i,level:null,responseType:"text",type:ue,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[de];if(r){const e=r.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(r.abort(),delete this.loaders[de])}}load(e){var t;const r=this.hls.config;let i,s=this.getInternalLoader(e);if(s){const t=this.hls.logger,r=s.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives))return void(r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===le?r.manifestLoadPolicy.default:me({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),re(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===de&&null!==e.level?t=this.hls.levels[e.level].details:e.type===he&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ue&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);i=me({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,r,i)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=e.data;t.parsing.start=performance.now(),Ir.isMediaPlaylist(n)||r.type!==le?this.handleTrackOrLevelPlaylist(e,t,r,i||null,s):this.handleMasterPlaylist(e,t,r,i)},onError:(e,t,r,i)=>{this.handleNetworkError(t,r,!1,e,i)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,i){const s=this.hls,n=e.data,a=ra(e,r),o=Ir.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f}=o;this.variableList=f,d.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:i,videoCodec:s}=e;for(let n=t.length;n--;){const a=t[n];At(a,"audio",r)?(e.audioCodec=i=i?`${i},${a}`:a,bt.audio[i.substring(0,4)]=2,t.splice(n,1)):At(a,"video",r)&&(e.videoCodec=s=s?`${s},${a}`:a,bt.video[s.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=Ir.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new gr({}),bitrate:0,url:""}))}s.trigger(oe.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,i,s){const n=this.hls,{id:a,level:o,type:l}=r,d=ra(e,r),h=re(o)?o:re(a)?a:0,u=ta(r),c=Ir.parseLevelPlaylist(e.data,d,h,u,0,this.variableList);if(l===le){const e={attrs:new gr({}),bitrate:0,details:c,name:"",url:d};c.requestScheduled=t.loading.start+zr(c,0),n.trigger(oe.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,e,t,r,i,s)}handleManifestParsingError(e,t,r,i,s){this.hls.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.MANIFEST_PARSING_ERROR,fatal:t.type===le,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:s})}handleNetworkError(e,t,r=!1,i,s){let n=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===de?n+=`: ${e.level} id: ${e.id}`:e.type!==he&&e.type!==ue||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ae.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case le:o=r?ae.MANIFEST_LOAD_TIMEOUT:ae.MANIFEST_LOAD_ERROR,l=!0;break;case de:o=r?ae.LEVEL_LOAD_TIMEOUT:ae.LEVEL_LOAD_ERROR,l=!1;break;case he:o=r?ae.AUDIO_TRACK_LOAD_TIMEOUT:ae.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ue:o=r?ae.SUBTITLE_TRACK_LOAD_TIMEOUT:ae.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const h={type:ne.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:s};if(i){const r=(null==t?void 0:t.url)||e.url;h.response=ye({url:r,data:void 0},i)}this.hls.trigger(oe.ERROR,h)}handlePlaylistLoaded(e,t,r,i,s,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:u,deliveryDirectives:c}=i,f=ra(t,i),g=ta(i);let p="number"==typeof i.level&&g===ce.MAIN?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:i,level:p,parent:g,networkDetails:s,stats:r});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:p,parent:g,networkDetails:s,stats:r})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case le:case de:if(p)if(d){if(d!==a.levels[p]){const e=a.levels.indexOf(d);e>-1&&(p=e)}}else p=0;a.trigger(oe.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:p||0,id:h||0,stats:r,networkDetails:s,deliveryDirectives:c,withoutMultiVariant:o===le});break;case he:a.trigger(oe.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:c});break;case ue:a.trigger(oe.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:c})}}}const sa={supported:!1,smooth:!1,powerEfficient:!1},na={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function aa(e,t,r,i={}){const s=e.videoCodec;if(!s&&!e.audioCodec||!r)return Promise.resolve(na);const n=[],a=function(e){var t;const r=null==(t=e.videoCodec)?void 0:t.split(","),i=la(e),s=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(e=>{const t={contentType:kt(Mt(e),"video"),width:s,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,r){var i;const s=null==(i=e.audioCodec)?void 0:i.split(","),n=la(e);if(s&&e.audioGroups)return e.audioGroups.reduce((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");s.forEach(t=>{const s={contentType:kt(t,"audio"),bitrate:r?oa(t,n):n};i&&(s.channels=""+i),e.push(s)})}return e},e):e},[]);return[]}(e,t,o>0),d=l.length;for(let h=o||1*d||1;h--;){const e={type:"media-source"};if(o&&(e.video=a[h%o]),d){e.audio=l[h%d];const t=e.audio.bitrate;e.video&&t&&(e.video.bitrate-=t)}n.push(e)}if(s){const e=navigator.userAgent;if(s.split(",").some(e=>vt(e))&&St())return Promise.resolve(function(e,t){return{supported:!1,configurations:t,decodingInfoResults:[sa],error:e}}(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:r,video:i}=e;if(i){t+=`${Ft(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(r){t+=`${i?"_":""}${Ft(r.contentType)}_c${r.channels}`}return t}(e);return i[t]||(i[t]=r.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function oa(e,t){if(t<=1)return 1;let r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function la(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}class da{static get version(){return qn}static isMSESupported(){return Xn()}static isSupported(){return Qn()}static getMediaSource(){return Ce()}static get Events(){return oe}static get MetadataSchema(){return ks}static get ErrorTypes(){return ne}static get ErrorDetails(){return ae}static get DefaultConfig(){return da.defaultConfig?da.defaultConfig:xn}static set DefaultConfig(e){da.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new is,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,r){const i=be();if("object"==typeof console&&!0===e||"object"==typeof e){const n=["debug","log","info","warn","error"];n.forEach(t=>{i[t]=Le(t,e,r)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(s){return be()}n.forEach(t=>{Ae[t]=Le(t,e)})}else me(Ae,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=function(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Cn(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];s.forEach(r=>{const s=`${e}Loading${r}`,l=t[s];if(void 0!==l&&a){o.push(s);const e=i[n].default;switch(t[n]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${qt(t[n])}`)}),ye(ye({},i),t)}(da.DefaultConfig,e,t);this.userConfig=e,r.progressive&&function(e,t){const r=e.loader;r!==An&&r!==wn?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):bn()&&(e.loader=An,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,t);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=r,l=new a(this),d=this.abrController=new i(this),h=new oi(this),u=r.interstitialsController,c=u?this.interstitialsController=new u(this,da):null,f=this.bufferController=new s(this,h),g=this.capLevelController=new n(this),p=new o(this),m=new ia(this),v=r.contentSteeringController,y=v?new v(this):null,E=this.levelController=new Vn(this,y),T=new Gn(this),S=new Zn(this.config,this.logger),b=this.streamController=new Jn(this,h,S),L=this.gapController=new In(this,h);g.setStreamController(b),p.setStreamController(b);const A=[m,E,b];c&&A.splice(1,0,c),y&&A.splice(1,0,y),this.networkControllers=A;const R=[d,f,L,g,p,T,h];this.audioTrackController=this.createController(r.audioTrackController,A);const k=r.audioStreamController;k&&A.push(this.audioStreamController=new k(this,h,S)),this.subtitleTrackController=this.createController(r.subtitleTrackController,A);const D=r.subtitleStreamController;D&&A.push(this.subtititleStreamController=new D(this,h,S)),this.createController(r.timelineController,R),S.emeController=this.emeController=this.createController(r.emeController,R),this.cmcdController=this.createController(r.cmcdController,R),this.latencyController=this.createController(Hn,R),this.coreComponents=R,A.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(oe.ERROR,w,l),this.on(oe.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,i){this._emitter.off(e,t,r,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const t=e===oe.ERROR;this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:t,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(oe.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,i=t?e:{media:r};this._media=r,this.trigger(oe.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(oe.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(oe.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,i=this._url=He.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(oe.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ce.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ce.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ce.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)})}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Nt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,r)for(let s=i;s--;){const t=e[s].attrs["HDCP-LEVEL"];if(t&&t<=r)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return aa(e,Wt(t),navigator.mediaCapabilities)}}da.defaultConfig=void 0;var ha=_e.KeySystemFormats,ua=_e.KeySystems,ca=_e.SubtitleStreamController,fa=_e.TimelineController,ga=_e.requestMediaKeySystemAccess;const pa=Object.freeze(Object.defineProperty({__proto__:null,AbrController:zt,AttrList:gr,AudioStreamController:xe,AudioTrackController:xe,BasePlaylistController:ri,BaseSegment:We,BaseStreamController:Gi,BufferController:ji,CMCDController:xe,CapLevelController:zi,ChunkMetadata:Si,ContentSteeringController:Xi,Cues:xe,DateRange:vr,EMEController:xe,ErrorActionFlags:dr,ErrorController:hr,ErrorDetails:ae,ErrorTypes:ne,Events:oe,FPSController:Zi,FetchLoader:An,Fragment:ze,Hls:da,HlsSkip:$t,HlsUrlParameters:Gt,KeySystemFormats:ha,KeySystems:ua,Level:Ht,LevelDetails:yr,LevelKey:kr,LoadStats:Ve,M3U8Parser:Ir,MetadataSchema:ks,NetworkErrorAction:lr,Part:Xe,PlaylistLevelType:ce,SubtitleStreamController:ca,SubtitleTrackController:xe,TimelineController:fa,XhrLoader:wn,default:da,fetchSupported:bn,getMediaSource:Ce,isMSESupported:Xn,isSupported:Qn,requestMediaKeySystemAccess:ga},Symbol.toStringTag,{value:"Module"}));e.applyContainerStyles=z,e.aspectRatioToPercent=Y,e.create=ee,e.createEmbedPlayer=X,e.default=te,e.initAll=Z,e.initElement=Q,e.parseDataAttributes=W,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
2
+ //# sourceMappingURL=embed.light.umd.cjs.map