@scarlett-player/embed 0.2.0 → 0.4.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.
@@ -1,2 +0,0 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ScarlettAudio={})}(this,function(t){"use strict";class e{constructor(t){this.subscribers=new Set,this.value=t}get(){return this.value}set(t){Object.is(this.value,t)||(this.value=t,this.notify())}update(t){this.set(t(this.value))}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}notify(){this.subscribers.forEach(t=>{try{t()}catch(e){console.error("[Scarlett Player] Error in signal subscriber:",e)}})}destroy(){this.subscribers.clear()}getSubscriberCount(){return this.subscribers.size}}function r(t){return new e(t)}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(t){this.signals=new Map,this.changeSubscribers=new Set,this.initializeSignals(t)}initializeSignals(t){const e={...i,...t};for(const[i,s]of Object.entries(e)){const t=i,e=r(s);e.subscribe(()=>{this.notifyChangeSubscribers(t)}),this.signals.set(t,e)}}get(t){const e=this.signals.get(t);if(!e)throw new Error(`[StateManager] Unknown state key: ${t}`);return e}getValue(t){return this.get(t).get()}set(t,e){this.get(t).set(e)}update(t){for(const[e,r]of Object.entries(t)){const t=e;this.signals.has(t)&&this.set(t,r)}}subscribeToKey(t,e){const r=this.get(t);return r.subscribe(()=>{e(r.get())})}subscribe(t){return this.changeSubscribers.add(t),()=>this.changeSubscribers.delete(t)}notifyChangeSubscribers(t){const e=this.get(t).get(),r={key:t,value:e,previousValue:e};this.changeSubscribers.forEach(t=>{try{t(r)}catch(e){console.error("[StateManager] Error in change subscriber:",e)}})}reset(){this.update(i)}resetKey(t){const e=i[t];this.set(t,e)}snapshot(){const t={};for(const[e,r]of this.signals)t[e]=r.get();return Object.freeze(t)}getSubscriberCount(t){return this.signals.get(t)?.getSubscriberCount()??0}destroy(){this.signals.forEach(t=>t.destroy()),this.signals.clear(),this.changeSubscribers.clear()}}const n={maxListeners:100,async:!1,interceptors:!0};class a{constructor(t){this.listeners=new Map,this.onceListeners=new Map,this.interceptors=new Map,this.options={...n,...t}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set);return this.listeners.get(t).add(e),this.checkMaxListeners(t),()=>this.off(t,e)}once(t,e){this.onceListeners.has(t)||this.onceListeners.set(t,new Set);const r=this.onceListeners.get(t);return r.add(e),this.listeners.has(t)||this.listeners.set(t,new Set),()=>{r.delete(e)}}off(t,e){const r=this.listeners.get(t);r&&(r.delete(e),0===r.size&&this.listeners.delete(t));const i=this.onceListeners.get(t);i&&(i.delete(e),0===i.size&&this.onceListeners.delete(t))}emit(t,e){const r=this.runInterceptors(t,e);if(null===r)return;const i=this.listeners.get(t);if(i){Array.from(i).forEach(t=>{this.safeCallHandler(t,r)})}const s=this.onceListeners.get(t);if(s){Array.from(s).forEach(t=>{this.safeCallHandler(t,r)}),this.onceListeners.delete(t)}}async emitAsync(t,e){const r=await this.runInterceptorsAsync(t,e);if(null===r)return;const i=this.listeners.get(t);if(i){const t=Array.from(i).map(t=>this.safeCallHandlerAsync(t,r));await Promise.all(t)}const s=this.onceListeners.get(t);if(s){const e=Array.from(s).map(t=>this.safeCallHandlerAsync(t,r));await Promise.all(e),this.onceListeners.delete(t)}}intercept(t,e){if(!this.options.interceptors)return()=>{};this.interceptors.has(t)||this.interceptors.set(t,new Set);const r=this.interceptors.get(t);return r.add(e),()=>{r.delete(e),0===r.size&&this.interceptors.delete(t)}}removeAllListeners(t){t?(this.listeners.delete(t),this.onceListeners.delete(t)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(t){return(this.listeners.get(t)?.size??0)+(this.onceListeners.get(t)?.size??0)}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.interceptors.clear()}runInterceptors(t,e){if(!this.options.interceptors)return e;const r=this.interceptors.get(t);if(!r||0===r.size)return e;let i=e;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(t,e){if(!this.options.interceptors)return e;const r=this.interceptors.get(t);if(!r||0===r.size)return e;let i=e;for(const n of r)try{const t=n(i);if(i=t instanceof Promise?await t:t,null===i)return null}catch(s){console.error("[EventBus] Error in interceptor:",s)}return i}safeCallHandler(t,e){try{t(e)}catch(r){console.error("[EventBus] Error in event handler:",r)}}async safeCallHandlerAsync(t,e){try{const r=t(e);r instanceof Promise&&await r}catch(r){console.error("[EventBus] Error in event handler:",r)}}checkMaxListeners(t){const e=this.listenerCount(t);e>this.options.maxListeners&&console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) exceeded for event: ${t}. Current count: ${e}. This may indicate a memory leak.`)}}const o=["debug","info","warn","error"],l=t=>{const e=`${t.scope?`[${t.scope}]`:"[ScarlettPlayer]"} ${t.message}`,r=t.metadata??"";switch(t.level){case"debug":console.debug(e,r);break;case"info":console.info(e,r);break;case"warn":console.warn(e,r);break;case"error":console.error(e,r)}};let d=class t{constructor(t){this.level=t?.level??"warn",this.scope=t?.scope,this.enabled=t?.enabled??!0,this.handlers=t?.handlers??[l]}child(e){return new t({level:this.level,scope:this.scope?`${this.scope}:${e}`:e,enabled:this.enabled,handlers:this.handlers})}debug(t,e){this.log("debug",t,e)}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}error(t,e){this.log("error",t,e)}setLevel(t){this.level=t}setEnabled(t){this.enabled=t}addHandler(t){this.handlers.push(t)}removeHandler(t){const e=this.handlers.indexOf(t);-1!==e&&this.handlers.splice(e,1)}log(t,e,r){if(!this.enabled||!this.shouldLog(t))return;const i={level:t,message:e,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(t){return o.indexOf(t)>=o.indexOf(this.level)}};var h=(t=>(t.SOURCE_NOT_SUPPORTED="SOURCE_NOT_SUPPORTED",t.SOURCE_LOAD_FAILED="SOURCE_LOAD_FAILED",t.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",t.PROVIDER_SETUP_FAILED="PROVIDER_SETUP_FAILED",t.PLUGIN_SETUP_FAILED="PLUGIN_SETUP_FAILED",t.PLUGIN_NOT_FOUND="PLUGIN_NOT_FOUND",t.PLAYBACK_FAILED="PLAYBACK_FAILED",t.MEDIA_DECODE_ERROR="MEDIA_DECODE_ERROR",t.MEDIA_NETWORK_ERROR="MEDIA_NETWORK_ERROR",t.UNKNOWN_ERROR="UNKNOWN_ERROR",t))(h||{});class u{constructor(t,e,r){this.errors=[],this.eventBus=t,this.logger=e,this.maxHistory=r?.maxHistory??10}handle(t,e){const r=this.normalizeError(t,e);return this.addToHistory(r),this.logError(r),this.eventBus.emit("error",r),r}throw(t,e,r){const i={code:t,message:e,fatal:r?.fatal??this.isFatalCode(t),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(t=>t.fatal)}normalizeError(t,e){return this.isPlayerError(t)?{...t,context:{...t.context,...e}}:{code:this.getErrorCode(t),message:t.message,fatal:this.isFatal(t),timestamp:Date.now(),context:e,originalError:t}}getErrorCode(t){const e=t.message.toLowerCase();return e.includes("network")?"MEDIA_NETWORK_ERROR":e.includes("decode")?"MEDIA_DECODE_ERROR":e.includes("source")?"SOURCE_LOAD_FAILED":e.includes("plugin")?"PLUGIN_SETUP_FAILED":e.includes("provider")?"PROVIDER_SETUP_FAILED":"UNKNOWN_ERROR"}isFatal(t){return this.isFatalCode(this.getErrorCode(t))}isFatalCode(t){return["SOURCE_NOT_SUPPORTED","PROVIDER_NOT_FOUND","MEDIA_DECODE_ERROR"].includes(t)}isPlayerError(t){return"object"==typeof t&&null!==t&&"code"in t&&"message"in t&&"fatal"in t&&"timestamp"in t}addToHistory(t){this.errors.push(t),this.errors.length>this.maxHistory&&this.errors.shift()}logError(t){const e=`[${t.code}] ${t.message}`;t.fatal?this.logger.error(e,{code:t.code,context:t.context}):this.logger.warn(e,{code:t.code,context:t.context})}}class c{constructor(t,e){this.cleanupFns=[],this.pluginId=t,this.stateManager=e.stateManager,this.eventBus=e.eventBus,this.container=e.container,this.getPluginFn=e.getPlugin,this.logger={debug:(r,i)=>e.logger.debug(`[${t}] ${r}`,i),info:(r,i)=>e.logger.info(`[${t}] ${r}`,i),warn:(r,i)=>e.logger.warn(`[${t}] ${r}`,i),error:(r,i)=>e.logger.error(`[${t}] ${r}`,i)}}getState(t){return this.stateManager.getValue(t)}setState(t,e){this.stateManager.set(t,e)}on(t,e){return this.eventBus.on(t,e)}off(t,e){this.eventBus.off(t,e)}emit(t,e){this.eventBus.emit(t,e)}getPlugin(t){return this.getPluginFn(t)}onDestroy(t){this.cleanupFns.push(t)}subscribeToState(t){return this.stateManager.subscribe(t)}runCleanups(){for(const e of this.cleanupFns)try{e()}catch(t){this.logger.error("Cleanup function failed",{error:t})}this.cleanupFns=[]}getCleanupFns(){return this.cleanupFns}}class f{constructor(t,e,r,i){this.plugins=new Map,this.eventBus=t,this.stateManager=e,this.logger=r,this.container=i.container}register(t,e){if(this.plugins.has(t.id))throw new Error(`Plugin "${t.id}" is already registered`);this.validatePlugin(t);const r=new c(t.id,{stateManager:this.stateManager,eventBus:this.eventBus,logger:this.logger,container:this.container,getPlugin:t=>this.getReadyPlugin(t)});this.plugins.set(t.id,{plugin:t,state:"registered",config:e,cleanupFns:[],api:r}),this.logger.info(`Plugin registered: ${t.id}`),this.eventBus.emit("plugin:registered",{name:t.id,type:t.type})}async unregister(t){const e=this.plugins.get(t);e&&("ready"===e.state&&await this.destroyPlugin(t),this.plugins.delete(t),this.logger.info(`Plugin unregistered: ${t}`))}async initAll(){const t=this.resolveDependencyOrder();for(const e of t)await this.initPlugin(e)}async initPlugin(t){const e=this.plugins.get(t);if(!e)throw new Error(`Plugin "${t}" not found`);if("ready"!==e.state){if("initializing"===e.state)throw new Error(`Plugin "${t}" is already initializing (possible circular dependency)`);for(const r of e.plugin.dependencies||[]){const e=this.plugins.get(r);if(!e)throw new Error(`Plugin "${t}" depends on missing plugin "${r}"`);"ready"!==e.state&&await this.initPlugin(r)}try{if(e.state="initializing",e.plugin.onStateChange){const t=this.stateManager.subscribe(e.plugin.onStateChange.bind(e.plugin));e.api.onDestroy(t)}if(e.plugin.onError){const t=this.eventBus.on("error",t=>{e.plugin.onError?.(t.originalError||new Error(t.message))});e.api.onDestroy(t)}await e.plugin.init(e.api,e.config),e.state="ready",this.logger.info(`Plugin ready: ${t}`),this.eventBus.emit("plugin:active",{name:t})}catch(r){throw e.state="error",e.error=r,this.logger.error(`Plugin init failed: ${t}`,{error:r}),this.eventBus.emit("plugin:error",{name:t,error:r}),r}}}async destroyAll(){const t=this.resolveDependencyOrder().reverse();for(const e of t)await this.destroyPlugin(e)}async destroyPlugin(t){const e=this.plugins.get(t);if(e&&"ready"===e.state)try{await e.plugin.destroy(),e.api.runCleanups(),e.state="registered",this.logger.info(`Plugin destroyed: ${t}`),this.eventBus.emit("plugin:destroyed",{name:t})}catch(r){this.logger.error(`Plugin destroy failed: ${t}`,{error:r}),e.state="registered"}}getPlugin(t){const e=this.plugins.get(t);return e?e.plugin:null}getReadyPlugin(t){const e=this.plugins.get(t);return"ready"===e?.state?e.plugin:null}hasPlugin(t){return this.plugins.has(t)}getPluginState(t){return this.plugins.get(t)?.state??null}getPluginIds(){return Array.from(this.plugins.keys())}getReadyPlugins(){return Array.from(this.plugins.values()).filter(t=>"ready"===t.state).map(t=>t.plugin)}getPluginsByType(t){return Array.from(this.plugins.values()).filter(e=>e.plugin.type===t).map(t=>t.plugin)}selectProvider(t){const e=this.getPluginsByType("provider");for(const r of e){const e=r.canPlay;if("function"==typeof e&&e(t))return r}return null}resolveDependencyOrder(){const t=new Set,e=new Set,r=[],i=(s,n=[])=>{if(t.has(s))return;if(e.has(s)){const t=[...n,s].join(" -> ");throw new Error(`Circular dependency detected: ${t}`)}const a=this.plugins.get(s);if(a){e.add(s);for(const t of a.plugin.dependencies||[])this.plugins.has(t)&&i(t,[...n,s]);e.delete(s),t.add(s),r.push(s)}};for(const s of this.plugins.keys())i(s);return r}validatePlugin(t){if(!t.id||"string"!=typeof t.id)throw new Error("Plugin must have a valid id");if(!t.name||"string"!=typeof t.name)throw new Error(`Plugin "${t.id}" must have a valid name`);if(!t.version||"string"!=typeof t.version)throw new Error(`Plugin "${t.id}" must have a valid version`);if(!t.type||"string"!=typeof t.type)throw new Error(`Plugin "${t.id}" must have a valid type`);if("function"!=typeof t.init)throw new Error(`Plugin "${t.id}" must have an init() method`);if("function"!=typeof t.destroy)throw new Error(`Plugin "${t.id}" must have a destroy() method`)}}class g{constructor(t){if(this._currentProvider=null,this.destroyed=!1,this.seekingWhilePlaying=!1,this.seekResumeTimeout=null,"string"==typeof t.container){const e=document.querySelector(t.container);if(!(e&&e instanceof HTMLElement))throw new Error(`ScarlettPlayer: container not found: ${t.container}`);this.container=e}else{if(!(t.container instanceof HTMLElement))throw new Error("ScarlettPlayer requires a valid HTMLElement container or CSS selector");this.container=t.container}if(this.initialSrc=t.src,this.eventBus=new a,this.stateManager=new s({autoplay:t.autoplay??!1,loop:t.loop??!1,volume:t.volume??1,muted:t.muted??!1,poster:t.poster??""}),this.logger=new d({level:t.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}),t.plugins)for(const e of t.plugins)this.pluginManager.register(e);this.logger.info("ScarlettPlayer initialized",{autoplay:t.autoplay,plugins:t.plugins?.length??0}),this.eventBus.emit("player:ready",void 0)}async init(){this.checkDestroyed();for(const[t,e]of this.pluginManager.plugins)"provider"!==e.plugin.type&&"registered"===e.state&&await this.pluginManager.initPlugin(t);return this.initialSrc&&await this.load(this.initialSrc),Promise.resolve()}async load(t){this.checkDestroyed();try{if(this.logger.info("Loading source",{source:t}),this.stateManager.update({playing:!1,paused:!0,ended:!1,buffering:!0,currentTime:0,duration:0,bufferedAmount:0,playbackState:"loading"}),this._currentProvider){const t=this._currentProvider.id;this.logger.info("Destroying previous provider",{provider:t}),await this.pluginManager.destroyPlugin(t),this._currentProvider=null}const e=this.pluginManager.selectProvider(t);if(!e)return void this.errorHandler.throw(h.PROVIDER_NOT_FOUND,`No provider found for source: ${t}`,{fatal:!0,context:{source:t}});this._currentProvider=e,this.logger.info("Provider selected",{provider:e.id}),await this.pluginManager.initPlugin(e.id),this.stateManager.set("source",{src:t,type:this.detectMimeType(t)}),"function"==typeof e.loadSource&&await e.loadSource(t),this.stateManager.getValue("autoplay")&&await this.play()}catch(e){this.errorHandler.handle(e,{operation:"load",source:t})}}async play(){this.checkDestroyed();try{this.logger.debug("Play requested"),this.eventBus.emit("playback:play",void 0)}catch(t){this.errorHandler.handle(t,{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(t){this.errorHandler.handle(t,{operation:"pause"})}}seek(t){this.checkDestroyed();try{this.logger.debug("Seek requested",{time:t});this.stateManager.getValue("playing")&&(this.seekingWhilePlaying=!0),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:seeking",{time:t}),this.stateManager.set("currentTime",t),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(e){this.errorHandler.handle(e,{operation:"seek",time:t})}}setVolume(t){this.checkDestroyed();const e=Math.max(0,Math.min(1,t));this.stateManager.set("volume",e),this.eventBus.emit("volume:change",{volume:e,muted:this.stateManager.getValue("muted")})}setMuted(t){this.checkDestroyed(),this.stateManager.set("muted",t),this.eventBus.emit("volume:mute",{muted:t})}setPlaybackRate(t){this.checkDestroyed(),this.stateManager.set("playbackRate",t),this.eventBus.emit("playback:ratechange",{rate:t})}setAutoplay(t){this.checkDestroyed(),this.stateManager.set("autoplay",t),this.logger.debug("Autoplay set",{autoplay:t})}on(t,e){return this.checkDestroyed(),this.eventBus.on(t,e)}once(t,e){return this.checkDestroyed(),this.eventBus.once(t,e)}getPlugin(t){return this.checkDestroyed(),this.pluginManager.getPlugin(t)}registerPlugin(t){this.checkDestroyed(),this.pluginManager.register(t)}getState(){return this.checkDestroyed(),this.stateManager.snapshot()}getQualities(){if(this.checkDestroyed(),!this._currentProvider)return[];const t=this._currentProvider;return"function"==typeof t.getLevels?t.getLevels():[]}setQuality(t){if(this.checkDestroyed(),!this._currentProvider)return void this.logger.warn("No provider available for quality change");const e=this._currentProvider;"function"==typeof e.setLevel&&(e.setLevel(t),this.eventBus.emit("quality:change",{quality:-1===t?"auto":`level-${t}`,auto:-1===t}))}getCurrentQuality(){if(this.checkDestroyed(),!this._currentProvider)return-1;const t=this._currentProvider;return"function"==typeof t.getCurrentLevel?t.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(t){this.logger.error("Fullscreen request failed",{error:t})}}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(t){this.logger.error("Exit fullscreen failed",{error:t})}}async toggleFullscreen(){this.fullscreen?await this.exitFullscreen():await this.requestFullscreen()}requestAirPlay(){this.checkDestroyed();const t=this.pluginManager.getPlugin("airplay");t&&"function"==typeof t.showPicker?t.showPicker():this.logger.warn("AirPlay plugin not available")}async requestChromecast(){this.checkDestroyed();const t=this.pluginManager.getPlugin("chromecast");t&&"function"==typeof t.requestSession?await t.requestSession():this.logger.warn("Chromecast plugin not available")}stopCasting(){this.checkDestroyed();const t=this.pluginManager.getPlugin("airplay");t&&"function"==typeof t.stop&&t.stop();const e=this.pluginManager.getPlugin("chromecast");e&&"function"==typeof e.stopSession&&e.stopSession()}seekToLive(){this.checkDestroyed();if(!this.stateManager.getValue("live"))return void this.logger.warn("Not a live stream");if(this._currentProvider){const t=this._currentProvider;if("function"==typeof t.getLiveInfo){const e=t.getLiveInfo();if(void 0!==e?.liveSyncPosition)return void this.seek(e.liveSyncPosition)}}const t=this.stateManager.getValue("duration");t>0&&this.seek(t)}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(t){const e=t.split(".").pop()?.toLowerCase();switch(e){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 m(t){if(t.name)return t.name;if(t.height){const e={2160:"4K",1440:"1440p",1080:"1080p",720:"720p",480:"480p",360:"360p",240:"240p",144:"144p"},r=Object.keys(e).map(Number).sort((e,r)=>Math.abs(e-t.height)-Math.abs(r-t.height))[0];return Math.abs(r-t.height)<=20?e[r]:`${t.height}p`}return t.bitrate?function(t){if(t>=1e6)return`${(t/1e6).toFixed(1)} Mbps`;if(t>=1e3)return`${Math.round(t/1e3)} Kbps`;return`${t} bps`}(t.bitrate):"Unknown"}var p="networkError",v="mediaError",y="muxError";function E(t){switch(t){case p:return"network";case v:return"media";case y:return"mux";default:return"other"}}function T(t,e,r){const i=[],s=(e,r)=>{t.on(e,r),i.push({event:e,handler:r})};return s("hlsManifestParsed",(i,s)=>{e.logger.debug("HLS manifest parsed",{levels:s.levels.length});const n=s.levels.map((e,r)=>({id:`level-${r}`,label:m(e),width:e.width,height:e.height,bitrate:e.bitrate,active:r===t.currentLevel}));e.setState("qualities",n),e.emit("quality:levels",{levels:n.map(t=>({id:t.id,label:t.label}))}),r.onManifestParsed?.(s.levels)}),s("hlsLevelSwitched",(i,s)=>{const n=t.levels[s.level],a=r.getIsAutoQuality?.()??t.autoLevelEnabled;if(e.logger.debug("HLS level switched",{level:s.level,height:n?.height,auto:a}),n){const t=a?`Auto (${m(n)})`:m(n);e.setState("currentQuality",{id:a?"auto":`level-${s.level}`,label:t,width:n.width,height:n.height,bitrate:n.bitrate,active:!0})}e.emit("quality:change",{quality:n?m(n):"auto",auto:a}),r.onLevelSwitched?.(s.level)}),s("hlsFragBuffered",()=>{e.setState("buffering",!1),r.onBufferUpdate?.()}),s("hlsFragLoading",()=>{e.setState("buffering",!0)}),s("hlsLevelLoaded",(t,i)=>{void 0!==i.details?.live&&(e.setState("live",i.details.live),r.onLiveUpdate?.())}),s("hlsError",(t,i)=>{const s=function(t){return{type:E(t.type),details:t.details||"Unknown error",fatal:t.fatal||!1,url:t.url,reason:t.reason,response:t.response}}(i);e.logger.warn("HLS error",{error:s}),r.onError?.(s)}),()=>{for(const{event:e,handler:r}of i)t.off(e,r);i.length=0}}function S(t,e){const r=[],i=(e,i)=>{t.addEventListener(e,i),r.push({event:e,handler:i})};i("playing",()=>{e.setState("playing",!0),e.setState("paused",!1),e.setState("playbackState","playing")}),i("pause",()=>{e.setState("playing",!1),e.setState("paused",!0),e.setState("playbackState","paused")}),i("ended",()=>{e.setState("playing",!1),e.setState("ended",!0),e.setState("playbackState","ended"),e.emit("playback:ended",void 0)}),i("timeupdate",()=>{e.setState("currentTime",t.currentTime),e.emit("playback:timeupdate",{currentTime:t.currentTime})}),i("durationchange",()=>{e.setState("duration",t.duration||0),e.emit("media:loadedmetadata",{duration:t.duration||0})}),i("waiting",()=>{e.setState("waiting",!0),e.setState("buffering",!0),e.emit("media:waiting",void 0)}),i("canplay",()=>{e.setState("waiting",!1),e.setState("playbackState","ready"),e.emit("media:canplay",void 0)}),i("canplaythrough",()=>{e.setState("buffering",!1),e.emit("media:canplaythrough",void 0)}),i("progress",()=>{if(t.buffered.length>0){const r=t.buffered.end(t.buffered.length-1),i=t.duration>0?r/t.duration:0;e.setState("bufferedAmount",i),e.setState("buffered",t.buffered),e.emit("media:progress",{buffered:i})}}),i("seeking",()=>{e.setState("seeking",!0)}),i("seeked",()=>{e.setState("seeking",!1),e.emit("playback:seeked",{time:t.currentTime})}),i("volumechange",()=>{e.setState("volume",t.volume),e.setState("muted",t.muted),e.emit("volume:change",{volume:t.volume,muted:t.muted})}),i("ratechange",()=>{e.setState("playbackRate",t.playbackRate),e.emit("playback:ratechange",{rate:t.playbackRate})}),i("loadedmetadata",()=>{e.setState("duration",t.duration),e.setState("mediaType",t.videoWidth>0?"video":"audio")}),i("error",()=>{const r=t.error;r&&(e.logger.error("Video element error",{code:r.code,message:r.message}),e.emit("media:error",{error:new Error(r.message||"Video playback error")}))}),i("enterpictureinpicture",()=>{e.setState("pip",!0),e.logger.debug("PiP: entered (standard)")}),i("leavepictureinpicture",()=>{e.setState("pip",!1),e.logger.debug("PiP: exited (standard)"),t.paused&&!e.getState("playing")||t.play().catch(()=>{})});const s=t;return"webkitPresentationMode"in t&&i("webkitpresentationmodechanged",()=>{const r=s.webkitPresentationMode,i="picture-in-picture"===r;e.setState("pip",i),e.logger.debug(`PiP: mode changed to ${r} (webkit)`),"inline"===r&&t.paused&&t.play().catch(()=>{})}),()=>{for(const{event:e,handler:i}of r)t.removeEventListener(e,i);r.length=0}}var L=null,b=null;function A(){if("undefined"==typeof document)return!1;return""!==document.createElement("video").canPlayType("application/vnd.apple.mpegurl")}function R(){return L?L.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 _(t){const e={...k,...t};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 p=()=>{if(s)return s;const t=r?.container.querySelector("video");return t?(s=t,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=t=>{const r=e.retryDelayMs??1e3,i=e.retryBackoffFactor??2;return r*Math.pow(i,t)},E=(t,e)=>{const i=e?`HLS error: ${t.details} (max retries exceeded)`:`HLS error: ${t.details}`;r?.logger.error(i,{type:t.type,details:t.details}),r?.setState("playbackState","error"),r?.setState("buffering",!1),r?.emit("error",{code:"MEDIA_ERROR",message:i,fatal:!0,timestamp:Date.now()})},_=t=>{if(!L||!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(t,!0),o?.(),o=null,i.destroy(),void(i=null);if(t.fatal)switch(r?.logger.error("Fatal HLS error",{type:t.type,details:t.details}),t.type){case"network":{const s=e.maxNetworkRetries??3;if(h>=s)return r?.logger.error(`Network error recovery failed after ${h} attempts`),void E(t,!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(t.details)}),c&&clearTimeout(c),c=setTimeout(()=>{i&&i.startLoad()},n);break}case"media":{const s=e.maxMediaRetries??2;if(u>=s)return r?.logger.error(`Media error recovery failed after ${u} attempts`),void E(t,!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(t.details)}),c&&clearTimeout(c),c=setTimeout(()=>{i&&i.recoverMediaError()},n);break}default:E(t,!1)}},D=async t=>{const e=p();return n=!0,r&&(l=S(e,r)),new Promise((i,s)=>{const n=()=>{e.removeEventListener("loadedmetadata",n),e.removeEventListener("error",a),r?.setState("source",{src:t,type:"application/x-mpegURL"}),r?.emit("media:loaded",{src:t,type:"application/x-mpegURL"}),i()},a=()=>{e.removeEventListener("loadedmetadata",n),e.removeEventListener("error",a);const t=e.error;s(new Error(t?.message||"Failed to load HLS source"))};e.addEventListener("loadedmetadata",n),e.addEventListener("error",a),e.src=t,e.load()})},w=async t=>{await async function(){return L||b||(b=(async()=>{try{const t=await Promise.resolve().then(()=>aa);if(!(L=t.default).isSupported())throw new Error("hls.js is not supported in this browser");return L}catch(t){throw b=null,new Error(`Failed to load hls.js: ${t instanceof Error?t.message:"Unknown error"}`)}})())}();const s=p();return n=!1,i=function(t){if(!L)throw new Error("hls.js is not loaded. Call loadHlsJs() first.");return new L(t)}({debug:e.debug,autoStartLoad:e.autoStartLoad,startPosition:e.startPosition,startLevel:-1,lowLatencyMode:e.lowLatencyMode,maxBufferLength:e.maxBufferLength,maxMaxBufferLength:e.maxMaxBufferLength,backBufferLength:e.backBufferLength,enableWorker:e.enableWorker,fragLoadingMaxRetry:1,manifestLoadingMaxRetry:1,levelLoadingMaxRetry:1,fragLoadingRetryDelay:500,manifestLoadingRetryDelay:500,levelLoadingRetryDelay:500}),r&&(l=S(s,r)),new Promise((e,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:t,type:"application/x-mpegURL"}),r?.emit("media:loaded",{src:t,type:"application/x-mpegURL"}),e())},onLevelSwitched:()=>{},onError:t=>{_(t),t.fatal&&!a&&"network"!==t.type&&"media"!==t.type&&(a=!0,n(new Error(t.details)))},getIsAutoQuality:()=>d}),i.attachMedia(s),i.loadSource(t)})};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(t){if(!A()&&!R())return!1;const e=t.toLowerCase();return!!e.split("?")[0].split("#")[0].endsWith(".m3u8")||(!!e.includes("application/x-mpegurl")||!!e.includes("application/vnd.apple.mpegurl"))},async init(t){r=t,r.logger.info("HLS plugin (light) initialized");const e=r.on("playback:play",async()=>{if(s)try{await s.play()}catch(t){r?.logger.error("Play failed",t)}}),a=r.on("playback:pause",()=>{s?.pause()}),o=r.on("playback:seeking",({time:t})=>{if(!s)return;const e=Math.max(0,Math.min(t,s.duration||0));s.currentTime=e}),l=r.on("volume:change",({volume:t})=>{s&&(s.volume=t)}),h=r.on("volume:mute",({muted:t})=>{s&&(s.muted=t)}),u=r.on("playback:ratechange",({rate:t})=>{s&&(s.playbackRate=t)}),c=r.on("quality:select",({quality:t,auto:e})=>{if(i&&!n)if(e||"auto"===t)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 e=parseInt(t.replace("level-",""),10);!isNaN(e)&&e>=0&&e<i.levels.length&&(i.nextLevel=e,r?.logger.debug(`Quality: queued switch to level ${e}`))}else r?.logger.warn("Quality selection not available")});r.onDestroy(()=>{e(),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(t){if(!r)throw new Error("Plugin not initialized");if(r.logger.info("Loading HLS source (light)",{src:t}),v(),a=t,r.setState("playbackState","loading"),r.setState("buffering",!0),R())r.logger.info("Using hls.js/light for HLS playback"),await w(t);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 D(t)}r.setState("playbackState","ready"),r.setState("buffering",!1)},getCurrentLevel:()=>n||!i?-1:i.currentLevel,setLevel(t){!n&&i?i.currentLevel=t:r?.logger.warn("Quality selection not available in native HLS mode")},getLevels(){return n||!i?[]:(t=i.levels,i.currentLevel,t.map((t,e)=>({index:e,width:t.width||0,height:t.height||0,bitrate:t.bitrate||0,label:m(t),codec:t.codecSet})));var t},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 t=r?.getState("playing")||!1,e=s?.currentTime||0,i=a;if(v(),await D(i),s&&e>0&&(s.currentTime=e),t&&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 t=r?.getState("playing")||!1,e=s?.currentTime||0,i=a;if(v(),await w(i),s&&e>0&&(s.currentTime=e),t&&s)try{await s.play()}catch(o){r?.logger.debug("Could not auto-resume after switch")}r?.logger.info("Switched to hls.js")}}}var D={primary:"#6366f1",background:"#18181b",text:"#fafafa",textSecondary:"#a1a1aa",progressBackground:"#3f3f46",progressFill:"#6366f1",borderRadius:"12px",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},w={layout:"full",showArtwork:!0,showTitle:!0,showArtist:!0,showTime:!0,showVolume:!0,showShuffle:!0,showRepeat:!0,showNavigation:!0,classPrefix:"scarlett-audio",autoHide:0,theme:D};function x(t){if(!isFinite(t)||t<0)return"0:00";const e=Math.floor(t/3600),r=Math.floor(t%3600/60),i=Math.floor(t%60);return e>0?`${e}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`:`${r}:${i.toString().padStart(2,"0")}`}function I(t,e){return`\n .${t} {\n font-family: ${e.fontFamily};\n background: ${e.background};\n color: ${e.text};\n border-radius: ${e.borderRadius};\n overflow: hidden;\n user-select: none;\n }\n\n .${t}--full {\n display: flex;\n flex-direction: column;\n padding: 20px;\n gap: 16px;\n max-width: 400px;\n }\n\n .${t}--compact {\n display: flex;\n align-items: center;\n padding: 12px 16px;\n gap: 12px;\n }\n\n .${t}--mini {\n display: flex;\n align-items: center;\n padding: 8px 12px;\n gap: 8px;\n }\n\n .${t}__artwork {\n flex-shrink: 0;\n background: ${e.progressBackground};\n border-radius: 8px;\n overflow: hidden;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .${t}--full .${t}__artwork {\n width: 100%;\n aspect-ratio: 1;\n border-radius: ${e.borderRadius};\n }\n\n .${t}--compact .${t}__artwork {\n width: 56px;\n height: 56px;\n }\n\n .${t}--mini .${t}__artwork {\n width: 40px;\n height: 40px;\n border-radius: 6px;\n }\n\n .${t}__artwork img {\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .${t}__artwork-placeholder {\n width: 50%;\n height: 50%;\n opacity: 0.3;\n }\n\n .${t}__info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${t}__title {\n font-size: 16px;\n font-weight: 600;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .${t}--mini .${t}__title {\n font-size: 14px;\n display: inline-block;\n animation: none;\n }\n\n .${t}__title-wrapper {\n overflow: hidden;\n width: 100%;\n }\n\n .${t}--mini .${t}__title-wrapper .${t}__title.scrolling {\n animation: marquee 8s linear infinite;\n }\n\n @keyframes marquee {\n 0% { transform: translateX(0); }\n 100% { transform: translateX(-50%); }\n }\n\n .${t}--mini .${t}__progress {\n margin-top: 4px;\n }\n\n .${t}--mini .${t}__progress-bar {\n height: 4px;\n }\n\n .${t}__artist {\n font-size: 14px;\n color: ${e.textSecondary};\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .${t}--mini .${t}__artist {\n font-size: 12px;\n }\n\n .${t}__progress {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .${t}__progress-bar {\n flex: 1;\n height: 6px;\n background: ${e.progressBackground};\n border-radius: 3px;\n cursor: pointer;\n position: relative;\n overflow: hidden;\n }\n\n .${t}__progress-bar:hover {\n height: 8px;\n }\n\n .${t}__progress-fill {\n height: 100%;\n background: ${e.progressFill};\n border-radius: 3px;\n width: 100%;\n transform-origin: left center;\n will-change: transform;\n }\n\n .${t}__progress-buffered {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: ${e.progressBackground};\n opacity: 0.5;\n border-radius: 3px;\n }\n\n .${t}__time {\n font-size: 12px;\n color: ${e.textSecondary};\n min-width: 40px;\n text-align: center;\n }\n\n .${t}__controls {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n }\n\n .${t}__btn {\n background: transparent;\n border: none;\n color: ${e.text};\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s, transform 0.1s;\n }\n\n .${t}__btn:hover {\n background: rgba(255, 255, 255, 0.1);\n }\n\n .${t}__btn:active {\n transform: scale(0.95);\n }\n\n .${t}__btn--primary {\n background: ${e.primary};\n width: 48px;\n height: 48px;\n }\n\n .${t}__btn--primary:hover {\n background: ${e.primary};\n opacity: 0.9;\n }\n\n .${t}--mini .${t}__btn--primary {\n width: 36px;\n height: 36px;\n }\n\n .${t}__btn--active {\n color: ${e.primary};\n }\n\n .${t}__btn svg {\n width: 20px;\n height: 20px;\n fill: currentColor;\n }\n\n .${t}__btn--primary svg {\n width: 24px;\n height: 24px;\n }\n\n .${t}__volume {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .${t}__volume-slider {\n width: 80px;\n height: 4px;\n background: ${e.progressBackground};\n border-radius: 2px;\n cursor: pointer;\n position: relative;\n }\n\n .${t}__volume-fill {\n height: 100%;\n background: ${e.text};\n border-radius: 2px;\n }\n\n .${t}__secondary-controls {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .${t}--hidden {\n display: none;\n }\n `}var P={play:'<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>',pause:'<svg viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>',previous:'<svg viewBox="0 0 24 24"><path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/></svg>',next:'<svg viewBox="0 0 24 24"><path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/></svg>',shuffle:'<svg viewBox="0 0 24 24"><path d="M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"/></svg>',repeatOff:'<svg viewBox="0 0 24 24"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/></svg>',repeatAll:'<svg viewBox="0 0 24 24"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/></svg>',repeatOne:'<svg viewBox="0 0 24 24"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z"/></svg>',volumeHigh:'<svg viewBox="0 0 24 24"><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>',volumeMuted:'<svg viewBox="0 0 24 24"><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>',music:'<svg viewBox="0 0 24 24"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>'};function C(t){const e={...w,...t},r={...D,...e.theme},i=e.classPrefix;let s=null,n=null,a=null,o=e.layout,l=!0,d=null,h=0,u=0,c=!1,f=null,g=null,m=null,p=null,v=null,y=null,E=null,T=null,S=null,L=null,b=null;const A=()=>{if(null!==d)return;const t=e=>{if(!s||!c)return void(d=null);const r=s.getState("duration")||0;if(r<=0)return void(d=requestAnimationFrame(t));const i=(e-u)/1e3,n=Math.min(h+i,r),a=n/r;p&&(p.style.transform=`scaleX(${a})`),v&&(v.textContent=x(n)),d=requestAnimationFrame(t)};u=performance.now(),d=requestAnimationFrame(t)},R=()=>{null!==d&&(cancelAnimationFrame(d),d=null)},k=()=>`\n ${e.showArtwork?`\n <div class="${i}__artwork">\n <img src="${e.defaultArtwork||""}" alt="Album art" />\n ${e.defaultArtwork?"":`<div class="${i}__artwork-placeholder">${P.music}</div>`}\n </div>\n `:""}\n <div class="${i}__info">\n ${e.showTitle?`<div class="${i}__title">-</div>`:""}\n ${e.showArtist?`<div class="${i}__artist">-</div>`:""}\n </div>\n <div class="${i}__progress">\n ${e.showTime?`<span class="${i}__time ${i}__time--current">0:00</span>`:""}\n <div class="${i}__progress-bar">\n <div class="${i}__progress-fill" style="transform: scaleX(0)"></div>\n </div>\n ${e.showTime?`<span class="${i}__time ${i}__time--duration">0:00</span>`:""}\n </div>\n <div class="${i}__controls">\n ${e.showShuffle?`<button class="${i}__btn ${i}__btn--shuffle" title="Shuffle">${P.shuffle}</button>`:""}\n ${e.showNavigation?`<button class="${i}__btn ${i}__btn--prev" title="Previous">${P.previous}</button>`:""}\n <button class="${i}__btn ${i}__btn--primary ${i}__btn--play" title="Play">${P.play}</button>\n ${e.showNavigation?`<button class="${i}__btn ${i}__btn--next" title="Next">${P.next}</button>`:""}\n ${e.showRepeat?`<button class="${i}__btn ${i}__btn--repeat" title="Repeat">${P.repeatOff}</button>`:""}\n </div>\n ${e.showVolume?`\n <div class="${i}__secondary-controls">\n <div class="${i}__volume">\n <button class="${i}__btn ${i}__btn--volume" title="Volume">${P.volumeHigh}</button>\n <div class="${i}__volume-slider">\n <div class="${i}__volume-fill" style="width: 100%"></div>\n </div>\n </div>\n </div>\n `:""}\n `,_=()=>`\n ${e.showArtwork?`\n <div class="${i}__artwork">\n <img src="${e.defaultArtwork||""}" alt="Album art" />\n </div>\n `:""}\n <div class="${i}__info">\n ${e.showTitle?`<div class="${i}__title">-</div>`:""}\n ${e.showArtist?`<div class="${i}__artist">-</div>`:""}\n <div class="${i}__progress">\n <div class="${i}__progress-bar">\n <div class="${i}__progress-fill" style="transform: scaleX(0)"></div>\n </div>\n </div>\n </div>\n <div class="${i}__controls">\n ${e.showNavigation?`<button class="${i}__btn ${i}__btn--prev" title="Previous">${P.previous}</button>`:""}\n <button class="${i}__btn ${i}__btn--primary ${i}__btn--play" title="Play">${P.play}</button>\n ${e.showNavigation?`<button class="${i}__btn ${i}__btn--next" title="Next">${P.next}</button>`:""}\n </div>\n `,C=()=>`\n <button class="${i}__btn ${i}__btn--primary ${i}__btn--play" title="Play">${P.play}</button>\n ${e.showArtwork?`\n <div class="${i}__artwork">\n <img src="${e.defaultArtwork||""}" alt="Album art" />\n </div>\n `:""}\n <div class="${i}__info">\n ${e.showTitle?`<div class="${i}__title-wrapper"><div class="${i}__title">-</div></div>`:""}\n <div class="${i}__progress">\n <div class="${i}__progress-bar">\n <div class="${i}__progress-fill" style="transform: scaleX(0)"></div>\n </div>\n </div>\n </div>\n `,M=()=>{if(!n||!s)return;E?.addEventListener("click",()=>{const t=s?.getState("playing");s?.emit(t?"playback:pause":"playback:play",void 0)}),n.querySelector(`.${i}__btn--prev`)?.addEventListener("click",()=>{const t=s?.getPlugin("playlist");t?t.previous():s?.emit("playback:seeking",{time:0})}),n.querySelector(`.${i}__btn--next`)?.addEventListener("click",()=>{const t=s?.getPlugin("playlist");t?.next()}),T?.addEventListener("click",()=>{const t=s?.getPlugin("playlist");t?.toggleShuffle()}),S?.addEventListener("click",()=>{const t=s?.getPlugin("playlist");t?.cycleRepeat()}),L?.addEventListener("click",()=>{const t=s?.getState("muted");s?.emit("volume:mute",{muted:!t})});const t=n.querySelector(`.${i}__progress-bar`);t?.addEventListener("click",t=>{const e=t,r=e.currentTarget.getBoundingClientRect(),i=(e.clientX-r.left)/r.width*(s?.getState("duration")||0);s?.emit("playback:seeking",{time:i})});const e=n.querySelector(`.${i}__volume-slider`);e?.addEventListener("click",t=>{const e=t,r=e.currentTarget.getBoundingClientRect(),i=Math.max(0,Math.min(1,(e.clientX-r.left)/r.width));s?.emit("volume:change",{volume:i,muted:!1})})},O=()=>{if(!s||!n)return;const t=s.getState("playing"),e=c;c=t,E&&(E.innerHTML=t?P.pause:P.play,E.title=t?"Pause":"Play");const r=s.getState("currentTime")||0,a=s.getState("duration")||0;if(h=r,u=performance.now(),t&&!e?A():!t&&e&&R(),!t){const t=a>0?r/a:0;p&&(p.style.transform=`scaleX(${t})`),v&&(v.textContent=x(r))}y&&(y.textContent=x(a));const l=s.getState("title"),d=s.getState("poster");if(g&&l&&(g.textContent=l,"mini"===o)){const t=g.parentElement;t&&g.scrollWidth>t.clientWidth?(g.textContent=`${l} • ${l} • `,g.classList.add("scrolling")):g.classList.remove("scrolling")}f&&d&&(f.src=d);const m=s.getState("volume")||1,k=s.getState("muted");b&&(b.style.width=100*(k?0:m)+"%"),L&&(L.innerHTML=k||0===m?P.volumeMuted:P.volumeHigh);const _=s.getPlugin("playlist");if(_){const t=_.getState();T&&T.classList.toggle(`${i}__btn--active`,t.shuffle),S&&(S.classList.toggle(`${i}__btn--active`,"none"!==t.repeat),"one"===t.repeat?S.innerHTML=P.repeatOne:"all"===t.repeat?S.innerHTML=P.repeatAll:S.innerHTML=P.repeatOff)}};return{id:"audio-ui",name:"Audio UI",version:"1.0.0",type:"ui",description:"Compact audio player interface",async init(t){s=t,s.logger.info("Audio UI plugin initialized"),s&&(a=document.createElement("style"),a.textContent=I(i,r),document.head.appendChild(a),n=document.createElement("div"),n.className=`${i} ${i}--${o}`,n.innerHTML="full"===o?k():"compact"===o?_():C(),f=n.querySelector(`.${i}__artwork img`),g=n.querySelector(`.${i}__title`),m=n.querySelector(`.${i}__artist`),p=n.querySelector(`.${i}__progress-fill`),v=n.querySelector(`.${i}__time--current`),y=n.querySelector(`.${i}__time--duration`),E=n.querySelector(`.${i}__btn--play`),T=n.querySelector(`.${i}__btn--shuffle`),S=n.querySelector(`.${i}__btn--repeat`),L=n.querySelector(`.${i}__btn--volume`),b=n.querySelector(`.${i}__volume-fill`),M(),s.container.appendChild(n));const e=s.subscribeToState(()=>{O()}),l=s.on("playback:timeupdate",()=>{O()}),d=s.on("playlist:change",t=>{t?.track&&(g&&(g.textContent=t.track.title||"-"),m&&(m.textContent=t.track.artist||"-"),f&&t.track.artwork&&(f.src=t.track.artwork))}),h=s.on("playlist:shuffle",()=>{O()}),u=s.on("playlist:repeat",()=>{O()});s.onDestroy(()=>{e(),l(),d(),h(),u()}),O()},async destroy(){s?.logger.info("Audio UI plugin destroying"),R(),n?.parentNode&&n.parentNode.removeChild(n),a?.parentNode&&a.parentNode.removeChild(a),n=null,a=null,s=null},getElement:()=>n,setLayout(t){n&&(R(),o=t,n.className=`${i} ${i}--${o}`,n.innerHTML="full"===o?k():"compact"===o?_():C(),f=n.querySelector(`.${i}__artwork img`),g=n.querySelector(`.${i}__title`),m=n.querySelector(`.${i}__artist`),p=n.querySelector(`.${i}__progress-fill`),v=n.querySelector(`.${i}__time--current`),y=n.querySelector(`.${i}__time--duration`),E=n.querySelector(`.${i}__btn--play`),T=n.querySelector(`.${i}__btn--shuffle`),S=n.querySelector(`.${i}__btn--repeat`),L=n.querySelector(`.${i}__btn--volume`),b=n.querySelector(`.${i}__volume-fill`),M(),O(),c&&A())},setTheme(t){Object.assign(r,t),a&&(a.textContent=I(i,r))},show(){l=!0,n?.classList.remove(`${i}--hidden`)},hide(){l=!1,n?.classList.add(`${i}--hidden`)},toggle(){l?this.hide():this.show()}}}var M={enablePlayPause:!0,enableSeek:!0,enableTrackNavigation:!0,seekOffset:10,updatePositionState:!0};function O(){return"undefined"!=typeof navigator&&"mediaSession"in navigator}function F(t){const e={...M,...t};let r=null,i={};const s=()=>{if(!O())return;const t=[],s=i.artwork||e.defaultArtwork||[];for(const e of s)t.push({src:e.src,sizes:e.sizes||"512x512",type:e.type||"image/png"});try{navigator.mediaSession.metadata=new MediaMetadata({title:i.title||"Unknown",artist:i.artist||"",album:i.album||"",artwork:t})}catch(n){r?.logger.warn("Failed to set media session metadata",n)}},n=()=>{if(!O()||!e.updatePositionState)return;const t=r?.getState("duration")||0,i=r?.getState("currentTime")||0,s=r?.getState("playbackRate")||1;if(t>0&&isFinite(t))try{navigator.mediaSession.setPositionState({duration:t,position:Math.min(i,t),playbackRate:s})}catch(n){r?.logger.debug("Failed to set position state",n)}},a=()=>{if(!O())return;const t=["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"];for(const r of t)try{navigator.mediaSession.setActionHandler(r,null)}catch(e){}};return{id:"media-session",name:"Media Session",version:"1.0.0",type:"feature",description:"Media Session API integration for system-level media controls",async init(t){if(r=t,!O())return void r.logger.info("Media Session API not supported in this browser");r.logger.info("Media Session plugin initialized"),(()=>{if(!O())return;const t=e.seekOffset||10;if(e.enablePlayPause)try{navigator.mediaSession.setActionHandler("play",()=>{r?.logger.debug("Media session: play"),r?.emit("playback:play",void 0)}),navigator.mediaSession.setActionHandler("pause",()=>{r?.logger.debug("Media session: pause"),r?.emit("playback:pause",void 0)}),navigator.mediaSession.setActionHandler("stop",()=>{r?.logger.debug("Media session: stop"),r?.emit("playback:pause",void 0),r?.emit("playback:seeking",{time:0})})}catch(i){r?.logger.debug("Some play/pause actions not supported",i)}if(e.enableSeek)try{navigator.mediaSession.setActionHandler("seekbackward",e=>{const i=e.seekOffset||t,s=r?.getState("currentTime")||0,n=Math.max(0,s-i);r?.logger.debug("Media session: seekbackward",{offset:i,newTime:n}),r?.emit("playback:seeking",{time:n})}),navigator.mediaSession.setActionHandler("seekforward",e=>{const i=e.seekOffset||t,s=r?.getState("currentTime")||0,n=r?.getState("duration")||0,a=Math.min(n,s+i);r?.logger.debug("Media session: seekforward",{offset:i,newTime:a}),r?.emit("playback:seeking",{time:a})}),navigator.mediaSession.setActionHandler("seekto",t=>{void 0!==t.seekTime&&(r?.logger.debug("Media session: seekto",{time:t.seekTime}),r?.emit("playback:seeking",{time:t.seekTime}))})}catch(i){r?.logger.debug("Some seek actions not supported",i)}if(e.enableTrackNavigation)try{navigator.mediaSession.setActionHandler("previoustrack",()=>{r?.logger.debug("Media session: previoustrack");const t=r?.getPlugin("playlist");t?t.previous():r?.emit("playback:seeking",{time:0})}),navigator.mediaSession.setActionHandler("nexttrack",()=>{r?.logger.debug("Media session: nexttrack");const t=r?.getPlugin("playlist");t&&t.next()})}catch(i){r?.logger.debug("Track navigation not supported",i)}})();const o=r.on("playback:play",()=>{O()&&(navigator.mediaSession.playbackState="playing")}),l=r.on("playback:pause",()=>{O()&&(navigator.mediaSession.playbackState="paused")}),d=r.on("playback:ended",()=>{O()&&(navigator.mediaSession.playbackState="none")});let h=0;const u=r.on("playback:timeupdate",()=>{const t=Date.now();t-h>=1e3&&(h=t,n())}),c=r.on("media:loadedmetadata",()=>{n()}),f=r.subscribeToState(t=>{"title"===t.key&&"string"==typeof t.value?(i.title=t.value,s()):"poster"===t.key&&"string"==typeof t.value&&(i.artwork=[{src:t.value,sizes:"512x512"}],s())}),g=r.on("playlist:change",t=>{if(t?.track){const e=t.track;i={title:e.title,artist:e.artist,album:e.album,artwork:e.artwork?[{src:e.artwork,sizes:"512x512"}]:void 0},s()}});r.onDestroy(()=>{o(),l(),d(),u(),c(),f(),g(),a()})},async destroy(){r?.logger.info("Media Session plugin destroying"),a(),O()&&(navigator.mediaSession.metadata=null,navigator.mediaSession.playbackState="none"),r=null},isSupported:()=>O(),setMetadata(t){i={...i,...t},s()},setPlaybackState(t){O()&&(navigator.mediaSession.playbackState=t)},setPositionState(t){if(O())try{navigator.mediaSession.setPositionState(t)}catch(e){r?.logger.debug("Failed to set position state",e)}},setActionHandler(t,e){if(O())try{navigator.mediaSession.setActionHandler(t,e)}catch(i){r?.logger.debug(`Action ${t} not supported`,i)}}}}var $={autoAdvance:!0,preloadNext:!0,persist:!1,persistKey:"scarlett-playlist",shuffle:!1,repeat:"none"};function N(){return`track-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function B(t){const e={...$,...t};let r=null,i=e.tracks||[],s=-1,n=e.shuffle||!1,a=e.repeat||"none",o=[];i=i.map(t=>({...t,id:t.id||N()}));const l=()=>{const t=i.map((t,e)=>e);if(o=function(t){const e=[...t];for(let r=e.length-1;r>0;r--){const t=Math.floor(Math.random()*(r+1));[e[r],e[t]]=[e[t],e[r]]}return e}(t),s>=0){const t=o.indexOf(s);t>0&&(o.splice(t,1),o.unshift(s))}},d=t=>n&&0!==o.length?o[t]??t:t,h=t=>n&&0!==o.length?o.indexOf(t):t,u=()=>{if(0===i.length)return!1;if("one"===a||"all"===a)return!0;return h(s)<i.length-1},c=()=>{if(0===i.length)return!1;if("one"===a||"all"===a)return!0;return h(s)>0},f=()=>{if(0===i.length)return-1;if("one"===a)return s;let t=h(s)+1;if(t>=i.length){if("all"!==a)return-1;n&&l(),t=0}return d(t)},g=()=>{if(e.persist)try{const t={tracks:i,currentIndex:s,shuffle:n,repeat:a,shuffleOrder:o};localStorage.setItem(e.persistKey,JSON.stringify(t))}catch(t){r?.logger.warn("Failed to persist playlist",t)}},m=()=>{const t=s>=0?i[s]:null;r?.emit("playlist:change",{track:t,index:s}),g()},p=t=>{if(t<0||t>=i.length)return void r?.logger.warn("Invalid track index",{index:t});const e=i[t];s=t,r?.logger.info("Track changed",{index:t,title:e.title,src:e.src}),e.title&&r?.setState("title",e.title),e.artwork&&r?.setState("poster",e.artwork),r?.setState("mediaType",e.type||"audio"),m()};return{id:"playlist",name:"Playlist",version:"1.0.0",type:"feature",description:"Playlist management with shuffle, repeat, and gapless playback",async init(t){r=t,r.logger.info("Playlist plugin initialized"),(()=>{if(e.persist)try{const t=localStorage.getItem(e.persistKey);if(t){const e=JSON.parse(t);i=e.tracks||[],s=e.currentIndex??-1,n=e.shuffle??!1,a=e.repeat??"none",o=e.shuffleOrder||[]}}catch(t){r?.logger.warn("Failed to load persisted playlist",t)}})(),n&&i.length>0&&l();const d=r.on("playback:ended",()=>{if(!e.autoAdvance)return;const t=f();t>=0?(r?.logger.debug("Auto-advancing to next track",{nextIdx:t}),p(t)):(r?.logger.info("Playlist ended"),r?.emit("playlist:ended",void 0))});r.onDestroy(()=>{d(),g()})},async destroy(){r?.logger.info("Playlist plugin destroying"),g(),r=null},add(t){const e=Array.isArray(t)?t:[t];if(e.forEach(t=>{const e={...t,id:t.id||N()},s=i.length;i.push(e),r?.emit("playlist:add",{track:e,index:s}),r?.logger.debug("Track added",{title:e.title,index:s})}),n){for(let t=i.length-e.length;t<i.length;t++){const e=Math.floor(Math.random()*(o.length-h(s)))+h(s)+1;o.splice(Math.min(e,o.length),0,t)}}g()},insert(t,e){const a={...e,id:e.id||N()},l=Math.max(0,Math.min(t,i.length));if(i.splice(l,0,a),s>=l&&s++,n){o=o.map(t=>t>=l?t+1:t);const t=Math.floor(Math.random()*o.length);o.splice(t,0,l)}r?.emit("playlist:add",{track:a,index:l}),g()},remove(t){let e;if("string"==typeof t){if(e=i.findIndex(e=>e.id===t),-1===e)return void r?.logger.warn("Track not found",{id:t})}else e=t;if(e<0||e>=i.length)return void r?.logger.warn("Invalid track index",{index:e});const[a]=i.splice(e,1);e<s?s--:e===s&&(s>=i.length&&(s=i.length-1),m()),n&&(o=o.filter(t=>t!==e).map(t=>t>e?t-1:t)),r?.emit("playlist:remove",{track:a,index:e}),g()},clear(){i=[],s=-1,o=[],r?.emit("playlist:clear",void 0),m()},play(t){let e;if(void 0===t)e=s>=0?s:n?d(0):0;else if("string"==typeof t){if(e=i.findIndex(e=>e.id===t),-1===e)return void r?.logger.warn("Track not found",{id:t})}else e=t;0!==i.length?p(e):r?.logger.warn("Playlist is empty")},next(){const t=f();t>=0?p(t):r?.logger.info("No next track")},previous(){if((r?.getState("currentTime")||0)>3)return void r?.emit("playback:seeking",{time:0});const t=(()=>{if(0===i.length)return-1;if("one"===a)return s;let t=h(s)-1;if(t<0){if("all"!==a)return-1;t=i.length-1}return d(t)})();t>=0?p(t):r?.logger.info("No previous track")},toggleShuffle(){this.setShuffle(!n)},setShuffle(t){n=t,t?l():o=[],r?.emit("playlist:shuffle",{enabled:t}),r?.logger.info("Shuffle mode",{enabled:t}),g()},cycleRepeat(){const t=["none","all","one"],e=(t.indexOf(a)+1)%t.length;this.setRepeat(t[e])},setRepeat(t){a=t,r?.emit("playlist:repeat",{mode:t}),r?.logger.info("Repeat mode",{mode:t}),g()},move(t,e){if(t<0||t>=i.length)return;if(e<0||e>=i.length)return;if(t===e)return;const[a]=i.splice(t,1);i.splice(e,0,a),s===t?s=e:t<s&&e>=s?s--:t>s&&e<=s&&s++,n&&l(),r?.emit("playlist:reorder",{tracks:[...i]}),g()},getState:()=>({tracks:[...i],currentIndex:s,currentTrack:s>=0?i[s]:null,shuffle:n,repeat:a,shuffleOrder:[...o],hasNext:u(),hasPrevious:c()}),getTracks:()=>[...i],getCurrentTrack:()=>s>=0?i[s]:null,getTrack:t=>i.find(e=>e.id===t)||null}}function U(t){const e=t.dataset,r={src:e.src,autoplay:void 0!==e.autoplay&&"false"!==e.autoplay,muted:void 0!==e.muted&&"false"!==e.muted,loop:void 0!==e.loop&&"false"!==e.loop,compact:void 0!==e.compact&&"false"!==e.compact,brandColor:e.brandColor,primaryColor:e.primaryColor,backgroundColor:e.backgroundColor,title:e.title,artist:e.artist,album:e.album,artwork:e.artwork||e.poster};if(e.playlist)try{r.playlist=JSON.parse(e.playlist)}catch(i){console.warn("[Scarlett Audio] Invalid playlist JSON")}return r}async function G(t,e){if(!e.src&&!e.playlist?.length)return console.error("[Scarlett Audio] No source URL or playlist provided"),null;try{t.style.position=t.style.position||"relative",e.compact?t.style.height=t.style.height||"64px":t.style.height=t.style.height||"120px",t.style.width=t.style.width||"100%";const r=[_(),F({title:e.title||e.playlist?.[0]?.title,artist:e.artist||e.playlist?.[0]?.artist,album:e.album,artwork:e.artwork||e.playlist?.[0]?.artwork})];e.playlist?.length&&r.push(B({items:e.playlist.map((t,e)=>({id:`track-${e}`,src:t.src,title:t.title,artist:t.artist,poster:t.artwork,duration:t.duration}))})),r.push(C({layout:e.compact?"compact":"full",theme:{primary:e.brandColor,text:e.primaryColor,background:e.backgroundColor}}));return await async function(t){const e=new g(t);return await e.init(),e}({container:t,src:e.src||e.playlist?.[0]?.src||"",autoplay:e.autoplay||!1,muted:e.muted||!1,loop:e.loop||!1,plugins:r})}catch(r){return console.error("[Scarlett Audio] Failed to create player:",r),null}}async function H(t){if(t.hasAttribute("data-scarlett-initialized"))return null;const e=U(t);t.setAttribute("data-scarlett-initialized","true");const r=await G(t,e);return r||t.removeAttribute("data-scarlett-initialized"),r}const V=["[data-scarlett-audio]","[data-audio-player]",".scarlett-audio"];async function K(){const t=V.join(", "),e=document.querySelectorAll(t),r=Array.from(e).map(t=>H(t));await Promise.all(r),e.length>0&&console.log(`[Scarlett Audio] Initialized ${e.length} player(s) (light build)`)}async function q(t){let e=null;if("string"==typeof t.container){if(e=document.querySelector(t.container),!e)return console.error(`[Scarlett Audio] Container not found: ${t.container}`),null}else e=t.container;return G(e,t)}const j={create:q,initAll:K,version:"0.1.2-audio-light"};"undefined"!=typeof window&&(window.ScarlettAudio=j),"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{K()}):K());const W=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},Y=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=z},z=Number.MAX_SAFE_INTEGER||9007199254740991;let X=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Q=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),J=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var Z="manifest",tt="level",et="audioTrack",rt="subtitleTrack",it={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class st{constructor(t,e=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}sample(t,e){const r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class nt{constructor(t,e,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 st(t),this.fast_=new st(e),this.defaultTTFB_=i,this.ttfb_=new st(t)}update(t,e){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==t&&(this.slow_=new st(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.fast_=new st(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new st(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){const r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(t){const e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,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 at(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var i=r.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ot(){return ot=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},ot.apply(null,arguments)}function lt(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,i)}return r}function dt(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?lt(Object(r),!0).forEach(function(e){at(t,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lt(Object(r)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))})}return t}class ht{constructor(t,e){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=`[${t}]:`;this.trace=ut,this.debug=e.debug.bind(null,r),this.log=e.log.bind(null,r),this.warn=e.warn.bind(null,r),this.info=e.info.bind(null,r),this.error=e.error.bind(null,r)}}const ut=function(){},ct={trace:ut,debug:ut,log:ut,warn:ut,info:ut,error:ut};function ft(){return ot({},ct)}function gt(t,e,r){return e[t]?e[t].bind(e):function(t,e){const r=self.console[t];return r?r.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):ut}(t,r)}const mt=ft();const pt=mt;function vt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var yt,Et;var Tt=Et?yt:(Et=1,yt={}),St=vt(Tt);function Lt(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function bt(t,e=!1){if("undefined"!=typeof TextDecoder){const r=new TextDecoder("utf-8").decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let i,s,n,a="",o=0;for(;o<r;){if(i=t[o++],0===i&&e)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=t[o++],a+=String.fromCharCode((31&i)<<6|63&s);break;case 14:s=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&n)}}return a}function At(t){let e="";for(let r=0;r<t.length;r++){let i=t[r].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function Rt(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var kt,_t={exports:{}};var Dt,wt,xt,It,Pt,Ct=(kt||(kt=1,Dt=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,wt=/^(?=([^\/?#]*))\1([^]*)$/,xt=/(?:\/|^)\.(?=\/)/g,It=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,_t.exports=Pt={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var i=Pt.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=Pt.normalizePath(i.path),Pt.buildURLFromParts(i)}var s=Pt.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=Pt.normalizePath(s.path),Pt.buildURLFromParts(s)):e;var n=Pt.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=wt.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=Pt.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?Pt.normalizePath(s.path):s.path),Pt.buildURLFromParts(o)},parseURL:function(t){var e=Dt.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(xt,"");t.length!==(t=t.replace(It,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}),_t.exports);class Mt{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 Ot="audio",Ft="video",$t="audiovideo";class Nt{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const r=Ht(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}(this,"stats")}setByteRange(t,e){const r=t.split("@",2);let i;i=1===r.length?(null==e?void 0:e.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={[Ot]:null,[Ft]:null,[$t]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Mt),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ct.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Ot]=null,t[Ft]=null,t[$t]=null}}function Bt(t){return"initSegment"!==t.sn}class Ut extends Nt{constructor(t,e){super(e),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=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(W(t)&&W(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const r=this._decryptdata=e[t[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=W(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){W(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Bt(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var r;const i=e[t];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,r,i,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:s,partial:n}}}class Gt extends Nt{constructor(t,e,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=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.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:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function Ht(t,e){const r=Object.getPrototypeOf(t);if(r){const t=Object.getOwnPropertyDescriptor(r,e);return t||Ht(r,e)}}const Vt=Math.pow(2,32)-1,Kt=[].push,qt={video:1,audio:2,id3:3,text:4};function jt(t){return String.fromCharCode.apply(null,t)}function Wt(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function Yt(t,e){const r=Xt(t,e);return r<0?4294967296+r:r}function zt(t,e){let r=Yt(t,e);return r*=Math.pow(2,32),r+=Yt(t,e+4),r}function Xt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Qt(t,e){const r=[];if(!e.length)return r;const i=t.byteLength;for(let s=0;s<i;){const n=Yt(t,s),a=n>1?s+n:i;if(jt(t.subarray(s+4,s+8))===e[0])if(1===e.length)r.push(t.subarray(s+8,a));else{const i=Qt(t.subarray(s+8,a),e.slice(1));i.length&&Kt.apply(r,i)}s=a}return r}function Jt(t){const e=[],r=t[0];let i=8;const s=Yt(t,i);i+=4;let n=0,a=0;0===r?(n=Yt(t,i),a=Yt(t,i+4),i+=8):(n=zt(t,i),a=zt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Wt(t,i);i+=2;for(let d=0;d<l;d++){let r=i;const n=Yt(t,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return pt.warn("SIDX has hierarchical references (not supported)"),null;const l=Yt(t,r);r+=4,e.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:e}}function Zt(t){const e=[],r=Qt(t,["moov","trak"]);for(let i=0;i<r.length;i++){const t=r[i],s=Qt(t,["tkhd"])[0];if(s){let r=s[0];const i=Yt(s,0===r?12:20),n=Qt(t,["mdia","mdhd"])[0];if(n){r=n[0];const s=Yt(n,0===r?12:20),a=Qt(t,["mdia","hdlr"])[0];if(a){const r=jt(a.subarray(8,12)),n={soun:Ot,vide:Ft}[r],o=te(Qt(t,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:s,type:n,stsd:o},e[n]=dt({timescale:s,id:i},o)):e[i]={timescale:s,type:r,stsd:o}}}}}return Qt(t,["moov","mvex","trex"]).forEach(t=>{const r=Yt(t,4),i=e[r];i&&(i.default={duration:Yt(t,12),flags:Yt(t,20)})}),e}function te(t){const e=t.subarray(8),r=e.subarray(86),i=jt(e.subarray(4,8));let s,n=i;const a="enca"===i||"encv"===i;if(a){const t=Qt(e,[i])[0];Qt(t.subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=Qt(t,["schm"])[0];if(e){const r=jt(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=Qt(t,["frma"])[0];e&&(n=jt(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Qt(r,["avcC"])[0];t&&t.length>3&&(n+="."+ie(t[1])+ie(t[2])+ie(t[3]),s=ee("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const t=Qt(e,[i])[0],r=Qt(t.subarray(28),["esds"])[0];if(r&&r.length>7){let t=4;if(3!==r[t++])break;t=re(r,t),t+=2;const e=r[t++];if(128&e&&(t+=2),64&e&&(t+=r[t++]),4!==r[t++])break;t=re(r,t);const i=r[t++];if(64!==i)break;if(n+="."+ie(i),t+=12,5!==r[t++])break;t=re(r,t);const s=r[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&r[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Qt(r,["hvcC"])[0];if(t&&t.length>12){const e=t[1],r=["","A","B","C"][e>>6],i=31&e,s=Yt(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+r+i,n+="."+function(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}s=ee("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ee(n,r)||n;break;case"vp09":{const t=Qt(r,["vpcC"])[0];if(t&&t.length>6){const e=t[4],r=t[5],i=t[6]>>4&15;n+="."+se(e)+"."+se(r)+"."+se(i)}break}case"av01":{const t=Qt(r,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,u=(8&t[2])>>3,c=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+se(i)+a+"."+se(d)+"."+h+"."+u+c+f+"."+se(g)+"."+se(m)+"."+se(p)+"."+v,s=ee("dav1",r)}break}}return{codec:n,encrypted:a,supplemental:s}}function ee(t,e){const r=Qt(e,["dvvC"]),i=r.length?r[0]:Qt(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return t+"."+se(e)+"."+se(r)}}function re(t,e){const r=e+5;for(;128&t[e++]&&e<r;);return e}function ie(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function se(t){return(t<10?"0":"")+t}function ne(t,e){Qt(t,["moov","trak"]).forEach(t=>{const r=Qt(t,["mdia","minf","stbl","stsd"])[0];if(!r)return;const i=r.subarray(8);let s=Qt(i,["enca"]);const n=s.length>0;n||(s=Qt(i,["encv"])),s.forEach(t=>{Qt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const r=function(t){const e=Qt(t,["schm"])[0];if(e){const r=jt(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=Qt(t,["schi","tenc"])[0];if(e)return e}}}(t);r&&e(r,n)})})})}function ae(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function oe(t,e){const r=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;return Qt(i,["moof"]).map(o=>{const l=o.byteOffset-8;Qt(o,["traf"]).map(o=>{const d=Qt(o,["tfdt"]).map(t=>{const e=t[0];let r=Yt(t,4);return 1===e&&(r*=Math.pow(2,32),r+=Yt(t,8)),r/s})[0];return void 0!==d&&(t=d),Qt(o,["tfhd"]).map(d=>{const h=Yt(d,4),u=16777215&Yt(d,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;h===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=Yt(d,p),p+=4),f&&(g=Yt(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=le(e.codec)),Qt(o,["trun"]).map(n=>{const o=n[0],d=16777215&Yt(n,0),h=!!(1&d);let u=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const L=Yt(n,4);let b=8;h&&(u=Yt(n,b),b+=4),f&&(b+=4);let A=u+l;for(let l=0;l<L;l++){if(m?(p=Yt(n,b),b+=4):p=c,v?(y=Yt(n,b),b+=4):y=g,E&&(b+=4),T&&(S=0===o?Yt(n,b):Xt(n,b),b+=4),e.type===Ft){let e=0;for(;e<y;){const n=Yt(i,A);if(A+=4,de(a,i[A])){he(i.subarray(A,A+n),a?2:1,t+S/s,r)}A+=n,e+=n+4}}t+=p/s}}))})})}),r}function le(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function de(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function he(t,e,r,i){const s=ue(t);let n=0;n+=e;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 t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){pt.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=Wt(s,e);if(e+=2,49===t){const t=Yt(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=s[e++]}i.push({type:t,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let r=0;r<16;r++){const i=s[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==r&&5!==r&&7!==r&&9!==r||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let r=0;r<n;r++)l[r]=s[e++];i.push({payloadType:a,pts:r,uuid:t.join(""),userData:bt(l),userDataBytes:l})}}}function ue(t){const e=t.byteLength,r=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return t;const s=e-r.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=t[a];return n}const ce=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),fe={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 ge(t,e){const r=fe[e];return!!r&&!!r[t.slice(0,4)]}function me(t,e,r=!0){return!t.split(",").some(t=>!pe(t,e,r))}function pe(t,e,r=!0){var i;const s=Lt(r);return null!=(i=null==s?void 0:s.isTypeSupported(ve(t,e)))&&i}function ve(t,e){return`${e}/mp4;codecs=${t}`}function ye(t){if(t){const e=t.substring(0,4);return fe.video[e]}return 2}function Ee(t){const e=ce();return t.split(",").reduce((t,r)=>{const i=e&&le(r)?9:fe.video[r];return i?(2*i+t)/(t?3:2):(fe.audio[r]+t)/(t?2:1)},0)}const Te={};const Se=/flac|opus|mp4a\.40\.34/i;function Le(t,e=!0){return t.replace(Se,t=>function(t,e=!0){if(Te[t])return Te[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<r.length;s++){var i;if(pe(r[s],"audio",e))return Te[t]=r[s],r[s];if("mp3"===r[s]&&null!=(i=Lt(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function be(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Ae(t,"audio")||Ae(t,"video")))return t;if(e){const r=e.split(",");if(r.length>1){if(t)for(let e=r.length;e--;)if(r[e].substring(0,4)===t.substring(0,4))return r[e];return r[0]}}return e||t}function Ae(t,e){return ge(t,e)&&pe(t,e)}function Re(t){if(t.startsWith("av01.")){const e=t.split("."),r=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=r[t-4];return e.join(".")}return t}function ke(t){const e=Lt(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function _e(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const De=["NONE","TYPE-0","TYPE-1",null];const we=["SDR","PQ","HLG"];var xe={No:"",Yes:"YES",v2:"v2"};function Ie(t){const{canSkipUntil:e,canSkipDateRanges:r,age:i}=t;return e&&i<e/2?r?xe.v2:xe.Yes:xe.No}class Pe{constructor(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Ce{constructor(t){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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const r=null==(e=t.supplemental)?void 0:e.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return Me(this._audioGroups,t)}hasSubtitleGroup(t){return Me(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Me(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Oe(t,e){let r=!1,i=[];if(t&&(r="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||we.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;r=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),r||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}const Fe=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(r,i)=>{if(t&&(i=t(r,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function $e(t,e){pt.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ne(t){return t.reduce((t,e)=>{let r=t.groups[e.groupId];r||(r=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(e);const i=e.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||e.default,r.hasAutoSelect=r.hasAutoSelect||e.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Be(t,e){var r;return!!t&&t!==(null==(r=e.loadLevelObj)?void 0:r.uri)}class Ue extends ht{constructor(t){super("abr",t.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=t=>{var e;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,m=!!t||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=s.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*y)*1e3))return;const E=p?p.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,L=this.getBwEstimate(),b=s.levels,A=b[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/L));const _=S?1e3*l.loaded/k:0,D=v/1e3,w=_?(R-l.loaded)/_:8*R/L+D;if(w<=E)return;const x=_?8*_:L,I=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),P=this.hls.config.abrBandWidthUpFactor;let C,M=Number.POSITIVE_INFINITY;for(C=c-1;C>u;C--){const t=b[C].maxBitrate,e=!b[C].details||I;if(M=this.getTimeToLoadFrag(D,x,d*t,e),M<Math.min(E,d+D))break}if(M>=w)return;if(M>10*d)return;S?this.bwEstimator.sample(h-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(h);const O=b[C].maxBitrate;this.getBwEstimate()*P>O&&this.resetEstimator(O);const F=this.findBestLevel(O,u,C,0,E,1,1);F>-1&&(C=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: ${w.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: ${W(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${C} @ ${0|O} bps`),s.nextLoadLevel=s.nextAutoLevel=C,this.clearTimer();const $=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===C&&C>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${C>0?"and switching down":""}\n Fragment duration: ${r.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,C>u){let e=this.findBestLevel(this.hls.levels[u].bitrate,u,C,0,t,1,1);-1===e&&(e=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};g||w>2*M?$():this.timer=self.setInterval($,1e3*M),s.trigger(J.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new nt(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.FRAG_LOADING,this.onFragLoading,this),t.on(J.FRAG_LOADED,this.onFragLoaded,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.FRAG_LOADING,this.onFragLoading,this),t.off(J.FRAG_LOADED,this.onFragLoaded,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(J.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){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(t,e){const r=e.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case Q.BUFFER_ADD_CODEC_ERROR:case Q.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Q.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:r,partCurrent:i}=this;if(t&&r&&t.sn===r.sn&&t.level===r.level){const e=performance.now(),r=i?i.stats:t.stats,s=e-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),r.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,r,i){return t+r/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const r=this.hls.config,{loading:i}=e.stats,s=i.end-i.first;W(s)&&(this.lastLevelLoadSec=s/1e3),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:r}){const i=r?r.stats:e.stats;if(e.type===it.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=r?r.duration:e.duration,s=this.hls.levels[e.level],n=(s.loaded?s.loaded.bytes:0)+i.loaded,a=(s.loaded?s.loaded.duration:0)+t;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:r,id:e.type};this.onFragBuffered(J.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:r,part:i}=e,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(t){return t.type!==it.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,r=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,e,t,0,i,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);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 t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:i,config:s,minAutoLevel:n}=r,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=s.abrBandWidthFactor,h=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}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 t=this.hls,e=t.media;if(!e)return 1/0;const r=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,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:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===d;let T,S="SDR",L=(null==v?void 0:v.frameRate)||0;const{audioPreference:b,videoPreference:A}=p;this.audioTracksByGroup||(this.audioTracksByGroup=Ne(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,r,i){return t.slice(r,i+1).reduce((t,e,r)=>{if(!e.codecSet)return t;const i=e.audioGroups;let s=t[e.codecSet];s||(t[e.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,e.bitrate);const n=Math.min(e.height,e.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,e.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,e.score),s.fragmentError+=e.fragmentError,s.videoRanges[e.videoRange]=(s.videoRanges[e.videoRange]||0)+1,t},{})}(f,0,e,r)),s=function(t,e,r,i,s){const n=Object.keys(t),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,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Oe(e,s);for(let b=n.length;b--;){const e=t[n[b]];h||(h=e.channels[2]>0),c=Math.min(c,e.minHeight),f=Math.min(f,e.minFramerate),g=Math.min(g,e.minBitrate),E.filter(t=>e.videoRanges[t]>0).length>0&&(u=!0)}c=W(c)?c:0,f=W(f)?f:0;const T=Math.max(1080,c),S=Math.max(30,f);g=W(g)?g:r,r=Math.max(g,r),u||(e=void 0);const L=n.length>1;return{codecSet:n.reduce((e,i)=>{const s=t[i];if(i===e)return e;if(v=u?E.filter(t=>s.videoRanges[t]>0):[],L){if(s.minBitrate>r)return $e(i,`min bitrate of ${s.minBitrate} > current estimate of ${r}`),e;if(!s.hasDefaultAudio)return $e(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return $e(i,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!s.channels[a])return $e(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),e}else if((!o||d)&&h&&0===s.channels[2])return $e(i,"no renditions with stereo sound found"),e;if(s.minHeight>T)return $e(i,`min resolution of ${s.minHeight} > maximum of ${T}`),e;if(s.minFramerate>S)return $e(i,`min framerate of ${s.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>s.videoRanges[t]>0))return $e(i,`no variants with VIDEO-RANGE of ${Fe(v)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return $e(i,`video codec preference "${l}" not found`),e;if(s.maxScore<p)return $e(i,`max score of ${s.maxScore} < selected max of ${p}`),e}return e&&(Ee(i)>=Ee(e)||s.fragmentError>t[e].fragmentError)?e:(m=s.minIndex,p=s.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(i,S,t,b,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],L=o,t=Math.max(t,l),this.log(`picked start tier ${Fe(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,_=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let x=r;x>=e;x--){var w;const e=f[x],o=x>h;if(!e)continue;if((T&&e.codecSet!==T||S&&e.videoRange!==S||o&&L>e.frameRate||!o&&L>0&&L<e.frameRate||null!=(w=e.supportedResult)&&null!=(w=w.decodingInfoResults)&&w.some(t=>!1===t.smooth))&&(!E||x!==R)){D.push(x);continue}const u=e.details,g=(c?null==u?void 0:u.partTarget:null==u?void 0:u.averagetargetduration)||k;let p;p=o?a*t:n*t;const v=k&&i>=2*k&&0===s?e.averageBitrate:e.maxBitrate,b=this.getTimeToLoadFrag(_,p,v*g,void 0===u);if(p>=v&&(x===d||0===e.loadError&&0===e.fragmentError)&&(b<=_||!W(b)||y&&!this.bitrateTestDelay||b<l)){const t=this.forcedAutoLevel;return x===m||-1!==t&&t===m||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[D[0]].codecs}" ${f[D[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${x} adjustedbw(${Math.round(p)})-bitrate=${Math.round(p-v)} ttfb:${_.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${b.toFixed(1)} firstSelection:${E} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=x),x}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),e)}}const Ge=function(t,e){let r=0,i=t.length-1,s=null,n=null;for(;r<=i;){s=(r+i)/2|0,n=t[s];const a=e(n);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function He(t,e,r=0,i=0,s=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-r;i>0&&i<15e-7&&(r+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===r&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Ve(r,i,n)||function(t,e,r){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),r);return t.start<=i}return!1}(n,t,Math.min(s,i))))return n;const a=Ge(e,Ve.bind(null,r,i));return!a||a===t&&n?n:a}function Ve(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function Ke(t,e,r){const i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function qe(t){switch(t.details){case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_TIMEOUT:case Q.LEVEL_LOAD_TIMEOUT:case Q.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function je(t){return t.details.startsWith("key")}function We(t){return je(t)&&!!t.frag&&!t.frag.decryptdata}function Ye(t,e){const r=qe(e);return t.default[(r?"timeout":"error")+"Retry"]}function ze(t,e){const r="linear"===t.backoff?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Xe(t){return dt(dt({},t),{errorRetry:null,timeoutRetry:null})}function Qe(t,e,r,i){if(!t)return!1;const s=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return Je(t)||!!t&&(t<400||t>499)}(s)||!!r);return t.shouldRetry?t.shouldRetry(t,e,r,i,n):n}function Je(t){return 0===t&&!1===navigator.onLine}var Ze={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},tr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class er extends ht{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(J.ERROR,this.onError,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(J.ERROR,this.onError,this),t.off(J.ERROR,this.onErrorOut,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===it.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,r=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===r?e.loadLevel:r}variantHasKey(t,e){if(t){var r;if(null!=(r=t.details)&&r.hasKey(e))return!0;const i=t.audioGroups;if(i){return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var r;return null==(r=t.details)?void 0:r.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var r;if(e.fatal)return;const i=this.hls,s=e.context;switch(e.details){case Q.FRAG_LOAD_ERROR:case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_ERROR:case Q.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Q.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction=rr());case Q.FRAG_GAP:case Q.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ze.SendAlternateToPenaltyBox);case Q.LEVEL_EMPTY_ERROR:case Q.LEVEL_PARSING_ERROR:{var n;const t=e.parent===it.MAIN?e.level:i.loadLevel;e.details===Q.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Q.LEVEL_LOAD_ERROR:case Q.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case Q.AUDIO_TRACK_LOAD_ERROR:case Q.AUDIO_TRACK_LOAD_TIMEOUT:case Q.SUBTITLE_LOAD_ERROR:case Q.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const t=i.loadLevelObj;if(t&&(s.type===et&&t.hasAudioGroup(s.groupId)||s.type===rt&&t.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Ze.SendAlternateToPenaltyBox,void(e.errorAction.flags=tr.MoveAllAlternatesMatchingHost)}return;case Q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Ze.SendAlternateToPenaltyBox,flags:tr.MoveAllAlternatesMatchingHDCP});case Q.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Q.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Q.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Ze.SendAlternateToPenaltyBox,flags:tr.MoveAllAlternatesMatchingKey});case Q.BUFFER_ADD_CODEC_ERROR:case Q.REMUX_ALLOC_ERROR:case Q.BUFFER_APPEND_ERROR:var a;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:i.loadLevel);return;case Q.INTERNAL_EXCEPTION:case Q.BUFFER_APPENDING_ERROR:case Q.BUFFER_FULL_ERROR:case Q.LEVEL_SWITCH_ERROR:case Q.BUFFER_STALLED_ERROR:case Q.BUFFER_SEEK_OVER_HOLE:case Q.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=rr())}e.type===X.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=rr())}getPlaylistRetryOrSwitchAction(t,e){const r=Ye(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(Qe(r,i,qe(t),t.response))return{action:Ze.RetryRequest,flags:tr.None,retryConfig:r,retryCount:i};const s=this.getLevelSwitchAction(t,e);return r&&(s.retryConfig=r,s.retryCount=i),s}getFragRetryOrSwitchAction(t){const e=this.hls,r=this.getVariantLevelIndex(t.frag),i=e.levels[r],{fragLoadPolicy:s,keyLoadPolicy:n}=e.config,a=Ye(je(t)?n:s,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==Q.FRAG_GAP&&i.fragmentError++,!We(t))){if(Qe(a,o,qe(t),t.response))return{action:Ze.RetryRequest,flags:tr.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const r=this.hls;null==e&&(e=r.loadLevel);const i=this.hls.levels[e];if(i){var s,n;const e=t.details;i.loadError++,e===Q.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=t.frag)?void 0:s.type,g=(f===it.AUDIO&&e===Q.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===Q.BUFFER_ADD_CODEC_ERROR||e===Q.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:t})=>i.audioCodec!==t),m="video"===t.sourceBufferName&&(e===Q.BUFFER_ADD_CODEC_ERROR||e===Q.BUFFER_APPEND_ERROR)&&d.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:p,groupId:v}=null!=(n=t.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(e===Q.FRAG_GAP&&f===it.MAIN&&t.frag){const e=d[s].details;if(e){const r=He(t.frag,e.fragments,t.frag.start);if(null!=r&&r.gap)continue}}else{if(p===et&&r.hasAudioGroup(v)||p===rt&&r.hasSubtitleGroup(v))continue;if(f===it.AUDIO&&null!=(a=i.audioGroups)&&a.some(t=>r.hasAudioGroup(t))||f===it.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(t=>r.hasSubtitleGroup(t))||g&&i.audioCodec===r.audioCodec||m&&i.codecSet===r.codecSet||!g&&i.codecSet!==r.codecSet)continue}l=s;break}}if(l>-1&&r.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ze.SendAlternateToPenaltyBox,flags:tr.None,nextAutoLevel:l}}return{action:Ze.SendAlternateToPenaltyBox,flags:tr.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var r;switch(null==(r=e.errorAction)?void 0:r.action){case Ze.DoNothing:break;case Ze.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Q.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,r=t.errorAction;if(!r)return;const{flags:i}=r,s=r.nextAutoLevel;switch(i){case tr.None:this.switchLevel(t,s);break;case tr.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(t.frag),s=e.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){e.maxHdcpLevel=De[De.indexOf(n)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case tr.MoveAllAlternatesMatchingKey:{const e=t.decryptdata;if(e){const i=this.hls.levels,s=i.length;for(let r=s;r--;){var n,a;if(this.variantHasKey(i[r],e))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=t.frag)?void 0:a.type} fragment) ${At(e.keyId||[])}`),i[r].fragmentError++,i[r].loadError++,this.log(`Removing level ${r} with key error (${t.error})`),this.hls.removeLevel(r)}const o=t.frag;if(this.hls.levels.length<s)r.resolved=!0;else if(o&&o.type!==it.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===Q.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=_e(t.mimeType),r=this.hls.levels;for(let i=r.length;i--;)r[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}}function rr(t){const e={action:Ze.DoNothing,flags:tr.None};return t&&(e.resolved=!0),e}const ir=/^(\d+)x(\d+)$/,sr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class nr{constructor(t,e){"string"==typeof t&&(t=nr.parseAttrList(t,e)),ot(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const r=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)r[t]=parseInt(e.slice(2*t,2*t+2),16);return r}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const r=this[t];return r?parseFloat(r):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ir.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let r;const i={};for(sr.lastIndex=0;null!==(r=sr.exec(t));){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(e&&(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":pt.warn(`${t}: attribute ${s} is missing quotes`)}i[s]=n}return i}}function ar(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function or(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class lr{constructor(t,e,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==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:r,e){const r=e.attr;for(const e in r)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==r[e]){pt.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=ot(new nr({}),r,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);W(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(pt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(W(t))return t}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&&W(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 dr{constructor(t){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=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let r=e.decryptdata;return r||(e.setKeyFormat(t.keyFormat),r=e.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return!!this.fragments.length&&W(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let r=t.length;r--;)if(t[r].index>e)return t[r].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function hr(t,e){return t.length===e.length&&!t.some((t,r)=>t!==e[r])}function ur(t,e){return!t&&!e||!(!t||!e)&&hr(t,e)}var cr=0,fr=1;function gr(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function mr(t){switch(t){case"AES-128":case"AES-256":return cr;case"AES-256-CTR":return fr;default:throw new Error(`invalid full segment method ${t}`)}}let pr={};class vr{static clearKeyUriToKeyIdMap(){pr={}}static setKeyIdForUri(t,e){pr[t]=e}static addKeyIdForUri(t){const e=Object.keys(pr).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,e),pr[t]=r,r}constructor(t,e,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=t,this.uri=e,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!gr(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Rt(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&hr(t.keyFormatVersions,this.keyFormatVersions)&&ur(t.iv,this.iv)&&ur(t.keyId,this.keyId)}isSupported(){if(this.method){if(gr(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(gr(this.method)){let e=this.iv;e||("number"!=typeof t&&(pt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}(t));return new vr(this.method,this.uri,"identity",this.keyFormatVersions,e)}return this}}const yr=/#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,Er=/#EXT-X-MEDIA:(.*)/g,Tr=/^#EXT(?:INF|-X-TARGETDURATION):/m,Sr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Lr=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 br{static findGroup(t,e){for(let r=0;r<t.length;r++){const i=t[r];if(i.id===e)return i}}static resolve(t,e){return Ct.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Tr.test(t)}static parseMasterPlaylist(t,e){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(yr.lastIndex=0,!t.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let s;for(;null!=(s=yr.exec(t));)if(s[1]){var n;const t=new nr(s[1],r),a=s[2],o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:br.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Dr(t.CODECS,o);const d=t["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},Dr(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),r.levels.push(o)}else if(s[3]){const t=s[3],i=s[4];switch(t){case"SESSION-DATA":{const t=new nr(i,r),e=t["DATA-ID"];e&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[e]=t);break}case"SESSION-KEY":{const t=kr(i,e,r);t.encrypted&&t.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(t)):pt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const t=new nr(i,r);r.contentSteering={uri:br.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=_r(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(t,e,r){let i;const s={},n=r.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Er.lastIndex=0;null!==(i=Er.exec(t));){const t=new nr(i[1],r),n=t.TYPE;if(n){const r=a[n],i=s[n]||[];s[n]=i;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,u=t.CHARACTERISTICS,c=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?br.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=r&&r.length){const t=br.findGroup(r,f.groupId)||r[0];wr(f,t,"audioCodec"),wr(f,t,"textCodec")}i.push(f)}}return s}static parseLevelPlaylist(t,e,r,i,s,n){var a;const o={url:e},l=new dr(e),d=l.fragments,h=[];let u,c,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,L=new Ut(i,o),b=-1,A=!1,R=null;if(Sr.lastIndex=0,l.m3u8=t,l.hasVariableRefs=!1,"#EXTM3U"!==(null==(a=Sr.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=Sr.exec(t));){A&&(A=!1,L=new Ut(i,o),L.playlistOffset=y,L.setStart(y),L.sn=p,L.cc=E,T&&(L.bitrate=T),L.level=r,m&&(L.initSegment=m,m.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(L.setByteRange(R),R=null)));const t=u[1];if(t){L.duration=parseFloat(t);const e=(" "+u[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(W(L.duration)){L.playlistOffset=y,L.setStart(y),f&&Pr(L,f,l),L.sn=p,L.level=r,L.cc=E,d.push(L);const t=(" "+u[3]).slice(1);L.relurl=t,xr(L,S,h),S=L,y+=L.duration,p++,v=0,A=!0}}else{if(u=u[0].match(Lr),!u){pt.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<u.length&&void 0===u[c];c++);const t=(" "+u[c]).slice(1),s=(" "+u[c+1]).slice(1),n=u[c+2]?(" "+u[c+2]).slice(1):null;switch(t){case"BYTERANGE":S?L.setByteRange(s,S):L.setByteRange(s);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=s,L.tagList.push(["PROGRAM-DATE-TIME",s]),-1===b&&(b=d.length);break;case"PLAYLIST-TYPE":l.type&&Cr(l,t,u),l.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Cr(l,t,u):d.length>0&&Mr(l,t,u),p=l.startSN=parseInt(s);break;case"SKIP":{l.skippedSegments&&Cr(l,t,u);const e=new nr(s,l),r=e.decimalInteger("SKIPPED-SEGMENTS");if(W(r)){l.skippedSegments+=r;for(let t=r;t--;)d.push(null);p+=r}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Cr(l,t,u),l.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==l.version&&Cr(l,t,u),l.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":l.live||Cr(l,t,u),l.live=!1;break;case"#":(s||n)&&L.tagList.push(n?[s,n]:[s]);break;case"DISCONTINUITY":E++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,s]),T=1e3*parseInt(s),W(T)?L.bitrate=T:T=0;break;case"DATERANGE":{const t=new nr(s,l),e=new lr(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:pt.warn(`Ignoring invalid DATERANGE tag: "${s}"`),L.tagList.push(["EXT-X-DATERANGE",s]);break}case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Cr(l,t,u):d.length>0&&Mr(l,t,u),l.startCC=E=parseInt(s);break;case"KEY":{const t=kr(s,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=ot({},f)),f[t.keyFormat]=t)}else pt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${s}" (light build)`);break}case"START":l.startTimeOffset=_r(s);break;case"MAP":{const t=new nr(s,l);if(L.duration){const e=new Ut(i,o);Ir(e,t,r,f),m=e,L.initSegment=m,m.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime)}else{const e=L.byteRangeEndOffset;if(e){const t=L.byteRangeStartOffset;R=`${e-t}@${t}`}else R=null;Ir(L,t,r,f),m=L,A=!0}m.cc=E;break}case"SERVER-CONTROL":g&&Cr(l,t,u),g=new nr(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&&Cr(l,t,u);const e=new nr(s);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,r=v++,i=new nr(s,l),n=new Gt(i,L,o,r,e);t.push(n),L.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new nr(s,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new nr(s,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:pt.warn(`line parsed but not handled: ${u}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(xr(L,S,h),L.cc=E,l.fragmentHint=L,f&&Pr(L,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=d.length,_=d[0],D=d[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&D){l.averagetargetduration=y/k;const t=D.sn;l.endSN="initSegment"!==t?t:0,l.live||(D.endList=!0),b>0&&(!function(t,e){let r=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=r.programDateTime-1e3*e.duration,r=e}}(d,b),_&&h.unshift(_))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&_&&Ar(h,l),l.endCC=E,l}}function Ar(t,e){let r=t.length;if(!r){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),r++}}const i=t[r-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=r;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const r=Rr(e,d,t,i,s);if(-1!==r){l.tagAnchor=e.fragments[r].ref;break}}}}function Rr(t,e,r,i,s){const n=r[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){const s=r[i].sn-t.startSN;if(s<0)return-1;const n=t.fragments;if(n.length>r.length){for(let a=(r[i+1]||n[n.length-1]).sn-t.startSN;a>s;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return s}}}return-1}function kr(t,e,r){var i,s;const n=new nr(t,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&&pt.error(`Invalid IV: ${n.IV}`);const u=o?br.resolve(o,e):"",c=(d||"1").split("/").map(Number).filter(Number.isFinite);return new vr(a,u,h,c,l,n.KEYID)}function _r(t){const e=new nr(t).decimalFloatingPoint("TIME-OFFSET");return W(e)?e:null}function Dr(t,e){let r=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const i=r.filter(e=>ge(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),r=r.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=r}function wr(t,e,r){const i=e[r];i&&(t[r]=i)}function xr(t,e,r){t.rawProgramDateTime?r.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Ir(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function Pr(t,e,r){t.levelkeys=e;const{encryptedFragments:i}=r;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function Cr(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function Mr(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function Or(t,e){const r=e.startPTS;if(W(r)){let i,s=0;e.sn>t.sn?(s=r-t.start,i=t):(s=t.start-r,i=e),i.duration!==s&&i.setDuration(s)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function Fr(t,e,r,i,s,n,a){i-r<=0&&(a.warn("Fragment should have a positive duration",e),i=r+e.duration,n=s+e.duration);let o=r,l=i;const d=e.startPTS,h=e.endPTS;if(W(d)){const u=Math.abs(d-r);t&&u>t.totalduration?a.warn(`media timestamps and playlist times differ by ${u}s for level ${e.level} ${t.url}`):W(e.deltaPTS)?e.deltaPTS=Math.max(u,e.deltaPTS):e.deltaPTS=u,o=Math.max(r,d),r=Math.min(r,d),s=void 0!==e.startDTS?Math.min(s,e.startDTS):s,l=Math.min(i,h),i=Math.max(i,h),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const u=r-e.start;0!==e.start&&e.setStart(r),e.setDuration(i-e.start),e.startPTS=r,e.maxStartPTS=o,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const c=e.sn;if(!t||c<t.startSN||c>t.endSN)return 0;let f;const g=c-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)Or(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Or(m[f],m[f+1]);return t.fragmentHint&&Or(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function $r(t,e,r){if(t===e)return;let i=null;const s=t.fragments;for(let h=s.length-1;h>=0;h--){const t=s[h].initSegment;if(t){i=t;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,r){const i=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=s;d<=n;d++){const s=l[a+d];let n=o[d];if(i&&!n&&s&&(n=e.fragments[d]=s),s&&n){r(s,n,d,o);const i=s.relurl,a=n.relurl;if(i&&qr(i,a))return void(e.playlistParsingError=Nr(`media sequence mismatch ${n.sn}:`,t,e,s,n));if(s.cc!==n.cc)return void(e.playlistParsingError=Nr(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,t,e,s,n))}}}(t,e,(t,r,s,a)=>{if((!e.startCC||e.skippedSegments)&&r.cc!==t.cc){const i=t.cc-r.cc;for(let t=s;t<a.length;t++)a[t].cc+=i;e.endCC=a[a.length-1].cc}W(t.startPTS)&&W(t.endPTS)&&(r.setStart(r.startPTS=t.startPTS),r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.setDuration(t.endPTS-t.startPTS),r.duration&&(n=r),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(r.elementaryStreams=t.elementaryStreams),r.loader=t.loader,t.hasStats&&(r.stats=t.stats),t.initSegment&&(r.initSegment=t.initSegment,i=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,r){const{dateRanges:i,recentlyRemovedDateranges:s}=e,n=ot({},t);s&&s.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(t=>{const e=n[t],s=new lr(i[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Fe(i[t].attr)}"`)}),n}(t.dateRanges,e,r));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&xr(o[t],o[t-1],i);Ar(i,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const r=Gr(t,e.startSN-1);e.startCC=null!=(l=null==r?void 0:r.cc)?l:a[0].cc}!function(t,e,r){if(t&&e){let i=0;for(let s=0,n=t.length;s<=n;s++){const n=t[s],a=e[s+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),n?Fr(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,r):Br(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function Nr(t,e,r,i,s){return new Error(`${t} ${s.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function Br(t,e,r=!0){const i=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,n=i>=0;let a=0;if(n&&i<s.length)a=s[i].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&r)a=t.fragmentStart+i*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}!function(t,e){if(e){const r=t.fragments;for(let i=t.skippedSegments;i<r.length;i++)r[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,a)}function Ur(t,e=1/0){let r=1e3*t.targetduration;if(t.updated){const i=t.fragments,s=4;if(i.length&&r*s>e){const t=1e3*i[i.length-1].duration;t<r&&(r=t)}}else r/=2;return Math.round(r)}function Gr(t,e,r){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:e<t.startSN&&r&&r.sn===e?r:null)}function Hr(t,e,r){return t?Vr(t.partList,e,r):null}function Vr(t,e,r){if(t)for(let i=t.length;i--;){const s=t[i];if(s.index===r&&s.fragment.sn===e)return s}return null}function Kr(t){t.forEach((t,e)=>{var r;null==(r=t.details)||r.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function qr(t,e){return!(t===e||!e)&&jr(t)!==jr(e)}function jr(t){return t.replace(/\?[^?]*$/,"")}class Wr extends ht{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}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(t,e,r){const i=null==e?void 0:e.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,e.url).href}catch(s){this.warn(`Could not construct new URL for Rendition Report: ${s}`),o=a.URI||""}if(o===t){n=r;break}o===t.substring(0,o.length)&&(n=r)}if(-1!==n){const t=i[n],s=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=r&&Ie(r);return new Pe(s,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,e,r){const{details:i,stats:s}=e,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 t=Math.max(o||0,0);i.appliedTimelineOffset=t,i.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(i.live||null!=r&&r.live){const o="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(r),r&&i.fragments.length>0){$r(r,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void r.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.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=Ur(i,1e3*(i.edge-h));if(i.requestScheduled+u<n?i.requestScheduled=n:i.requestScheduled+=u,this.log(`live playlist ${t} ${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 t=this.hls.config.lowLatencyMode,s=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,d=s===a;-1!==l?d?(f=a+1,g=t?0:l):(f=s,g=t?l+1:i.maxPartIndex):f=a+1;const h=i.age,u=h+i.ageHeader;let m=Math.min(u-i.partTarget,1.5*i.targetduration);if(m>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: ${m} with playlist age: ${i.age}`),m=0;else{const t=Math.floor(m/i.targetduration);if(f+=t,void 0!==g){g+=Math.round(m%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${t} to part ${g}`)}i.tuneInGoal=m}if(c=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g),t||!d)return i.requestScheduled=n,void this.loadingPlaylist(o,c)}else(i.canBlockReload||i.canSkipUntil)&&(c=this.getDeliveryDirectives(i,e.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(t,e,r){const i=r||t.details;if(!i)return void this.loadingPlaylist(t,e);const s=self.performance.now(),n=i.requestScheduled;if(s>=n)return void this.loadingPlaylist(t,e);const a=n-s;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,r,i){let s=Ie(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,i=e.part,s=xe.No),new Pe(r,i,s)}checkRetry(t){const e=t.details,r=qe(t),i=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(s===Ze.RetryRequest||!i.resolved&&s===Ze.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(r&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=ze(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}}var Yr="NOT_LOADED",zr="APPENDING",Xr="PARTIAL",Qr="OK";class Jr{constructor(t){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=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.BUFFER_APPENDED,this.onBufferAppended,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.BUFFER_APPENDED,this.onBufferAppended,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const r=this.activePartLists[e];if(r)for(let i=r.length;i--;){const e=r[i];if(!e)break;if(e.start<=t&&t<=e.end&&e.loaded)return e}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,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)===e&&(!r||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,r,i,s){this.timeRanges&&(this.timeRanges[t]=e);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[t];o&&(0!==o.time.length?o.time.some(t=>{const r=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&this.removeFragment(a.body),r}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const r=t.frag,i=ti(r),s=this.fragments[i];if(!s||s.buffered&&r.gap)return;const n=!r.relurl;Object.keys(e).forEach(i=>{const a=r.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;s.range[i]=this.getBufferedTimes(r,t.part,l,o)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),Zr(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const r=this.activePartLists[e];r&&(this.activePartLists[e]=ei(r,e=>e.fragment.sn>=t))}fragBuffered(t,e){const r=ti(t);let i=this.fragments[r];!i&&e&&(i=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t))}getBufferedTimes(t,e,r,i){const s={time:[],partial:r},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let d=0;d<i.length;d++){const t=i.start(d)-this.bufferPadding,e=i.end(d)+this.bufferPadding;if(l>=t&&o<=e){s.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(n<e&&a>t){const t=Math.max(n,i.start(d)),e=Math.min(a,i.end(d));e>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:e}))}else if(a<=t)break}return s}getPartialFragment(t){let e,r,i,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Zr(d)&&(r=d.body.start-a,i=d.body.end+a,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(s=d.body,n=e)))}),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Zr(e))}getState(t){const e=ti(t),r=this.fragments[e];return r?r.buffered?Zr(r)?Xr:Qr:zr:Yr}isTimeBuffered(t,e,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,t>=i&&e<=s)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const r=e.frag,i=e.part?null:e,s=ti(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:r,part:i,timeRanges:s,type:n}=e;if("initSegment"===r.sn)return;const a=r.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ti(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,r=Object.keys(e);if(!t)return r.length>0;for(let i=r.length;i--;){const s=e[r[i]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,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<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)})}removeFragment(t){const e=ti(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const e=t.sn;this.activePartLists[t.type]=ei(r,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Zr(t){var e,r,i;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(r=t.range.audio)&&r.partial||null!=(i=t.range.audiovideo)&&i.partial)}function ti(t){return`${t.type}_${t.level}_${t.sn}`}function ei(t,e){return t.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}class ri{constructor(t,e,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=r}decrypt(t,e){switch(this.aesMode){case cr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case fr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class ii{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_(t){const e=new DataView(t),r=new Uint32Array(4);for(let i=0;i<4;i++)r[i]=e.getUint32(4*i);return r}initTable(){const t=this.sBox,e=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,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,t[f]=r,e[r]=f;const o=c[f],m=c[o],p=c[m];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*p^65537*m^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[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let r=!0,i=0;for(;i<e.length&&r;)r=e[i]===this.key[i],i++;if(r)return;this.key=e;const s=this.keySize=e.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],m=c[2],p=c[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=e[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]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,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],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,L,b,A,R,k,_,D,w,x,I;const P=this.networkToHostOrderSwap;for(;e<p.length;){for(k=P(p[e]),_=P(p[e+1]),D=P(p[e+2]),w=P(p[e+3]),L=k^s[0],b=w^s[1],A=D^s[2],R=_^s[3],x=4,I=1;I<i;I++)y=o[L>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&R]^s[x],E=o[b>>>24]^l[A>>16&255]^d[R>>8&255]^h[255&L]^s[x+1],T=o[A>>>24]^l[R>>16&255]^d[L>>8&255]^h[255&b]^s[x+2],S=o[R>>>24]^l[L>>16&255]^d[b>>8&255]^h[255&A]^s[x+3],L=y,b=E,A=T,R=S,x+=4;y=n[L>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^s[x],E=n[b>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&L]^s[x+1],T=n[A>>>24]<<24^n[R>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^s[x+2],S=n[R>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^s[x+3],v[e]=P(y^c),v[e+1]=P(S^f),v[e+2]=P(T^g),v[e+3]=P(E^m),c=k,f=_,g=D,m=w,e+=4}return v.buffer}}class si{constructor(t,e,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=r}expandKey(){const t=function(t){switch(t){case cr:return"AES-CBC";case fr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class ni{constructor(t,{removePKCS7Padding:e=!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=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const r=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,r,i){return this.useSoftware?new Promise((s,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,r,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,r,i)}softwareDecrypt(t,e,r,i){const{currentIV:s,currentResult:n,remainderData:a}=this;if(i!==cr||16!==e.byteLength)return pt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=ae(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ii),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,r,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,r,i));this.key=e,this.fastAesKey=new si(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ri(this.subtle,new Uint8Array(r),i).decrypt(t.buffer,e)}).catch(s=>(pt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,r,i)))}onWebCryptoError(t,e,r,i){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,r,i);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const r=t.length-t.length%16;return r!==t.length&&(e=t.slice(0,r),this.remainderData=t.slice(r)),e}logOnce(t){this.logEnabled&&(pt.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ai=Math.pow(2,17);class oi{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const r=t.url;if(!r)return Promise.reject(new hi({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,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(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void o(di(t));t.gap=!1}const l=this.loader=s?new s(i):new n(i),d=li(t);t.loader=l;const h=Xe(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:ai};t.stats=l.stats;const c={onSuccess:(e,r,i,s)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,i,s,n)=>{this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:dt({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:n}))},onAbort:(e,r,i)=>{this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,r,i)=>{this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:i,stats:e}))}};e&&(c.onProgress=(r,i,s,n)=>e({frag:t,part:null,payload:s,networkDetails:n})),l.load(d,u,c)})}loadPart(t,e,r){this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(di(t,e));const l=this.loader=s?new s(i):new n(i),d=li(t,e);t.loader=l;const h=Xe(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ai};e.stats=l.stats,l.load(d,u,{onSuccess:(i,s,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:i.data,networkDetails:o};r(d),a(d)},onError:(r,i,s,n)=>{this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:dt({url:d.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:n}))},onAbort:(r,i,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,i,s)=>{this.resetLoader(t,l),o(new hi({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:r}))}})})}updateStatsFromPart(t,e){const r=t.stats,i=e.stats,s=i.total;if(r.loaded+=i.loaded,s){const i=Math.round(t.duration/e.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(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function li(t,e=null){const r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,n=r.byteRangeEndOffset;if(W(s)&&W(n)){var a;let e=s,r=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-s;t%16&&(r=n+(16-t%16)),0!==s&&(i.resetIV=!0,e=s-16)}i.rangeStart=e,i.rangeEnd=r}var o;return i}function di(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:X.MEDIA_ERROR,details:Q.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new hi(i)}class hi extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ui extends ht{constructor(t,e){super(t,e),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(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!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 ci{constructor(t,e,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=t,this.sn=e,this.id=r,this.size=i,this.part=s,this.partial=n}}const fi={length:0,start:()=>0,end:()=>0};class gi{static isBuffered(t,e){if(t){const r=gi.getBuffered(t);for(let t=r.length;t--;)if(e>=r.start(t)&&e<=r.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=gi.getBuffered(t);return gi.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}static bufferInfo(t,e,r){if(t){const i=gi.bufferedRanges(t);if(i.length)return gi.bufferedInfo(i,e,r)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,r){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,s=[];if(r)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(i=d);const n=s.length;if(n){const e=s[n-1].end;t[d].start-e<r?t[d].end>e&&(s[n-1].end=t[d].end):s.push(t[d])}else s.push(t[d])}else s=t;let n,a=0,o=e,l=e;for(let d=0;d<s.length;d++){const t=s[d].start,h=s[d].end;if(-1===i&&e>=t&&e<=h&&(i=d),e+r>=t&&e<h)o=t,l=h,a=l-e;else if(e+r<t){n=t;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||fi}catch(e){return pt.log("failed to get media.buffered",e),fi}}}function mi(t,e){for(let i=0,s=t.length;i<s;i++){var r;if((null==(r=t[i])?void 0:r.cc)===e)return t[i]}return null}function pi(t,e){const r=t.start+e;t.startPTS=r,t.setStart(r),t.endPTS=r+t.duration}function vi(t,e){const r=e.fragments;for(let i=0,s=r.length;i<s;i++)pi(r[i],t);e.fragmentHint&&pi(e.fragmentHint,t),e.alignedSliding=!0}function yi(t,e){t&&(!function(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const r=Math.min(e.endCC,t.endCC),i=mi(e.fragments,r),s=mi(t.fragments,r);if(!i||!s)return;pt.log(`Aligning playlist at start of dicontinuity sequence ${r}`);vi(i.start-s.start,t)}(e,t),e.alignedSliding||function(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const r=t.fragments,i=e.fragments;if(!r.length||!i.length)return;let s,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=mi(i,a),n=mi(r,a));s&&n||(s=i[Math.floor(i.length/2)],n=mi(r,s.cc)||r[Math.floor(r.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;vi((l-o)/1e3-(n.start-s.start),t)}(e,t),e.alignedSliding||e.skippedSegments||Br(t,e,!1))}function Ei(t,e,r){Ti(t,e,r),t.addEventListener(e,r)}function Ti(t,e,r){t.removeEventListener(e,r)}const Si=function(t){let e="";const r=t.length;for(let i=0;i<r;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e},Li="STOPPED",bi="IDLE",Ai="KEY_LOADING",Ri="FRAG_LOADING",ki="FRAG_LOADING_WAITING_RETRY",_i="PARSING",Di="PARSED",wi="ENDED",xi="ERROR",Ii="WAITING_LEVEL";class Pi extends ui{constructor(t,e,r,i,s){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Li,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:t,fragCurrent:e,media:r,mediaBuffer:i,state:s}=this,n=r?r.currentTime:0,a=gi.bufferInfo(i||r,n,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${W(n)?n.toFixed(3):n}, state: ${s}, ${o?"out of":"in"} buffer`),this.state===wi)this.resetLoadingState();else if(e){const r=t.maxFragLookUpTolerance,i=e.start-r,s=e.start+e.duration+r;if(o||s<a.start||i>a.end){const t=n>s;(n<i||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.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 t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}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===bi&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=t,this.fragmentLoader=new oi(t.config),this.keyLoader=r,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ni(t.config)}registerListeners(){const{hls:t}=this;t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Li)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Li}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const r=t.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;const s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=gi.bufferedInfo(s,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return gi.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const r=this.media=this.mediaBuffer=e.media;Ei(r,"seeking",this.onMediaSeeking),Ei(r,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Li&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){const r=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ti(i,"seeking",this.onMediaSeeking),Ti(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(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Li,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(t,e,r){this.startFragRequested=!0,this._loadFragForPlayback(t,e,r)}_loadFragForPlayback(t,e,r){this._doFragLoad(t,e,r,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,r=t.frag;this.fragContextChanged(r)?(e===Ri||!this.fragCurrent&&e===_i)&&(this.fragmentTracker.removeFragment(r),this.state=bi):("payload"in t&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level}`),this.hls.trigger(J.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==Li&&this.state!==xi&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:r}=this;if(r.getState(t)===zr){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&r.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===Xr&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,r=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:r};this.hls.trigger(J.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:r,payload:i}=t,s=r.decryptdata;if(i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&gr(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,mr(s.method)).catch(t=>{throw e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),t}).then(i=>{const s=self.performance.now();return e.trigger(J.FRAG_DECRYPTED,{frag:r,payload:i,stats:{tstart:n,tdecrypt:s}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==Li&&this.state!==xi&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state!==Li&&(this.state=bi),t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var r,i;const s=t.tracks;if(s&&!e.encrypted&&(null!=(r=s.audio)&&r.encrypted||null!=(i=s.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,r=new Error("EME not supported (light build)");return this.warn(r.message),!t||t.mediaKeys?!1:(this.hls.trigger(J.ERROR,{type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_KEYS,fatal:!0,error:r,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${r?Si(gi.getBuffered(r)):"(detached)"})`),Bt(t)){var i;if(t.type!==it.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=bi)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=bi}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:r,part:i,partsLoaded:s}=t,n=!s||0===s.length||s.some(t=>!t),a=new ci(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,r=null,i){var s;this.fragCurrent=t;const n=e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(s=t.decryptdata)&&s.key)t.encrypted||(a=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Ai,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(J.KEY_LOADED,t),this.state===Ai&&(this.state=bi),t}),this.hls.trigger(J.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Bt(t)&&(!o||t.sn!==o.sn)){const r=this.shouldLoadParts(e.details,t.end);r!==this.loadingParts&&(this.log(`LL-Part loading ${r?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=r)}if(r=Math.max(t.start,r||0),this.loadingParts&&Bt(t)){const s=n.partList;if(s&&i){r>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(s,t,r);if(o>-1){const l=s[o];let d;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${s.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Ri,d=a?a.then(r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(t,l,e,i)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,i).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(J.FRAG_LOADING,{frag:t,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}var l;if(Bt(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),W(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Ri;const d=this.config.progressive&&t.type!==it.SUBTITLE;let h;return h=d&&a?a.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,i)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,d?i:void 0),a]).then(([t])=>(!d&&i&&i(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(J.FRAG_LOADING,{frag:t,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,r,i){return new Promise((s,n)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger(J.FRAG_LOADED,i);const a=Hr(r.details,t.sn,e.index+1)||Vr(l,t.sn,e.index+1);if(!a)return s({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===Q.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===X.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(J.ERROR,e)}else this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==_i)return void(this.fragCurrent||this.state===Li||this.state===xi||(this.state=bi));const{frag:r,part:i,level:s}=e,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,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var r;const s=t.partList[0];if(s.fragment.type===it.SUBTITLE)return!1;if(e>=s.end+((null==(r=t.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(t){const{levels:e,fragCurrent:r}=this,{level:i,sn:s,part:n}=t;if(null==e||!e[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=e[i],o=a.details,l=n>-1?Hr(o,s,n):null,d=l?l.fragment:Gr(o,s,r);return d?(r&&r!==d&&(d.stats=r.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,r,i,s){if(this.state!==_i)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=ae(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:t.type,frag:e,part:r,chunkMeta:i,offset:d,parent:e.type,data:o};if(this.hls.trigger(J.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!gi.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const r=e.currentTime,i=gi.bufferInfo(e,r,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,i.end-n),r+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var r;const i=this.getLoadPosition();if(!W(i))return null;const s=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,s)}getFwdBufferInfoAtPos(t,e,r,i){const s=gi.bufferInfo(t,e,i);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,r);if(n&&(s.nextStart<=n.end||n.gap)){const r=Math.max(Math.min(s.nextStart,n.end)-e,i);return gi.bufferInfo(t,e,r)}}return s}getMaxBufferLength(t){const{config:e}=this;let r;return r=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(r,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const r=this.config,i=Math.max(Math.min(t-e,r.maxBufferLength),e),s=Math.max(t-3*e,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t,e=it.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,e){const r=e.fragments,i=r.length;if(!i)return null;const{config:s}=this,n=r[0].start,a=s.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const r=s.initialLiveManifestSize;if(i<r)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${r})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const r=this.hls.startPosition,i=this.hls.liveSyncPosition,s=o?(-1!==r&&r>=n?r:i)||o.start:t;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 t<=n&&(o=r[0]);if(!o){const r=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,r,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(r[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){const r=this.fragmentTracker.getState(t);return(r===Qr||r===Xr&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,r,i,s){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&r.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==t&&r.len+t.len>=s){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(t,e){return t?(this.config,t):t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,r){let i=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[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===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),i=a),s=l}return i}loadedEndOfParts(t,e){let r;for(let i=t.length;i--;){if(r=t[i],!r.loaded)return!1;if(e>r.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,r=this.fragPrevious;let i=null;if(r){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!W(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const s=t[i];if(Ke(e,r,s))return s}return null}(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const s=r.sn+1;if(s>=t.startSN&&s<=t.endSN){const n=e[s-t.startSN];r.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(t,e,r){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:s}=t;let n;return s&&(i=i.concat(s)),Ge(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=r?1:t.start>r?-1:0)),n||null}return null}(t,r.cc,r.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,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),t<e){var c;u=He(s,n,t,t<this.lastCurrentTime||t>e-l||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const t=u.sn-r.startSN,e=this.fragmentTracker.getState(u);if((e===Qr||e===Xr&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!h||d[0].fragment.sn>u.sn||!r.live)){if(u.level===s.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==Qr?e:null}}}return u}alignPlaylists(t,e,r){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const s=t.fragmentStart,n=!e,a=t.alignedSliding&&W(s);if(n||!a&&!s){yi(r,t);const s=t.fragmentStart;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),s}return s}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let r=this.startPosition;r<e&&(r=-1);const i=this.timelineOffset;if(-1===r){const s=null!==this.startTimeOffset,n=s?this.startTimeOffset:t.startTimeOffset;null!==n&&W(n)?(r=e+n,n<0&&(r+=t.edge),r=Math.min(Math.max(e,r),e+t.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${n} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):t.live?(r=this.hls.liveSyncPosition||e,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 t;const{media:e}=this;let r=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?r=e.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Bt(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ki)||(this.state=bi)}onFragmentOrKeyLoadError(t,e){var r;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!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=e.details===Q.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction;if(!a)return void(this.state=xi);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,u=!!h,c=u&&o===Ze.RetryRequest,f=u&&!a.resolved&&l===tr.MoveAllAlternatesMatchingHost,g=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!c&&f&&Bt(i)&&!i.endList&&g&&!We(e))this.resetFragmentErrors(t),this.treatAsGap(i),a.resolved=!0;else if((c||f)&&d<h.maxNumRetry){var m;const r=Je(null==(m=e.response)?void 0:m.code),s=ze(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=ki,a.resolved=!0,r)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${s}ms`)}else if(h){if(this.resetFragmentErrors(t),!(d<h.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===Ze.RemoveAlternatePermanently||(a.resolved=!0)}else this.state=o===Ze.SendAlternateToPenaltyBox?Ii:xi;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,r=e===1/0;(!e||t>=e||r&&!Je(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=bi)}reduceLengthAndFlushBuffer(t){if(this.state===_i||this.state===Di){const e=t.frag,r=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===it.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Li&&(this.state=bi)}afterBufferFlushed(t,e,r){if(!t)return;const i=gi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,r),this.state===wi&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Li&&(this.state=bi)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,r,i){const s=r.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i?0:Fr(s,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(J.LEVEL_PTS_UPDATED,{details:s,level:r,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===r.fragmentError||e&&(r.fragmentError<2||t.endList))&&this.treatAsGap(t,r),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Di,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(J.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===it.MAIN?"level":"track"}fragInfo(t,e=!0,r){var i,s;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${(null!=(i=e&&!r?t.startPTS:(r||t).start)?i:NaN).toFixed(3)}-${(null!=(s=e&&!r?t.endPTS:(r||t).end)?s:NaN).toFixed(3)}]${r&&"main"===t.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class Ci{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,r){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||r||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const r={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const r={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const r=null==(e=t[0])?void 0:e.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(i){var r;if(s.onError(i),null===this.queues||null===this.tracks)return;const e=null==(r=this.tracks[t])?void 0:r.buffer;null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,r;return null!=(e=this.queues)&&e[t]||null!=(r=this.tracks)&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const r=null==(e=this.tracks)?void 0:e[t],i=null==r?void 0:r.buffer;return i?`SourceBuffer${i.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const Mi=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Oi="HlsJsTrackRemovedError";class Fi extends Error{constructor(t){super(t),this.name=Oi}}class $i extends ht{constructor(t,e){var r;super("buffer-controller",t.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=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:r}=this;t&&this.log("Media source opened"),e&&r&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(J.MEDIA_ATTACHED,{media:e,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:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(r=Lt(t.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:t}=this;t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.BUFFER_RESET,this.onBufferReset,this),t.on(J.BUFFER_APPENDING,this.onBufferAppending,this),t.on(J.BUFFER_CODECS,this.onBufferCodecs,this),t.on(J.BUFFER_EOS,this.onBufferEos,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.FRAG_PARSED,this.onFragParsed,this),t.on(J.FRAG_CHANGED,this.onFragChanged,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.BUFFER_RESET,this.onBufferReset,this),t.off(J.BUFFER_APPENDING,this.onBufferAppending,this),t.off(J.BUFFER_CODECS,this.onBufferCodecs,this),t.off(J.BUFFER_EOS,this.onBufferEos,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.FRAG_PARSED,this.onFragParsed,this),t.off(J.FRAG_CHANGED,this.onFragChanged,this),t.off(J.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const r={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?ot(r,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(r[e]=ot({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,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(t,e){var r;let i=2;(e.audio&&!e.video||!e.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(t,e){const r=this.media=e.media;this.transferData=this.overrides=void 0;const i=Lt(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(n),t)this._objectUrl=r.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{r.removeAttribute("src");const e=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||e&&n instanceof e,Ni(r),function(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}(r,t),r.load()}catch(s){r.src=t}else r.src=t}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,r;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const r=this.tracks,i=e.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: ${Fe(r,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Fe(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!function(t,e){const r=Object.keys(t),i=Object.keys(e),s=r.length,n=i.length;return!s||!n||s===n&&!r.some(t=>-1===i.indexOf(t))}(i,r)){e.mediaSource=null,e.tracks=void 0;const s=t.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(J.MEDIA_DETACHING,{}),this.onMediaAttaching(J.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,s.forEach(t=>{const e=t,r=i[e];if(r){const t=r.buffer;if(t){const i=this.fragmentTracker,s=r.id;if(i.hasFragments(s)||i.hasParts(s)){const r=gi.getBuffered(t);i.detectEvictedFragments(e,r,s,null,!0)}const n=Bi(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,r)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const r=!!e.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(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===s.readyState;try{const e=s.sourceBuffers;for(let r=e.length;r--;)t&&e[r].abort(),s.removeSourceBuffer(e[r]);t&&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&&Ni(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(J.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${t}`,s)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Bi(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Ci(this.tracks)}onBufferCodecs(t,e){var r;const i=this.tracks,s=Object.keys(e);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&s.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach(t=>{var r,s;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:u}=n;let c=i[t];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[t],g=null!=f&&f.buffer?f:c,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:h,id:a});const v=be(m,p),y=null==v?void 0:v.replace(Mi,"$1");let E=be(o,l);const T=null==(s=E)?void 0:s.replace(Mi,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=Le(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(c.pendingCodec||c.codec)&&(c.pendingCodec=E),c.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(r=e.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((t,e)=>{const r=this.tracks[e];return t[e]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,e,r){const i=`${e};codecs=${r}`,s={label:`change-type=${i}`,execute:()=>{const s=this.tracks[t];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),s.codec=r,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(s,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const r=t.start,i=r+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,it.MAIN))?void 0:e.gap))return;const s={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&gi.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,it.MAIN))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:s,frag:t},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:r}=this,{data:i,type:s,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,h=l.buffering[s],{sn:u,cc:c}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,m=o?o.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);const p=r.audio;let v=!1;"audio"===s&&"audio/mpeg"===(null==p?void 0:p.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 t=o||a,e=this.blockedAudioAppend;if("audio"!==s||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===s){const r=t.end;if(e){const t=e.frag.start;(r>t||r<this.lastVideoAppendEnd||gi.isBuffered(E,t))&&this.unblockAudio()}this.lastVideoAppendEnd=r}}else{const e=t.start+.05*t.duration,r=E.buffered,i=this.currentOp("video");r.length||i?!i&&!gi.isBuffered(E,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||a).start,S={label:`append-${s}`,execute:()=>{var t;h.executeStart=self.performance.now();const e=null==(t=this.tracks[s])?void 0:t.buffer;e&&(v?this.updateTimestampOffset(e,T,.1,s,u,c):void 0!==d&&W(d)&&this.updateTimestampOffset(e,d,1e-6,s,u,c)),this.appendExecutor(i,s)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===g.first&&(g.first=t),m&&0===m.first&&(m.first=t);const e={};this.sourceBuffers.forEach(([t,r])=>{t&&(e[t]=gi.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(J.BUFFER_APPENDED,{type:s,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const r={type:X.MEDIA_ERROR,parent:a.type,details:Q.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},i=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)r.details=Q.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)r.errorAction=rr(!0);else if(t.name===Oi&&0===this.sourceBufferCount)r.errorAction=rr(!0);else{const t=++this.appendErrors[s];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${i||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||i)&&(r.fatal=!0)}this.hls.trigger(J.ERROR,r)}};this.log(`queuing "${s}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===it.MAIN?"level":"track"} ${a.level} cc: ${c}`),this.append(S,s,this.isPending(this.tracks[s]))}getFlushOp(t,e,r){return this.log(`queuing "${t}" remove ${e}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(J.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${r} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:r,startOffset:i,endOffset:s}=e;r?this.append(this.getFlushOp(r,i,s),r):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,s),t)})}onFragParsed(t,e){const{frag:r,part:i}=e,s=[],n=i?i.elementaryStreams:r.elementaryStreams;n[$t]?s.push("audiovideo"):(n[Ot]&&s.push("audio"),n[Ft]&&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 t=self.performance.now();r.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:r.stats;this.hls.trigger(J.FRAG_BUFFERED,{frag:r,part:i,stats:e,id:r.type})},s).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var r;this.sourceBuffers.forEach(([t])=>{if(t){const r=this.tracks[t];e.type&&e.type!==t||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(J.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(J.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===Q.BUFFER_APPEND_ERROR&&e.frag){var r;const t=null==(r=e.errorAction)?void 0:r.nextAutoLevel;W(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:r}=this;if(!r||null===e)return;if(!this.sourceBufferCount)return;const i=t.config,s=r.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(W(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(s/n)*n-t;this.flushBackBuffer(s,n,e)}const o=i.frontBufferFlushThreshold;if(W(o)&&o>0){const t=Math.max(i.maxBufferLength,o),e=Math.max(t,n),r=Math.floor(s/n)*n+e;this.flushFrontBuffer(s,n,r)}}flushBackBuffer(t,e,r){this.sourceBuffers.forEach(([t,e])=>{if(e){const s=gi.getBuffered(e);if(s.length>0&&r>s.start(0)){var i;this.hls.trigger(J.BACK_BUFFER_REACHED,{bufferEnd:r});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(J.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}})}flushFrontBuffer(t,e,r){this.sourceBuffers.forEach(([e,i])=>{if(i){const s=gi.getBuffered(i),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(r>a||t>=a&&t<=o)return;this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:r}=this;if(!e||!this.media||"open"!==(null==r?void 0:r.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&r.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const s=null==(t=this.overrides)?void 0:t.duration;if(s)return W(s)?{duration:s}:null;const n=this.media.duration;return i>(W(r.duration)?r.duration:0)&&i>n||!W(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:r}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==t&&(W(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==r&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${r}.`),i.setLiveSeekableRange(e,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Fe(r)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,r])=>{if(e){const i=this.tracks[e];t[e]={buffer:r,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(J.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const a=n,o=t[a];if(this.isPending(o)){const t=this.getTrackCodec(o,a),n=`${o.container};codecs=${t}`;o.codec=t,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${Fe(o)}`);try{const t=r.addSourceBuffer(n),i=Bi(a),s=[a,t];e[i]=s,o.buffer=t}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(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:s,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(t,e){const r=t.supplemental;let i=t.codec;r&&("video"===e||"audiovideo"===e)&&me(r,"video")&&(i=function(t,e){const r=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)ge(e[t],"video")||r.push(e[t])}return e&&r.push(e),r.join(",")}(i,r));const s=be(i,t.levelCodec);return s?"audio"===e.slice(0,5)?Le(s,this.appendSource):s:""}trackSourceBuffer(t,e){const r=e.buffer;if(!r)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:r,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const r=e.removedRanges;null!=r&&r.length&&this.hls.trigger(J.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const r=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==r?void 0:r.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const r=this.currentOp(t);r&&(r.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var r;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${i}`,e),this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const s=this.currentOp(t);s&&s.onError(i)}updateTimestampOffset(t,e,r,i,s,n){const a=e-t.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${s} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,r){const{media:i,mediaSource:s}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!s||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=W(i.duration)?i.duration:1/0,l=W(s.duration)?s.duration:1/0,d=Math.max(0,e),h=Math.min(r,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const r=this.tracks[e],i=null==r?void 0:r.buffer;if(!i)throw new Fi(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,i.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,i=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(e=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;r&&!r.updating&&this.shiftAndExecuteNext(t)})}append(t,e,r){this.operationQueue&&this.operationQueue.append(t,e,r)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,r){const i=this.tracks[t];if(!i)return;const s=i.buffer;if(!s)return;const n=r.bind(this,t);i.listeners.push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const r=e.buffer;r&&(e.listeners.forEach(t=>{r.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}}function Ni(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function Bi(t){return"audio"===t?1:0}class Ui{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.BUFFER_CODECS,this.onBufferCodecs,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.BUFFER_CODECS,this.onBufferCodecs,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const r=this.hls.levels[e.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const r=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,r.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&W(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.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 t=this.hls.levels;if(t.length){const e=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=r,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const r=e.filter((e,r)=>this.isLevelAllowed(e)&&r<=t);return this.clientRect=null,Ui.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 t=this.media,e={width:0,height:0};if(t){const r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(e){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,r){if(null==t||!t.length)return-1;const i=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let s=t.length-1;const n=Math.max(e,r);for(let a=0;a<t.length;a+=1){const e=t[a];if((e.width>=n||e.height>=n)&&i(e,t[a+1])){s=a;break}}return s}}class Gi extends ht{constructor(t){super("content-steering",t.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=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}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(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}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(t,e){const{contentSteering:r}=e;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:r}=e;if((null==r?void 0:r.action)===Ze.SendAlternateToPenaltyBox&&r.flags===tr.MoveAllAlternatesMatchingHost){const t=this.levels;let i=this._pathwayPriority,s=this.pathwayId;if(e.context){const{groupId:r,pathwayId:i,type:n}=e.context;r&&t?s=this.getPathwayForGroupId(r,n,s):i&&(s=i)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==s),e.details!==Q.BUFFER_APPEND_ERROR||e.fatal?r.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${s} levels: ${t?t.length:t} priorities: ${Fe(i)} penalized: ${Fe(this.penalizedPathways)}`):r.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(t=>{i-r[t]>3e5&&delete r[t]});for(let s=0;s<t.length;s++){const i=t[s];if(i in r)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Kr(e),this.hls.trigger(J.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(e===et&&i[s].hasAudioGroup(t)||e===rt&&i[s].hasSubtitleGroup(t))return i[s].pathwayId;return r}clonePathways(t){const e=this.levels;if(!e)return;const r={},i={};t.forEach(t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===s))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new nr(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(r[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Vi(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Ce({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let r=1;r<t.audioGroups.length;r++)d.addGroupId("audio",`${t.audioGroups[r]}_clone_${s}`);if(t.subtitleGroups)for(let r=1;r<t.subtitleGroups.length;r++)d.addGroupId("text",`${t.subtitleGroups[r]}_clone_${s}`);return d});e.push(...o),Hi(this.audioTracks,r,a,s),Hi(this.subtitleTracks,i,a,s)})}loadSteeringManifest(t){const e=this.hls.config,r=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new r(e);try{i=new self.URL(t)}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const s={responseType:"json",url:i.href},n=e.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:(t,e,r,s)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.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(J.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,r,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let s=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,s)},onTimeout:(t,e,r)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const r=null==(e=this.hls)?void 0:e.media;!r||r.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}}function Hi(t,e,r,i){t&&Object.keys(e).forEach(s=>{const n=t.filter(t=>t.groupId===s).map(t=>{const n=ot({},t);return n.details=void 0,n.attrs=new nr(n.attrs),n.url=n.attrs.URI=Vi(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function Vi(t,e,r,i){const{HOST:s,PARAMS:n,[r]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}class Ki{constructor(t){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=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const r=this.hls.config;if(r.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,r){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,s=r-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*s/t,o=this.hls;if(o.trigger(J.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(J.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}var qi,ji={exports:{}};var Wi=(qi||(qi=1,function(t){var e=Object.prototype.hasOwnProperty,r="~";function i(){}function s(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||t,a),l=r?r+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new i:delete t._events[e]}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 t,i,s=[];if(0===this._eventsCount)return s;for(i in t=this._events)e.call(t,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},o.prototype.listeners=function(t){var e=r?r+t:t,i=this._events[e];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(t){var e=r?r+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,s,n,a){var o=r?r+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,i),!0;case 4:return h.fn.call(h.context,e,i,s),!0;case 5:return h.fn.call(h.context,e,i,s,n),!0;case 6:return h.fn.call(h.context,e,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(t,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,e);break;case 3:h[d].fn.call(h[d].context,e,i);break;case 4:h[d].fn.call(h[d].context,e,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(t,e,r){return n(this,t,e,r,!1)},o.prototype.once=function(t,e,r){return n(this,t,e,r,!0)},o.prototype.removeListener=function(t,e,i,s){var n=r?r+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||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!==e||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(t){var e;return t?(e=r?r+t:t,this._events[e]&&a(this,e)):(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,t.exports=o}(ji)),ji.exports),Yi=vt(Wi);class zi{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let r;return t.length?(r=1===t.length?t[0]:function(t,e){const r=new Uint8Array(e);let i=0;for(let s=0;s<t.length;s++){const e=t[s];r.set(e,i),i+=e.length}return r}(t,e),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Xi(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Qi(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Ji(t,e){let r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3],r}function Zi(t,e){const r=e;let i=0;for(;Qi(t,e);){i+=10;i+=Ji(t,e+6),Xi(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(r,r+i)}function ts(t,e){return 255===t[e]&&240==(246&t[e+1])}function es(t,e){return 1&t[e+1]?7:9}function rs(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function is(t,e){return e+1<t.length&&ts(t,e)}function ss(t,e){if(is(t,e)){const r=es(t,e);if(e+r>=t.length)return!1;const i=rs(t,e);if(i<=r)return!1;const s=e+i;return s===t.length||is(t,s)}return!1}function ns(t,e,r,i,s){if(!t.samplerate){const n=function(t,e,r,i){const s=e[r+2],n=s>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(s>>6&3),o=e[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 pt.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}}(e,r,i,s);if(!n)return;ot(t,n)}}function as(t){return 9216e4/t}function os(t,e,r,i,s){const n=i+s*as(t.samplerate),a=function(t,e){const r=es(t,e);if(e+r<=t.length){const i=rs(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}(e,r);let o;if(a){const{frameLength:i,headerLength:s}=a,l=s+i,d=Math.max(0,r+l-e.length);d?(o=new Uint8Array(l-s),o.set(e.subarray(r+s,e.length),0)):o=e.subarray(r+s,r+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-r;o=new Uint8Array(l),o.set(e.subarray(r,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function ls(t,e){return Qi(t,e)&&Ji(t,e+6)+10<=t.length-e}function ds(t,e=0,r=1/0){return function(t,e,r,i){const s=(n=t,n instanceof ArrayBuffer?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(c=t,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,d=(o+e)/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)}(t,e,r,Uint8Array)}function hs(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=t.data.subarray(1).indexOf(0);if(-1===r)return;const i=bt(ds(t.data,1,r)),s=t.data[2+r],n=t.data.subarray(3+r).indexOf(0);if(-1===n)return;const a=bt(ds(t.data,3+r,n));let o;var l;return o="--\x3e"===i?bt(ds(t.data,4+r+n)):(l=t.data.subarray(4+r+n))instanceof ArrayBuffer?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=i,e.pictureType=s,e.description=a,e.data=o,e}function us(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=bt(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const r=bt(t.data.subarray(e),!0);e+=r.length+1;const i=bt(t.data.subarray(e));return{key:t.type,info:r,data:i}}const e=bt(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?hs(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const r=bt(t.data.subarray(e),!0);e+=r.length+1;const i=bt(t.data.subarray(e));return{key:t.type,info:r,data:i}}const e=bt(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function cs(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=Ji(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}}function fs(t){let e=0;const r=[];for(;Qi(t,e);){const i=Ji(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const s=e+i;for(;e+10<s;){const i=cs(t.subarray(e)),s=us(i);s&&r.push(s),e+=i.size+10}Xi(t,e)&&(e+=10)}return r}function gs(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function ms(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),r=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function ps(t){const e=fs(t);for(let r=0;r<e.length;r++){const t=e[r];if(gs(t))return ms(t)}}let vs=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function ys(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Es{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(t,e,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,r){}demux(t,e){this.cachedData&&(t=ae(this.cachedData,t),this.cachedData=null);let r,i=Zi(t,0),s=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?ps(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&W(o))&&(this.basePTS=Ts(o,e,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:vs.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){const e=this.appendFrame(n,t,s);e?(this.frameIndex++,this.lastPTS=e.sample.pts,s+=e.length,r=s):s=l}else ls(t,s)?(i=Zi(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:vs.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const e=t.slice(r);this.cachedData?this.cachedData=ae(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:ys(),id3Track:a,textTrack:ys()}}demuxSampleAes(t,e,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:ys(),id3Track:this._id3Track,textTrack:ys()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Ts=(t,e,r)=>{if(W(t))return 90*t;return 9e4*e+(r?9e4*r.baseTime/r.timescale:0)};let Ss=null;const Ls=[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],bs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],As=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Rs=[0,1,1,4];function ks(t,e,r,i,s){if(r+24>e.length)return;const n=_s(e,r);if(n&&r+n.frameLength<=e.length){const a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function _s(t,e){const r=t[e+1]>>3&3,i=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Ls[14*(3===r?3-i:3===i?3:4)+s-1],d=bs[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,u=As[r][i],c=Rs[i],f=8*u*c,g=Math.floor(u*l/d+a)*c;if(null===Ss){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ss=t?parseInt(t[1]):0}return!!Ss&&Ss<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Ds(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function ws(t,e){return e+1<t.length&&Ds(t,e)}function xs(t,e){if(e+1<t.length&&Ds(t,e)){const r=4,i=_s(t,e);let s=r;null!=i&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===t.length||ws(t,n)}return!1}const Is=/\/emsg[-/]ID3/i;function Ps(t,e){return W(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class Cs{constructor(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new ni(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,cr)}decryptAacSample(t,e,r){const i=t[e].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(t,e+1,r)}).catch(r)}decryptAacSamples(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e);let i=0;for(let s=32;s<t.length-16;s+=160,i+=16)r.set(t.subarray(s,s+16),i);return r}getAvcDecryptedUnit(t,e){const r=new Uint8Array(e);let i=0;for(let s=32;s<t.length-16;s+=160,i+=16)t.set(r.subarray(i,i+16),s);return t}decryptAvcSample(t,e,r,i,s){const n=ue(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,r+1,i)}).catch(i)}decryptAvcSamples(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();const s=t[e].units;for(;!(r>=s.length);r++){const n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,r,i,n),this.decrypter.isSync())))return}}}}class Ms{constructor(){this.VideoSample=null}createVideoSample(t,e,r){return{key:t,frame:!1,pts:e,dts:r,units:[],length:0}}getLastNalUnit(t){var e;let r,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;r=t[t.length-1]}return r}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const r=e.samples,i=r.length;if(!i)return void e.dropped++;{const e=r[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,r){const i=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o,l,d,h=0,u=-1,c=0;for(-1===s&&(u=0,c=this.getNALuType(e,0),s=0,h=1);h<i;)if(o=e[h++],s)if(1!==s)if(o)if(1===o){if(l=h-s-1,u>=0){const t={data:e.subarray(u,l),type:c};a.push(t)}else{const r=this.getLastNalUnit(t.samples);r&&(n&&h<=4-n&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-n)),l>0&&(r.data=ae(r.data,e.subarray(0,l)),r.state=0))}h<i?(d=this.getNALuType(e,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 t={data:e.subarray(u,i),type:c,state:s};a.push(t)}if(0===a.length){const r=this.getLastNalUnit(t.samples);r&&(r.data=ae(r.data,e))}return t.naluState=s,a}}class Os{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");i.set(t.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const r=this.word>>>32-e;if(t>32&&pt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?r<<e|this.readBits(e):r}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Fs extends Ms{parsePES(t,e,r,i){const s=this.parseNALu(t,r.data,i);let n,a=this.VideoSample,o=!1;r.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(i=>{var s,l;switch(i.type){case 1:{let e=!1;n=!0;const s=i.data;if(o&&s.length>4){const t=this.readSliceType(s);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),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,he(i.data,1,r.pts,e.samples);break;case 7:{var h,u;n=!0,o=!0;const e=i.data,r=this.readSPS(e);if(!t.sps||t.width!==r.width||t.height!==r.height||(null==(h=t.pixelRatio)?void 0:h[0])!==r.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==r.pixelRatio[1]){t.width=r.width,t.height=r.height,t.pixelRatio=r.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:n=!0,t.pps=[i.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),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,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new Os(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let r,i=8,s=8;for(let n=0;n<t;n++)0!==s&&(r=e.readEG(),s=(i+r+256)%256),i=0===s?i:s}readSPS(t){const e=new Os(t);let r,i,s,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),u=e.readUEG.bind(e),c=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),m(),m(),f(1),c())for(i=3!==t?8:12,s=0;s<i;s++)c()&&p(s<6?16:64,e)}m();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),r=u(),s=0;s<r;s++)g();m(),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 L=[1,1];if(c()&&c()){switch(d()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[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:L}}}const $s=188;class Ns{constructor(t,e,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=t,this.config=e,this.typeSupported=r,this.logger=i,this.videoParser=null}static probe(t,e){const r=Ns.syncOffset(t);return r>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(t){const e=t.length;let r=Math.min(940,e-$s)+1,i=0;for(;i<r;){let s=!1,n=-1,a=0;for(let o=i;o<e;o+=$s){if(71!==t[o]||e-o!==$s&&71!==t[o+$s]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+18612,t.length-$s)+1)),s||(s=0===Bs(t,o)),s&&a>1&&(0===n&&a>2||o+$s>r))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:qt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ns.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ns.createTrack("audio",i),this._id3Track=Ns.createTrack("id3"),this._txtTrack=Ns.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:r}=this;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,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,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=ae(this.remainderData,t)).length,this.remainderData=null),y<$s&&!i)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,Ns.syncOffset(t));y-=(y-E)%$s,y<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let L=E;L<y;L+=$s)if(71===t[L]){const e=!!(64&t[L+1]),i=Bs(t,L);let y;if((48&t[L+3])>>4>1){if(y=L+5+t[L+4],y===L+$s)continue}else y=L+4;switch(i){case d:e&&(h&&(s=Ks(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(t.subarray(y,L+$s)),h.size+=L+$s-y);break;case u:if(e){if(f&&(s=Ks(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(t.subarray(y,L+$s)),f.size+=L+$s-y);break;case c:e&&(g&&(s=Ks(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(t.subarray(y,L+$s)),g.size+=L+$s-y);break;case 0:e&&(y+=t[y]+1),v=this._pmtId=Us(t,y);break;case v:{e&&(y+=t[y]+1);const i=Gs(t,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===m||p||(this.logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,L=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=i}}else T++;T>0&&Hs(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:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:r,id3Track:i,textTrack:s}=t,n=r.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=Ks(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=Ks(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Ks(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,r){const i=this.demux(t,r,!0,!this.config.progressive),s=this.sampleAes=new Cs(this.observer,this.config,e);return this.decrypt(i,s)}readyVideoParser(t){null===this.videoParser&&"avc"===t&&(this.videoParser=new Fs)}decrypt(t,e){return new Promise(r=>{const{audioTrack:i,videoTrack:s}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,()=>{r(t)}):r(t)}):s.samples&&e.decryptAvcSamples(s.samples,0,0,()=>{r(t)})})}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(t,e){let r=0;const i=this.aacOverFlow;let s,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,s=i.sample.unit.byteLength;if(-1===e)o=ae(i.sample.unit,o);else{const n=s-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),r=i.missing}}for(s=r,n=o.length;s<n-1&&!is(o,s);s++);if(s!==r){let t;const e=s<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",Hs(this.observer,new Error(t),e,this.logger),!e)return}if(ns(t,this.observer,o,s,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=as(t.samplerate);a=i.sample.pts+e}}let l,d=0;for(;s<n;){if(l=os(t,o,s,a,d),s+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;s<n-1&&!is(o,s);s++);}}parseMPEGPES(t,e){const r=e.data,i=r.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(ws(r,n)){const e=ks(t,r,n,a,s);if(!e)break;n+=e.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=ot({},e,{type:this._videoTrack?vs.emsg:vs.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function Bs(t,e){return((31&t[e+1])<<8)+t[e+2]}function Us(t,e){return(31&t[e+10])<<8|t[e+11]}function Gs(t,e,r,i,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=Bs(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){Vs("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){Vs("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){Vs("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=e+5,i=l;for(;i>2;){if(106===t[r])n.warn("AC-3 in M2TS support not included in build");const e=t[r+1]+2;r+=e,i-=e}}break;case 194:case 135:return Hs(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return Hs(s,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}e+=l+5}return a}function Hs(t,e,r,i){i.warn(`parsing error: ${e.message}`),t.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function Vs(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ks(t,e){let r,i,s,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ae(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>t.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&&(e.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(t.size<=h)return null;t.size-=h;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){r=l[t];let e=r.byteLength;if(h){if(h>e){h-=e;continue}r=r.subarray(h),e-=h,h=0}u.set(r,o),o+=e}return i&&(i-=s+3),{data:u,pts:n,dts:a,len:i}}return null}class qs{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)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===e)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===e)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===e)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 js=Math.pow(2,32)-1;class Ws{static init(){let t;for(t in Ws.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:[]},Ws.types)Ws.types.hasOwnProperty(t)&&(Ws.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);Ws.HDLR_TYPES={video:e,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]);Ws.STTS=Ws.STSC=Ws.STCO=s,Ws.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ws.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ws.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ws.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]);Ws.FTYP=Ws.box(Ws.types.ftyp,n,o,n,a),Ws.DINF=Ws.box(Ws.types.dinf,Ws.box(Ws.types.dref,i))}static box(t,...e){let r=8,i=e.length;const s=i;for(;i--;)r+=e[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(t,4),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}static hdlr(t){return Ws.box(Ws.types.hdlr,Ws.HDLR_TYPES[t])}static mdat(t){return Ws.box(Ws.types.mdat,t)}static mdhd(t,e){e*=t;const r=Math.floor(e/(js+1)),i=Math.floor(e%(js+1));return Ws.box(Ws.types.mdhd,new Uint8Array([1,0,0,0,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,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(t){return Ws.box(Ws.types.mdia,Ws.mdhd(t.timescale||0,t.duration||0),Ws.hdlr(t.type),Ws.minf(t))}static mfhd(t){return Ws.box(Ws.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Ws.box(Ws.types.minf,Ws.box(Ws.types.smhd,Ws.SMHD),Ws.DINF,Ws.stbl(t)):Ws.box(Ws.types.minf,Ws.box(Ws.types.vmhd,Ws.VMHD),Ws.DINF,Ws.stbl(t))}static moof(t,e,r){return Ws.box(Ws.types.moof,Ws.mfhd(t),Ws.traf(r,e))}static moov(t){let e=t.length;const r=[];for(;e--;)r[e]=Ws.trak(t[e]);return Ws.box.apply(null,[Ws.types.moov,Ws.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(Ws.mvex(t)))}static mvex(t){let e=t.length;const r=[];for(;e--;)r[e]=Ws.trex(t[e]);return Ws.box.apply(null,[Ws.types.mvex,...r])}static mvhd(t,e){e*=t;const r=Math.floor(e/(js+1)),i=Math.floor(e%(js+1)),s=new Uint8Array([1,0,0,0,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,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 Ws.box(Ws.types.mvhd,s)}static sdtp(t){const e=t.samples||[],r=new Uint8Array(4+e.length);let i,s;for(i=0;i<e.length;i++)s=e[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Ws.box(Ws.types.sdtp,r)}static stbl(t){return Ws.box(Ws.types.stbl,Ws.stsd(t),Ws.box(Ws.types.stts,Ws.STTS),Ws.box(Ws.types.stsc,Ws.STSC),Ws.box(Ws.types.stsz,Ws.STSZ),Ws.box(Ws.types.stco,Ws.STCO))}static avc1(t){let e,r,i,s=[],n=[];for(e=0;e<t.sps.length;e++)r=t.sps[e],i=r.byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));for(e=0;e<t.pps.length;e++)r=t.pps[e],i=r.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));const a=Ws.box(Ws.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Ws.box(Ws.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,Ws.box(Ws.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ws.box(Ws.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(t){const e=t.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,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Ws.box(Ws.types.mp4a,Ws.audioStsd(t),Ws.box(Ws.types.esds,Ws.esds(t)))}static mp3(t){return Ws.box(Ws.types[".mp3"],Ws.audioStsd(t))}static ac3(t){return Ws.box(Ws.types["ac-3"],Ws.audioStsd(t),Ws.box(Ws.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Ws.box(Ws.types.stsd,Ws.STSD,Ws.mp4a(t));if("mp3"===e&&"mp3"===t.codec)return Ws.box(Ws.types.stsd,Ws.STSD,Ws.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Ws.box(Ws.types.stsd,Ws.STSD,Ws.avc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,s=t.height||0,n=Math.floor(r/(js+1)),a=Math.floor(r%(js+1));return Ws.box(Ws.types.tkhd,new Uint8Array([1,0,0,7,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,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(t,e){const r=Ws.sdtp(t),i=t.id,s=Math.floor(e/(js+1)),n=Math.floor(e%(js+1));return Ws.box(Ws.types.traf,Ws.box(Ws.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Ws.box(Ws.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])),Ws.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,Ws.box(Ws.types.trak,Ws.tkhd(t),Ws.mdia(t))}static trex(t){const e=t.id;return Ws.box(Ws.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const r=t.samples||[],i=r.length,s=12+16*i,n=new Uint8Array(s);let a,o,l,d,h,u;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],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 Ws.box(Ws.types.trun,n)}static initSegment(t){Ws.types||Ws.init();const e=Ws.moov(t);return ae(Ws.FTYP,e)}static hvc1(t){return new Uint8Array}}Ws.types=void 0,Ws.HDLR_TYPES=void 0,Ws.STTS=void 0,Ws.STSC=void 0,Ws.STCO=void 0,Ws.STSZ=void 0,Ws.VMHD=void 0,Ws.SMHD=void 0,Ws.STSD=void 0,Ws.FTYP=void 0,Ws.DINF=void 0;function Ys(t,e=!1){return function(t,e,r=1,i=!1){const s=t*e*r;return i?Math.round(s):s}(t,1e3,1/9e4,e)}function zs(t){const{baseTime:e,timescale:r,trackId:i}=t;return`${e/r} (${e}/${r}) trackId: ${i}`}let Xs,Qs=null,Js=null;function Zs(t,e,r,i){return{duration:e,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class tn extends ht{constructor(t,e,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=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===Qs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qs=t?parseInt(t[1]):0}if(null===Js){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Js=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?zs(e):e} > ${t?zs(t):t}`),this._initPTS=this._initDTS=t}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(t){let e=!1;const r=t[0].pts,i=t.reduce((t,i)=>{let s=i.pts,n=s-t;return n<-4294967296&&(e=!0,s=en(s,r),n=s-t),n>0?t:s},r);return e&&this.debug("PTS rollover detected"),i}remux(t,e,r,i,s,n,a,o){let l,d,h,u,c,f,g=s,m=s;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,b,A;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(L=t.pixelRatio)?void 0:L[0])||(null==(b=e.pixelRatio)?void 0:b[1])!==(null==(A=t.pixelRatio)?void 0:A[1]))||!t&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,s,n));const r=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.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 t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}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(e.samples),i=(en(t.samples[0].pts,r)-r)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,s,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===it.AUDIO?m:void 0),T){const i=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,m,r,i)}}else T&&(l=this.remuxVideo(e,m,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=rn(r,s,this._initPTS,this._initDTS)),i.samples.length&&(u=sn(i,s,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:u,id3:c}}computeInitPts(t,e,r,i){const s=Math.round(r*e);let n=en(t,s);if(n<s+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-n)/e} ${i}`);n<s+e;)n+=8589934592;return n-s}generateIS(t,e,r,i){const s=t.samples,n=e.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),t.config&&s.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Ws.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(g=t.id,u=t.inputTimeScale,l&&u===l.timescale?c=!1:d=h=this.computeInitPts(s[0].pts,u,r,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Ws.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(g=e.id,u=e.inputTimeScale,l&&u===l.timescale)c=!1;else{const t=this.getVideoStartPts(n),e=en(n[0].dts,t),i=this.computeInitPts(e,u,r,"video"),s=this.computeInitPts(t,u,r,"video");h=Math.min(h,i),d=Math.min(d,s)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.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(t,e,r,i){const s=t.inputTimeScale,n=t.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,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===c){const t=d+e*s,i=n[0].pts-en(n[0].dts,n[0].pts);Qs&&null!==c&&Math.abs(t-i-(c+d))<15e3?r=!0:c=t-i-d}const y=c+d;for(let O=0;O<o;O++){const t=n[O];t.pts=en(t.pts,y),t.dts=en(t.dts,y),t.dts<n[O>0?O-1:O].dts&&(v=!0)}v&&n.sort(function(t,e){const r=t.dts-e.dts,i=t.pts-e.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||t.inputTimeScale/30;if(r){const r=h-y,i=r>T,s=r<-1;if((i||s)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ys(r,!0)} ms (${r}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ys(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||y>=n[0].pts||Qs)){h=y;const t=n[0].pts-r;if(i)n[0].dts=h,n[0].pts=t;else{let e=!0;for(let i=0;i<n.length&&!(n[i].dts>t&&e);i++){const t=n[i].pts;if(n[i].dts-=r,n[i].pts-=r,i<n.length-1){const r=n[i+1].pts;e=r<=n[i].pts==r<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ys(t,!0)}/${Ys(h,!0)}, delta: ${Ys(r,!0)} ms`)}}h=Math.max(0,h);let S=0,L=0,b=h;for(let O=0;O<o;O++){const t=n[O],e=t.units,r=e.length;let i=0;for(let s=0;s<r;s++)i+=e[s].data.length;L+=i,S+=r,t.length=i,t.dts<b?(t.dts=b,b+=T/4|0||1):b=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}u=n[o-1].dts;const A=L+4*S+8;let R;try{R=new Uint8Array(A)}catch(M){return void this.observer.emit(J.ERROR,J.ERROR,{type:X.MUX_ERROR,details:Q.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(Ws.types.mdat,4);let _=!1,D=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,I=Number.NEGATIVE_INFINITY;for(let O=0;O<o;O++){const t=n[O],e=t.units;let r,l=0;for(let i=0,s=e.length;i<s;i++){const t=e[i],r=t.data,s=t.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-t.dts,r=n[O+1].pts-t.pts;else{const e=this.config,a=O>0?t.dts-n[O-1].dts:T;if(r=O>0?t.pts-n[O-1].pts:T,e.stretchShortVideoTrack&&null!==this.nextAudioTs){const r=Math.floor(e.maxBufferHole*s),n=(i?m+i*s:this.nextAudioTs+d)-t.pts;n>r?(g=n-a,g<0?g=a:_=!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(t.pts-t.dts);D=Math.min(D,g),x=Math.max(x,g),w=Math.min(w,r),I=Math.max(I,r),a.push(Zs(t.key,g,l,h))}if(a.length)if(Qs){if(Qs<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Js&&I-w<x-D&&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 t=h;for(let e=0,r=a.length;e<r;e++){const i=t+a[e].duration,s=t+a[e].cts;if(e<r-1){const t=i+a[e+1].cts;a[e].duration=t-s}else a[e].duration=e?a[e-1].duration:T;a[e].cts=0,t=i}}g=_||!g?T:g;const P=u+g;this.nextVideoTs=c=P-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const C={data1:Ws.moof(t.sequenceNumber++,h,ot(t,{samples:a})),data2:R,startPTS:(m-d)/s,endPTS:(p+g-d)/s,startDTS:(h-d)/s,endDTS:c/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,C}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,r,i,s){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],c=void 0!==s;let f=t.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,v=p+e*n;if(this.isAudioContiguous=r=r||f.length&&m>0&&(i&&Math.abs(v-(m+p))<9e3||Math.abs(en(f[0].pts,v)-(m+p))<20*l),f.forEach(function(t){t.pts=en(t.pts,v)}),!r||m<0){const t=f.length;if(f=f.filter(t=>t.pts>=0),t!==f.length&&this.warn(`Removed ${f.length-t} of ${t} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===s?0:i&&!c?Math.max(0,v-p):f[0].pts-p}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let r=0,i=m+p;r<f.length;r++){const s=f[r],a=s.pts,o=a-i,d=Math.abs(1e3*o/n);if(o<=-e*l&&c)0===r&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,i=a);else if(o>=e*l&&d<1e4&&c){let e=Math.round(o/l);for(i=a-e*l;i<0&&e&&l;)e--,i+=l;0===r&&(this.nextAudioTs=m=i-p),this.warn(`Injecting ${e} audio frames @ ${((i-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=qs.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=s.unit.subarray()),f.splice(r,0,{unit:e,pts:i}),i+=l,r++}}s.pts=i,i+=l}}let y,E=null,T=null,S=0,L=f.length;for(;L--;)S+=f[L].unit.byteLength;for(let x=0,I=f.length;x<I;x++){const e=f[x],i=e.unit;let s=e.pts;if(null!==T){u[x-1].duration=Math.round((s-T)/a)}else{if(r&&"aac"===t.segmentCodec&&(s=m+p),E=s,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(w){return void this.observer.emit(J.ERROR,J.ERROR,{type:X.MUX_ERROR,details:Q.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!h){new DataView(y.buffer).setUint32(0,S),y.set(Ws.types.mdat,4)}}y.set(i,g);const n=i.byteLength;g+=n,u.push(Zs(!0,o,n,0)),T=s}const b=u.length;if(!b)return;const A=u[u.length-1];m=T-p,this.nextAudioTs=m+a*A.duration;const R=h?new Uint8Array(0):Ws.moof(t.sequenceNumber++,E/a,ot({},t,{samples:u}));t.samples=[];const k=(E-p)/n,_=this.nextAudioTs/n,D={data1:R,data2:y,startPTS:k,endPTS:_,startDTS:k,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,D}}function en(t,e){let r;if(null===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t}function rn(t,e,r,i){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let o=0;o<s;o++){const s=t.samples[o];s.pts=en(s.pts-r.baseTime*n/r.timescale,e*n)/n,s.dts=en(s.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function sn(t,e,r){const i=t.samples.length;if(!i)return;const s=t.inputTimeScale;for(let a=0;a<i;a++){const i=t.samples[a];i.pts=en(i.pts-r.baseTime*s/r.timescale,e*s)/s}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function nn(t,e,r=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(r?t.duration:0))/t.timescale:e}function an(t,e,r){const i=t.codec;if(i&&i.length>4)return i;if(e===Ot){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Le(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{Xs=self.performance.now.bind(self.performance)}catch(oa){Xs=Date.now}const on=[{demux:class{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,r,i){const s=this.videoTrack=ys("video",1),n=this.audioTrack=ys("audio",1),a=this.txtTrack=ys("text",1);if(this.id3Track=ys("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Zt(t);if(o.video){const{id:t,timescale:e,codec:r,supplemental:i}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=r,s.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:r}=o.audio;n.id=t,n.timescale=e,n.codec=r}a.id=qt.text,s.sampleDuration=0,s.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let r=0;r<e;){const i=Yt(t,r);if(i>8&&109===t[r+4]&&111===t[r+5]&&111===t[r+6]&&102===t[r+7])return!0;r=i>1?r+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let r=t;const i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=ae(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},r=Qt(t,["moof"]);if(r.length<2)return e.remainder=t,e;const i=r[r.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(r);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=r;const n=this.extractID3Track(i,e);return s.samples=oe(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return r.samples=oe(t,e),{videoTrack:e,audioTrack:ys(),id3Track:i,textTrack:ys()}}extractID3Track(t,e){const r=this.id3Track;if(t.samples.length){const i=Qt(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let r="",i="",s=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==jt(t.subarray(d,d+1));)r+=jt(t.subarray(d,d+1)),d+=1;for(r+=jt(t.subarray(d,d+1)),d+=1;"\0"!==jt(t.subarray(d,d+1));)i+=jt(t.subarray(d,d+1)),d+=1;i+=jt(t.subarray(d,d+1)),d+=1,s=Yt(t,12),n=Yt(t,16),o=Yt(t,20),l=Yt(t,24),d=28}else if(1===e){d+=4,s=Yt(t,d),d+=4;const e=Yt(t,d);d+=4;const n=Yt(t,d);for(d+=4,a=2**32*e+n,Y(a)||(a=Number.MAX_SAFE_INTEGER,pt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Yt(t,d),d+=4,l=Yt(t,d),d+=4;"\0"!==jt(t.subarray(d,d+1));)r+=jt(t.subarray(d,d+1)),d+=1;for(r+=jt(t.subarray(d,d+1)),d+=1;"\0"!==jt(t.subarray(d,d+1));)i+=jt(t.subarray(d,d+1)),d+=1;i+=jt(t.subarray(d,d+1)),d+=1}return{schemeIdUri:r,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Is.test(i.schemeIdUri)){const t=Ps(i,e);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:t,pts:t,type:vs.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=Ps(i,e);r.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:vs.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(t,e,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 ht{constructor(t,e,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(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,r,i){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t,i),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:r,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:n}=this.initData=Zt(t);if(e)!function(t,e){if(!t||!e)return;const r=e.keyId;r&&e.isCommonEncryption&&ne(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(pt.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${At(i)} -> ${At(r)}`),t.set(r,8))})}(t,e);else{const t=s||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}s&&(r=an(s,Ot,this)),n&&(i=an(n,Ft,this));const a={};s&&n?a.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:s?a.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,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};W(d)||(d=this.lastEndTime=s||0);const u=e.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(t,e,r){const i={},s=Qt(t,["moof","traf"]);for(let n=0;n<s.length;n++){const t=s[n],a=Qt(t,["tfhd"])[0],o=Yt(a,4),l=e[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=Qt(t,["tfdt"])[0];if(h){const t=h[0];let e=Yt(h,4);1===t&&(e===Vt?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=Vt+1,e+=Yt(h,8))),W(e)&&(!W(d.start)||e<d.start)&&(d.start=e)}const u=l.default,c=Yt(a,0)|(null==u?void 0:u.flags);let f=(null==u?void 0:u.duration)||0;8&c&&(f=Yt(a,2&c?12:8));const g=Qt(t,["trun"]);let m=d.start||0,p=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],r=Yt(t,4),i=d.sampleCount;d.sampleCount+=r;const s=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let u=8,c=r;for(s&&(u+=4),n&&r&&(1&t[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=i),u+=4,a?(v=Yt(t,u),u+=4):v=f,o&&(u+=4),h&&(u+=4),m+=v,p+=v,c--);c--;)a?(v=Yt(t,u),u+=4):v=f,o&&(u+=4),l&&(1&t[u+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(c+1),d.keyFrameStart=m),u+=4),h&&(u+=4),m+=v,p+=v;!p&&f&&(p+=f*r)}d.duration+=p}if(!Object.keys(i).some(t=>i[t].duration)){let e=1/0,r=0;const s=Qt(t,["sidx"]);for(let t=0;t<s.length;t++){const i=Jt(s[t]);if(null!=i&&i.references){e=Math.min(e,i.earliestPresentationTime/i.timescale);const t=i.references.reduce((t,e)=>t+e.info.duration||0,0);r=Math.max(r,t+i.earliestPresentationTime/i.timescale)}}r&&W(r)&&Object.keys(i).forEach(t=>{i[t].duration||(i[t].duration=r*i[t].timescale-i[t].start)})}return i}(u,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=nn(p,1/0),y=nn(m,1/0),E=nn(p,0,!0),T=nn(m,0,!0);let S=s,L=0;const b=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),A=b?m:p;if(A){const t=A.timescale,e=A.start-s*t,r=b?f.audio.id:f.video.id;S=A.start/t,L=b?T-y:E-v,!n&&l||!function(t,e,r,i){if(null===t)return!0;const s=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-r)>s}(l,S,s,L)&&t===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${e/t} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${S-s} (${e}/${t}) trackId: ${r}`),l=null,c.initPTS=e,c.timescale=t,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+L;L>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _=!!f.audio,D=!!f.video;let w="";_&&(w+="audio"),D&&(w+="video");const x={data1:u,startPTS:R,startDTS:R,endPTS:k,endDTS:k,type:w,hasAudio:_,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=_&&!D?x:void 0,h.video=D?x:void 0;const I=null==p?void 0:p.sampleCount;if(I){const t=p.keyFrameIndex,e=-1!==t;x.nb=I,x.dropped=0===t||this.isVideoContiguous?0:e?t:I,x.independent=e,x.firstKeyFrame=t,e&&p.keyFrameStart&&(x.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${I} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return h.initSegment=c,h.id3=rn(r,s,l,l),i.samples.length&&(h.text=sn(i,s,l)),h}}},{demux:Ns,remux:tn},{demux:class extends Es{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const r=Zi(t,0);let i=(null==r?void 0:r.length)||0;if(xs(t,i))return!1;for(let s=t.length;i<s;i++)if(ss(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&ts(t,e)&&rs(t,e)<=t.length-e}(t,e)}appendFrame(t,e,r){ns(t,this.observer,e,r,t.manifestCodec);const i=os(t,e,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:tn},{demux:class extends Es{resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Zi(t,0);let r=(null==e?void 0:e.length)||0;if(e&&11===t[r]&&119===t[r+1]&&void 0!==ps(e)&&((t,e)=>{let r=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];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],e+=1,i-=o}return r})(t,r)<=16)return!1;for(let i=t.length;r<i;r++)if(xs(t,r))return pt.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Ds(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,r){if(null!==this.basePTS)return ks(t,e,r,this.basePTS,this.frameIndex)}},remux:tn}];class ln{constructor(t,e,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=t,this.typeSupported=e,this.config=r,this.id=s,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,r,i){const s=r.transmuxing;s.executeStart=Xs();let n=new Uint8Array(t);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:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(t,e){let r=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(r=e);return r}(n,e);if(E&&gr(E.method)){const t=this.getDecrypter(),e=mr(E.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,e).then(t=>{const e=this.push(t,null,r);return this.decryptionPromise=null,e}),this.decryptionPromise;{let i=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer,e);if(r.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return s.executeEnd=Xs(),dn(r);n=new Uint8Array(i)}}const T=this.needsProbing(d,h);if(T){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),s.executeEnd=Xs(),dn(r)}(d||h||f||T)&&this.resetInitSegment(y,g,m,v,e),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,c,u,r);this.asyncResult=hn(S);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,s.executeEnd=Xs(),S}flush(t){const e=t.transmuxing;e.executeStart=Xs();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(r){const e=r.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Xs();const r=[dn(t)];return this.asyncResult?Promise.resolve(r):r}const d=o.flush(a);return hn(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,r){const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,{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===it.MAIN?"level":"track"} ${r.level}`);const d=this.remuxer.remux(i,s,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=Xs()}resetInitialTimestamp(t){const{demuxer:e,remuxer:r}=this;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,r,i,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,r,i),a.resetInitSegment(t,e,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,r,i,s){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,s):this.transmuxUnencrypted(t,r,i,s),n}transmuxUnencrypted(t,e,r,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,e,r,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,r,i,s){return this.demuxer.demuxSampleAes(t,e,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(t){const{config:e,observer:r,typeSupported:i}=this;let s;for(let h=0,u=on.length;h<u;h++){var n;if(null!=(n=on[h].demux)&&n.probe(t,this.logger)){s=on[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,e,i,this.logger)),a&&a instanceof d||(this.demuxer=new d(r,e,i,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new ni(this.config)),t}}const dn=t=>({remuxResult:{},chunkMeta:t});function hn(t){return"then"in t&&t.then instanceof Function}class un{constructor(t,e,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=t,this.videoCodec=e,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class cn{constructor(t,e,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=t,this.contiguous=e,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n}}function fn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}const gn=/(\d+)-(\d+)\/(\d+)/;class mn{constructor(t){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=t.fetchSetup||pn,this.controller=new self.AbortController,this.stats=new Mt}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 t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,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(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ot({},t.headers))};t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return r}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&W(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},e.timeout);(hn(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),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},l-(a-i.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new vn(e||"fetch, bad network response",t,r)}i.loading.first=a,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=gn.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(W(t))return t}const r=t.get("Content-Length");if(r)return parseInt(r)}(r.headers)||i.total;const o=null==(s=this.callbacks)?void 0:s.onProgress;return o&&W(e.highWaterMark)?this.loadProgressively(r,i,t,e.highWaterMark,o):n?r.arrayBuffer():"json"===t.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&&!W(e.highWaterMark)&&h(i,t,r,o),null==(n=this.callbacks)||n.onSuccess(d,i,t,o)}).catch(e=>{var r;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const s=e&&e.code||0,n=e?e.message:null;null==(r=this.callbacks)||r.onError({code:s,text:n},t,e?e.details:null,i)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,r,i=0,s){const n=new zi,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&s(e,r,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(e,r,n.flush().buffer,t)):s(e,r,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function pn(t,e){return new self.Request(t.url,e)}class vn extends Error{constructor(t,e,r){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=r}}const yn=/^age:\s*[\d.]+\s*$/im;class En{constructor(t){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=t&&t.xhrSetup||null,this.stats=new Mt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)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,e.url)}).catch(t=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",e.url,!0),s(r,e.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,e,t)}).catch(t=>{var s;null==(s=this.callbacks)||s.onError({code:r.status,text:t.message},e,r,i)}):this.openAndSendXhr(r,e,t)}openAndSendXhr(t,e,r){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=r.loadPolicy;if(i)for(const a in i)t.setRequestHeader(a,i[a]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&W(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:r}=this;if(!t||!e)return;const i=e.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),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const s=null!=l?l:e.response;if(null!=s){var n,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===e.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,t,s,e);const d={url:e.responseURL,data:s,code:i};return void(null==(a=this.callbacks)||a.onSuccess(d,r,t,e))}}const d=s.loadPolicy.errorRetry;var o;if(Qe(d,r.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(d);else pt.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,r)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Qe(t,this.stats.retry,!0))this.retry(t);else{var e;pt.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:r}=this;this.retryDelay=ze(t,r.retry),r.retry++,pt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${r.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&yn.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Tn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Sn=dt(dt({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:En,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ue,bufferController:$i,capLevelController:Ui,errorController:er,fpsController:Ki,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:Tn},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:Tn},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:St,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:Gi,interstitialsController:void 0});function Ln(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ln):Object.keys(t).reduce((e,r)=>(e[r]=Ln(t[r]),e),{}):t}class bn extends ui{constructor(t,e){super("gap-controller",t.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 t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const r=this.media=e.media;Ei(r,"playing",this.onMediaPlaying),Ei(r,"waiting",this.onMediaWaiting),Ei(r,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:r}=this;r&&(Ti(r,"playing",this.onMediaPlaying),Ti(r,"waiting",this.onMediaWaiting),Ti(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){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,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1})));if(!gi.getBuffered(n).length)return void(this.nudgeRetry=0);const h=gi.bufferInfo(n,t,0),u=h.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){const e=An(this.hls.inFlightFragments,t),r=h.len>2,i=!u||e||u-t>2&&!c.getPartialFragment(t);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 e=Math.max(u,h.start||0)-t,r=!(null==f||!f.live)?2*f.targetduration:2,i=kn(t,c);if(e>0&&(e<=r||i))return void(n.paused||this._trySkipBufferHole(i))}const g=s.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(J.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const T=gi.bufferInfo(n,t,s.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(J.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){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&&t>i.end(0)){const r=gi.bufferedInfo(gi.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){const r=gi.timeRangesToArray(i),s=gi.bufferedInfo(r,e,0).bufferedIndex;if(s>-1&&s<r.length-1){const e=gi.bufferedInfo(r,t,0).bufferedIndex,i=r[s].end,n=r[s+1].start;if((-1===e||e>s)&&n-i<1&&t-i<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(r.message),this.media.currentTime+=1e-6;let s=kn(t,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);const a=gi.bufferInfo(this.media,t,0);this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:s,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,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=kn(r,n);if(d||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,u=this.adjacentTraversal(t,r);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-r<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const r=this.fragmentTracker,i=t.nextStart;if(r&&i){const t=r.getFragAtPos(e,it.MAIN),s=r.getFragAtPos(i,it.MAIN);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:r,stallReported:i,stalled:s}=this;if(!i&&null!==s&&r&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Fe(t)})`);this.warn(i.message),e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:s}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:r,media:i}=this,s=null==(e=this.hls)?void 0:e.config;if(!i||!r||!s)return 0;const n=i.currentTime,a=gi.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=s.maxBufferHole,d=a.len>0&&a.len<1&&i.readyState<3,h=o-n;if(h>0&&(e||d)){if(h>s.maxBufferHole){let e=!1;if(0===n){const t=r.getAppendedFrag(0,it.MAIN);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(An(this.hls.inFlightFragments,o))return 0;let e=!1,i=t.end;for(;i<o;){const t=kn(i,r);if(!t){e=!0;break}i+=t.duration}if(e)return 0}}const e=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,i.currentTime=e,null==t||!t.gap){const r=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),i={type:X.MEDIA_ERROR,details:Q.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?i.part=t:i.frag=t),this.hls.trigger(J.ERROR,i)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:r,nudgeRetry:i}=this,s=null==e?void 0:e.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,e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const r=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(r.message),e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:t.len,bufferInfo:t})}}}function An(t,e){const r=Rn(t.main);if(r&&r.start<=e)return r;const i=Rn(t.audio);return i&&i.start<=e?i:null}function Rn(t){if(!t)return null;switch(t.state){case bi:case Li:case wi:case xi:return null}return t.frag}function kn(t,e){return e.getAppendedFrag(t,it.MAIN)||e.getPartialFragment(t)}function _n(t,e){let r;try{r=new Event("addtrack")}catch(oa){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function Dn(t,e,r,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,r){const i=[],s=function(t,e){if(e<=t[0].startTime)return 0;const r=t.length-1;if(e>t[r].endTime)return-1;let i,s=0,n=r;for(;s<=n;)if(i=Math.floor((n+s)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&s<r))return i;s=i+1}return t[s].startTime-e<e-t[n].startTime?s:n}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=r)i.push(s);else if(s.startTime>r)return i}return i}(t.cues,e,r);for(let e=0;e<s.length;e++)i&&!i(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function wn(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function xn(t,e,r,i,s){let n=new t(e,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new t(e,r,Fe(s?dt({type:s},i):i))}return n}const In=(()=>{const t=wn();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Pn{constructor(t){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(J.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var r;this.media=e.media,!1===(null==(r=e.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&function(t,e){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===r&&(t.mode=r)}(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const r=t[e];if("metadata"===r.kind&&"id3"===r.label)return _n(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:i}=this.hls.config;if(!r&&!i)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=wn();if(n)for(let a=0;a<s.length;a++){const t=s[a].type;if(t===vs.emsg&&!r||!i)continue;const e=fs(s[a].data),o=s[a].pts;let l=o+s[a].duration;l>In&&(l=In);l-o<=0&&(l=o+.25);for(let r=0;r<e.length;r++){const i=e[r];if(!gs(i)){this.updateId3CueEnds(o,t);const e=xn(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(t,e){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===e&&r.startTime<t&&r.endTime===In&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,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 t;t="audio"===i?t=>t.type===vs.audioId3&&o:"video"===i?t=>t.type===vs.emsg&&a:t=>t.type===vs.audioId3&&o||t.type===vs.emsg&&a,Dn(s,e,r,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:i,enableDateRangeMetadataCues:s,interstitialsController:n}=this.hls.config;if(!s)return;const a=wn();if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let h=this.dateRangeCuesAppended;var u;if(o&&e)if(null!=(u=o.cues)&&u.length){const t=Object.keys(h).filter(t=>!d.includes(t));for(let e=t.length;e--;){var c;const r=t[e],i=null==(c=h[r])?void 0:c.cues;delete h[r],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(r){}}})}}else h=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&W(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],r=l[e],i=r.startTime,s=h[e],n=(null==s?void 0:s.cues)||{};let o=(null==s?void 0:s.durationKnown)||!1,u=In;const{duration:c,endDate:f}=r;if(f&&null!==c)u=i+c,o=!0;else if(r.endOnNext&&!o){const t=d.reduce((t,e)=>{if(e!==r.id){const i=l[e];if(i.class===r.class&&i.startDate>r.startDate&&(!t||r.startDate<t.startDate))return i}return t},null);t&&(u=t.startTime,o=!0)}const g=Object.keys(r.attr);for(let t=0;t<g.length;t++){const l=g[t];if(!ar(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 t=r.attr[l];or(l)&&(t=Rt(t));const s=xn(a,i,u,{key:l,data:t},vs.dateRange);s&&(s.id=e,this.id3Track.addCue(s),n[l]=s)}}h[e]={cues:n,dateRange:r,durationKnown:o}}}}}class Cn{constructor(t){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:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||1===s||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=r-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,r));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:r,targetduration:i}=t,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||e;(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(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const r=this.levelDetails;if(null===r)return null;const i=r.edge,s=t-e-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 t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.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(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var r;e.details===Q.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(t,e){var r,i;t.playbackRate!==e&&(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 ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class Mn extends Wr{constructor(t,e){super(t,"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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const r=this.hls.config.preferManagedMediaSource,i=[],s={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=Le(d,r)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let r=0;r<e.length;r++){const t=e[r].split(".");t.length>2&&"avc1"===t[0]&&(e[r]=`avc1.${parseInt(t[1]).toString(16)}${("000"+parseInt(t[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:u,height:c,unknownCodecs:f}=t,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 "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${`${y||"."}-`}${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(s[S])if(s[S].uri===t.url||t.attrs["PATHWAY-ID"])s[S].addGroupId("audio",e.AUDIO),s[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const r=this.createLevel(t);s[S]=r,i.push(r)}else{const e=this.createLevel(t);s[S]=e,n[S]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new Ce(t),r=t.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(t.message),e.supportedResult=Tt.getUnsupportedResult(t,[])}return e}isAudioSupported(t){return me(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return me(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,r,i,s){var n;let a=[],o=[],l=t;const d=(null==(n=e.stats)?void 0:n.parsing)||{};if((r||i)&&s&&(l=l.filter(({videoCodec:t,videoRange:e,width:r,height:i})=>{return(!!t||!(!r||!i))&&(!!(s=e)&&we.indexOf(s)>-1);var s})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",r=t;e.levels.length&&(r=`one or more CODECS in variant not supported: ${Fe(e.levels.map(t=>t.attrs.CODECS).filter((t,e,r)=>r.indexOf(t)===e))}`,this.warn(r),t+=` (${r})`);const i=new Error(t);this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:r})}}),void(d.end=performance.now());e.audioTracks&&(a=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),On(a)),e.subtitles&&(o=e.subtitles,On(o));const h=l.slice(0);l.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return we.indexOf(t.videoRange)-we.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const r=ye(t.videoCodec),i=ye(e.videoCodec);if(r!==i)return i-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const r=Ee(t.codecSet),i=Ee(e.codecSet);if(r!==i)return i-r}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.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 t=u.bitrate,e=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(c=this.hls.userConfig)?void 0:c.abrEwmaDefaultEstimate)){const r=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);r>e&&e===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=r)}break}const f=s&&!i,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:i,altAudio:m&&!f&&a.some(t=>!!t.url)};d.end=performance.now(),this.hls.trigger(J.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const r=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:r,reason:r.message}),i)return;t=Math.min(t,e.length-1)}const r=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,r===t&&i&&s===a)return;this.log(`Switching to level ${t} (${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:t,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(J.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),r=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=r}}onError(t,e){!e.fatal&&e.context&&e.context.type===tt&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===it.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const r=this._levels[e.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(t,e){var r;const{level:i,details:s}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(r=e.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const r=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(J.LEVEL_LOADING,{url:r,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const r=this._levels.filter((e,r)=>r!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));Kr(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.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(J.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(J.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function On(t){const e={};t.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}const Fn="1.6.15",$n={};let Nn=0;class Bn{constructor(t,e,r,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Nn++,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=t=>{const e=t.data,r=this.hls;if(r&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":r.logger[e.data.logType]&&r.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,r.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===J.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Yi,this.observer.on(J.FRAG_DECRYPTED,n),this.observer.on(J.ERROR,n);const a=ke(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 "${e}"`),this.workerContext=function(t){const e=$n[t];if(e)return e.clientCount++,e;const r=new self.URL(t,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return $n[t]=i,i}(s.workerPath)):(r.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=$n[Fn];if(t)return t.clientCount++,t;const e=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(e),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return $n[Fn]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:Fe(s)})}catch(oa){r.warn(`Error setting up "${e}" Web Worker, fallback to inline`,oa),this.terminateWorker(),this.error=null,this.transmuxer=new ln(this.observer,a,s,"",e,t.logger)}return}}this.transmuxer=new ln(this.observer,a,s,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Nn++;const e=this.hls.config,r=ke(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:Fe(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=$n[t||Fn];if(e&&1===e.clientCount--){const{worker:r,objectURL:i}=e;delete $n[t||Fn],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,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,m=s.decryptdata,p=this.frag,v=!(p&&s.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),b=self.performance.now();(y||E||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&L||(n.stats.parsing.start=b);const A=!(p&&(null==(h=s.initSegment)?void 0:h.url)===(null==(u=p.initSegment)?void 0:u.url)),R=new cn(v,L,o,y,g,A);if(!L||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===it.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${A}`);const t=new un(r,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,R);hn(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(r){const e=r.flush(t);hn(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,r){this.hls&&(this.error=t,this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Un(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gn(){if(!Lt())return!1;const t=Un();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function Hn(){if(!Gn())return!1;const t=Lt();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(ve(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(ve(e,"audio"))))}class Vn extends Pi{constructor(t,e,r){super(t,e,r,"stream-controller",it.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 t=this.media,e=t?t.currentTime:null;if(null===e||!W(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const r=this.getFwdBufferInfoAtPos(t,e,it.MAIN,0);null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${r?r.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(J.BUFFER_CREATED,this.onBufferCreated,this),t.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(J.BUFFER_CREATED,this.onBufferCreated,this),t.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:r,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}r>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=bi,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Li}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ii:{const{levels:t,level:e}=this,r=null==t?void 0:t[e],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=bi;break}if(this.hls.nextLoadLevel!==this.level){this.state=bi;break}break}case ki:this.checkRetryDate()}this.state===bi&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:r,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?t.nextLoadLevel:t.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 t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(J.BUFFER_EOS,t),void(this.state=wi)}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const l=n.details;if(!l||this.state===Ii||this.waitForLive(n))return this.level=s,this.state=Ii,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&&Bt(c)&&this.fragmentTracker.getState(c)!==Qr){var f;const t=(null!=(f=this.backtrackFragment)?f:c).sn-l.startSN,e=l.fragments[t-1];e&&c.cc===e.cc&&(c=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const t=this.audioOnly&&!this.altAudio?Ot:Ft,e=(t===Ft?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,it.MAIN)}c=this.getNextFragmentLoopLoading(c,l,a,it.MAIN,h)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(t,e,r){const i=this.fragmentTracker.getState(t);i===Yr||i===Xr?Bt(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,r):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,it.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let r;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;r=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else r=0;const n=this.getBufferedFrag(e.currentTime+r);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,r=t.duration,i=Math.max(n.end,e+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 t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Ai:case Ri:case ki:case _i:case Di:this.state=bi}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const r=e.media;Ei(r,"playing",this.onMediaPlaying),Ei(r,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:r}=this;r&&(Ti(r,"playing",this.onMediaPlaying),Ti(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(J.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let r=!1,i=!1;for(let s=0;s<e.levels.length;s++){const t=e.levels[s].audioCodec;t&&(r=r||-1!==t.indexOf("mp4a.40.2"),i=i||-1!==t.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&i&&!function(){var t;const e=Un();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:r}=this;if(!r||this.state!==bi)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Ii)}onLevelLoaded(t,e){var r;const{levels:i,startFragRequested:s}=this,n=e.level,a=e.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=e.levelInfo,d=this.fragCurrent;!d||this.state!==Ri&&this.state!==ki||d.level!==e.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(J.LEVEL_UPDATED,{details:a,level:n}),this.state===Ii){if(this.waitForCdnTuneIn(a))return;this.state=bi}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.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 t=gi.bufferInfo(r,i,0);if(null==(l=t.buffered)||!l.length)return void(r.currentTime=i);if(t.start<=s)return void(r.currentTime=i);const{nextStart:e}=gi.bufferedInfo(t.buffered,s,0);e&&(r.currentTime=e)}else r.currentTime=i}}_handleFragmentLoadProgress(t){var e;const r=t.frag,{part:i,payload:s}=t,{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==(e=r.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Bn(this.hls,it.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new ci(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[r.cc];c.push(s,h,u,l,r,i,o.totalduration,d,m,p)}onAudioTrackSwitching(t,e){const r=this.hls,i=0!==this.altAudio;if(Be(e.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 t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(J.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(J.AUDIO_TRACK_SWITCHED,e)}),void r.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(J.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const r=Be(e.url,this.hls);if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r?2:0,this.tick()}onBufferCreated(t,e){const r=e.tracks;let i,s,n=!1;for(const a in r){const t=r[a];if("main"===t.id){if(s=a,i=t,"video"===a){const t=r[a];t&&(this.videoBuffer=t.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(t,e){const{frag:r,part:i}=e,s=r.type===it.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===Di&&(this.state=bi));const t=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),Bt(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}const n=this.media;n&&(!this._hasEnoughToStart&&gi.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var r;if(e.fatal)this.state=xi;else switch(e.details){case Q.FRAG_GAP:case Q.FRAG_PARSING_ERROR:case Q.FRAG_DECRYPT_ERROR:case Q.FRAG_LOAD_ERROR:case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_ERROR:case Q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(it.MAIN,e);break;case Q.LEVEL_LOAD_ERROR:case Q.LEVEL_LOAD_TIMEOUT:case Q.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ii||(null==(r=e.context)?void 0:r.type)!==tt||(this.state=bi);break;case Q.BUFFER_ADD_CODEC_ERROR:case Q.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case Q.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Q.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=bi,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Ot||!this.altAudio){const t=(e===Ft?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,it.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let r=this.startPosition;if(r>=0&&e<r){if(t.seeking)return void this.log(`could not seek to ${r}, already seeking at ${e}`);const i=this.timelineOffset;i&&r&&(r+=i);const s=this.getLevelDetails(),n=gi.getBuffered(t),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),e<r&&(this.log(`seek to target start position ${r} from current time ${e} buffer start ${a}`),t.currentTime=r)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:r}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=bi,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(J.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==Li&&this.state!==xi&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:r}=this,{remuxResult:i,chunkMeta:s}=t,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=_i,c){const t=c.tracks;if(t){const i=a.initSegment||a;if(this.unhandledEncryptionError(c,a))return;this._bufferInitSegment(l,t,i,s),r.trigger(J.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const i=c.initPTS,n=c.timescale,o=this.initPTS[a.cc];if(W(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const t=c.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:t},r.trigger(J.INIT_PTS_FOUND,{frag:a,id:e,initPTS:i,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,r=!t||a.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,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:t;if(!e&&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 e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,s,e||r)}else{if(!e&&!r)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:r,endDTS:i}=g;o&&(o.elementaryStreams[Ot]={startPTS:t,endPTS:e,startDTS:r,endDTS:i}),a.setElementaryStreamInfo(Ot,t,e,r,i),this.bufferFragmentData(g,a,o,s)}if(f&&null!=u&&u.samples.length){const t={id:e,frag:a,details:f,samples:u.samples};r.trigger(J.FRAG_PARSING_METADATA,t)}if(f&&h){const t={id:e,frag:a,details:f,samples:h.samples};r.trigger(J.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${Bt(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,r,i){if(this.state!==_i)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(r));const{audio:s,video:n,audiovideo:a}=e;if(s){const r=t.audioCodec;let i=be(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 t=s.metadata;t&&"channelCount"in t&&1!==(t.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=it.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${i||""}/${r||""}/${s.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=it.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]=[${t.videoCodec||""}/${r}]${n.codec!==r?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(J.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(J.BUFFER_APPENDING,{type:t,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,it.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,r=null==t?void 0:t[e];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=bi}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const r=t.currentTime;if(gi.isBuffered(t,r)?e=this.getAppendedFrag(r):gi.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,r=e.level;t&&e.sn===t.sn&&t.level===r||(this.fragPlaying=e,this.hls.trigger(J.FRAG_CHANGED,{frag:e}),t&&t.level===r||this.hls.trigger(J.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return W(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(W(e)){const t=this.getLevelDetails(),r=this.currentFrag||(t?He(null,t.fragments,e):null);if(r){const t=r.programDateTime;if(null!==t){const i=t+1e3*(e-r.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Kn extends ht{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[r].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=Q.KEY_LOAD_ERROR,r,i,s){return new hi({type:X.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:r,networkDetails:i})}loadClear(t,e,r){return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var r,i;const s=t.decryptdata;if(!s){const r=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,r))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=qn(s);let o=this.keyIdToKeyInfo[a];if(null!=(r=o)&&r.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:t,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(e=>{const{keyInfo:r}=e;return s.key=r.decryptdata.key,{frag:t,keyInfo:r}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+At(s.keyId):""} URI: ${s.uri} from ${t.type} ${t.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,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t,e){const r={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var i;if(!t.decryptdata.keyId&&null!=(i=e.initSegment)&&i.data){const r=function(t){const e=[];return ne(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(r.length){let e=r[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${At(e)}`),vr.setKeyIdForUri(t.decryptdata.uri,e)):(e=vr.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${At(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!Bt(e))return Promise.resolve(r);const s=this.emeController.loadKey(r);return(t.keyLoadPromise=s.then(e=>(t.mediaKeySessionContext=e,r))).catch(r=>{throw t.keyLoadPromise=null,"data"in r&&(r.data.frag=e),r})}return Promise.resolve(r)}loadKeyHTTP(t,e){const r=this.config,i=new(0,r.loader)(r);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((s,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,r,i)=>{const{frag:a,keyInfo:o}=r,l=qn(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,Q.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(t,r,i,s)=>{this.resetLoader(r),n(this.createKeyLoadError(e,Q.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,dt({url:a.url,data:void 0},t)))},onTimeout:(t,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(e,Q.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(e,Q.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,d)})}resetLoader(t){const{frag:e,keyInfo:r,url:i}=t,s=r.loader;e.keyLoader===s&&(e.keyLoader=null,r.loader=null);const n=qn(r.decryptdata)||i;delete this.keyIdToKeyInfo[n],s&&s.destroy()}}function qn(t){return t.uri}function jn(t){const{type:e}=t;switch(e){case et:return it.AUDIO;case rt:return it.SUBTITLE;default:return it.MAIN}}function Wn(t,e){let r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}class Yn{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_LOADING,this.onLevelLoading,this),t.off(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,r=e.pLoader,i=e.loader,s=new(r||i)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:r}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Z,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:r,level:i,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:tt,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:et,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:rt,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const r=this.loaders[tt];if(r){const t=r.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(r.abort(),delete this.loaders[tt])}}load(t){var e;const r=this.hls.config;let i,s=this.getInternalLoader(t);if(s){const e=this.hls.logger,r=s.context;if(r&&r.levelOrTrack===t.levelOrTrack&&(r.url===t.url||r.deliveryDirectives&&!t.deliveryDirectives))return void(r.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${r.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}if(i=t.type===Z?r.manifestLoadPolicy.default:ot({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),W(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===tt&&null!==t.level?e=this.hls.levels[t.level].details:t.type===et&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===rt&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,r=e.targetduration;if(t&&r){const e=1e3*Math.max(3*t,.8*r);i=ot({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,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:(t,e,r,i)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=t.data;e.parsing.start=performance.now(),br.isMediaPlaylist(n)||r.type!==Z?this.handleTrackOrLevelPlaylist(t,e,r,i||null,s):this.handleMasterPlaylist(t,e,r,i)},onError:(t,e,r,i)=>{this.handleNetworkError(e,r,!1,t,i)},onTimeout:(t,e,r)=>{this.handleNetworkError(e,r,!0,void 0,t)}};s.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,r,i){const s=this.hls,n=t.data,a=Wn(t,r),o=br.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,r,o.playlistParsingError,i,e);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f}=o;this.variableList=f,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:i,videoCodec:s}=t;for(let n=e.length;n--;){const a=e[n];me(a,"audio",r)?(t.audioCodec=i=i?`${i},${a}`:a,fe.audio[i.substring(0,4)]=2,e.splice(n,1)):me(a,"video",r)&&(t.videoCodec=s=s?`${s},${a}`:a,fe.video[s.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=br.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(t=>!t.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 nr({}),bitrate:0,url:""}))}s.trigger(J.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(t,e,r,i,s){const n=this.hls,{id:a,level:o,type:l}=r,d=Wn(t,r),h=W(o)?o:W(a)?a:0,u=jn(r),c=br.parseLevelPlaylist(t.data,d,h,u,0,this.variableList);if(l===Z){const t={attrs:new nr({}),bitrate:0,details:c,name:"",url:d};c.requestScheduled=e.loading.start+Ur(c,0),n.trigger(J.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,t,e,r,i,s)}handleManifestParsingError(t,e,r,i,s){this.hls.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.MANIFEST_PARSING_ERROR,fatal:e.type===Z,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:i,stats:s})}handleNetworkError(t,e,r=!1,i,s){let n=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===tt?n+=`: ${t.level} id: ${t.id}`:t.type!==et&&t.type!==rt||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Q.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case Z:o=r?Q.MANIFEST_LOAD_TIMEOUT:Q.MANIFEST_LOAD_ERROR,l=!0;break;case tt:o=r?Q.LEVEL_LOAD_TIMEOUT:Q.LEVEL_LOAD_ERROR,l=!1;break;case et:o=r?Q.AUDIO_TRACK_LOAD_TIMEOUT:Q.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case rt:o=r?Q.SUBTITLE_TRACK_LOAD_TIMEOUT:Q.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const h={type:X.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:s};if(i){const r=(null==e?void 0:e.url)||t.url;h.response=dt({url:r,data:void 0},i)}this.hls.trigger(J.ERROR,h)}handlePlaylistLoaded(t,e,r,i,s,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:u,deliveryDirectives:c}=i,f=Wn(e,i),g=jn(i);let m="number"==typeof i.level&&g===it.MAIN?l:void 0;const p=t.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:e,context:i,level:m,parent:g,networkDetails:s,stats:r});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:i,level:m,parent:g,networkDetails:s,stats:r})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Z:case tt:if(m)if(d){if(d!==a.levels[m]){const t=a.levels.indexOf(d);t>-1&&(m=t)}}else m=0;a.trigger(J.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:r,networkDetails:s,deliveryDirectives:c,withoutMultiVariant:o===Z});break;case et:a.trigger(J.AUDIO_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:c});break;case rt:a.trigger(J.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:c})}}}const zn={supported:!1,smooth:!1,powerEfficient:!1},Xn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Qn(t,e,r,i={}){const s=t.videoCodec;if(!s&&!t.audioCodec||!r)return Promise.resolve(Xn);const n=[],a=function(t){var e;const r=null==(e=t.videoCodec)?void 0:e.split(","),i=Zn(t),s=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return r?r.map(t=>{const e={contentType:ve(Re(t),"video"),width:s,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,r){var i;const s=null==(i=t.audioCodec)?void 0:i.split(","),n=Zn(t);if(s&&t.audioGroups)return t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");s.forEach(e=>{const s={contentType:ve(e,"audio"),bitrate:r?Jn(e,n):n};i&&(s.channels=""+i),t.push(s)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let h=o||1*d||1;h--;){const t={type:"media-source"};if(o&&(t.video=a[h%o]),d){t.audio=l[h%d];const e=t.audio.bitrate;t.video&&e&&(t.video.bitrate-=e)}n.push(t)}if(s){const t=navigator.userAgent;if(s.split(",").some(t=>le(t))&&ce())return Promise.resolve(function(t,e){return{supported:!1,configurations:e,decodingInfoResults:[zn],error:t}}(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:r,video:i}=t;if(i){e+=`${_e(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(r){e+=`${i?"_":""}${_e(r.contentType)}_c${r.channels}`}return e}(t);return i[e]||(i[e]=r.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function Jn(t,e){if(e<=1)return 1;let r=128e3;return"ec-3"===t?r=768e3:"ac-3"===t&&(r=64e4),Math.min(e/2,r)}function Zn(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}class ta{static get version(){return Fn}static isMSESupported(){return Gn()}static isSupported(){return Hn()}static getMediaSource(){return Lt()}static get Events(){return J}static get MetadataSchema(){return vs}static get ErrorTypes(){return X}static get ErrorDetails(){return Q}static get DefaultConfig(){return ta.defaultConfig?ta.defaultConfig:Sn}static set DefaultConfig(t){ta.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Yi,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 e=this.logger=function(t,e,r){const i=ft();if("object"==typeof console&&!0===t||"object"==typeof t){const n=["debug","log","info","warn","error"];n.forEach(e=>{i[e]=gt(e,t,r)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch(s){return ft()}n.forEach(e=>{mt[e]=gt(e,t)})}else ot(mt,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(t,e,r){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Ln(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];s.forEach(r=>{const s=`${t}Loading${r}`,l=e[s];if(void 0!==l&&a){o.push(s);const t=i[n].default;switch(e[n]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Fe(e[n])}`)}),dt(dt({},i),e)}(ta.DefaultConfig,t,e);this.userConfig=t,r.progressive&&function(t,e){const r=t.loader;r!==mn&&r!==En?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):fn()&&(t.loader=mn,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,e);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=r,l=new a(this),d=this.abrController=new i(this),h=new Jr(this),u=r.interstitialsController,c=u?this.interstitialsController=new u(this,ta):null,f=this.bufferController=new s(this,h),g=this.capLevelController=new n(this),m=new o(this),p=new Yn(this),v=r.contentSteeringController,y=v?new v(this):null,E=this.levelController=new Mn(this,y),T=new Pn(this),S=new Kn(this.config,this.logger),L=this.streamController=new Vn(this,h,S),b=this.gapController=new bn(this,h);g.setStreamController(L),m.setStreamController(L);const A=[p,E,L];c&&A.splice(1,0,c),y&&A.splice(1,0,y),this.networkControllers=A;const R=[d,f,b,g,m,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 _=r.subtitleStreamController;_&&A.push(this.subtititleStreamController=new _(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(Cn,R),this.coreComponents=R,A.push(l);const D=l.onErrorOut;"function"==typeof D&&this.on(J.ERROR,D,l),this.on(J.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(t,e){if(t){const r=new t(this);return e&&e.push(r),r}return null}on(t,e,r=this){this._emitter.on(t,e,r)}once(t,e,r=this){this._emitter.once(t,e,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,r=this,i){this._emitter.off(t,e,r,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,r){return this._emitter.emit(t,e,r)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const e=t===J.ERROR;this.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,fatal:e,event:t,error:r}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(J.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,r=e?t.media:t,i=e?t:{media:r};this._media=r,this.trigger(J.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(J.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(J.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,r=this._url,i=this._url=Ct.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(J.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(t,e),this.started&&this.networkControllers);r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[it.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[it.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[it.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?r:3&r|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return De.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const r=t.length;for(let i=0;i<r;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:r}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,r)for(let s=i;s--;){const e=t[s].attrs["HDCP-LEVEL"];if(e&&e<=r)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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(t){this.latencyController.targetLatency=t}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(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Qn(t,Ne(e),navigator.mediaCapabilities)}}ta.defaultConfig=void 0;var ea=Tt.KeySystemFormats,ra=Tt.KeySystems,ia=Tt.SubtitleStreamController,sa=Tt.TimelineController,na=Tt.requestMediaKeySystemAccess;const aa=Object.freeze(Object.defineProperty({__proto__:null,AbrController:Ue,AttrList:nr,AudioStreamController:St,AudioTrackController:St,BasePlaylistController:Wr,BaseSegment:Nt,BaseStreamController:Pi,BufferController:$i,CMCDController:St,CapLevelController:Ui,ChunkMetadata:ci,ContentSteeringController:Gi,Cues:St,DateRange:lr,EMEController:St,ErrorActionFlags:tr,ErrorController:er,ErrorDetails:Q,ErrorTypes:X,Events:J,FPSController:Ki,FetchLoader:mn,Fragment:Ut,Hls:ta,HlsSkip:xe,HlsUrlParameters:Pe,KeySystemFormats:ea,KeySystems:ra,Level:Ce,LevelDetails:dr,LevelKey:vr,LoadStats:Mt,M3U8Parser:br,MetadataSchema:vs,NetworkErrorAction:Ze,Part:Gt,PlaylistLevelType:it,SubtitleStreamController:ia,SubtitleTrackController:St,TimelineController:sa,XhrLoader:En,default:ta,fetchSupported:fn,getMediaSource:Lt,isMSESupported:Gn,isSupported:Hn,requestMediaKeySystemAccess:na},Symbol.toStringTag,{value:"Module"}));t.create=q,t.createAudioPlayer=G,t.default=j,t.initAll=K,t.initElement=H,t.parseAudioDataAttributes=U,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
2
- //# sourceMappingURL=embed.audio.light.umd.cjs.map