@scarlett-player/embed 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +109 -15
- package/dist/embed.audio.js +4354 -0
- package/dist/embed.audio.js.map +1 -0
- package/dist/embed.audio.light.js +4338 -0
- package/dist/embed.audio.light.js.map +1 -0
- package/dist/embed.audio.light.umd.cjs +2 -0
- package/dist/embed.audio.light.umd.cjs.map +1 -0
- package/dist/embed.audio.umd.cjs +2 -0
- package/dist/embed.audio.umd.cjs.map +1 -0
- package/dist/embed.full.js +5835 -0
- package/dist/embed.full.js.map +1 -0
- package/dist/embed.full.umd.cjs +2 -0
- package/dist/embed.full.umd.cjs.map +1 -0
- package/dist/embed.js +57 -62
- package/dist/embed.js.map +1 -1
- package/dist/embed.light.js +4611 -0
- package/dist/embed.light.js.map +1 -0
- package/dist/embed.light.umd.cjs +2 -0
- package/dist/embed.light.umd.cjs.map +1 -0
- package/dist/embed.umd.cjs +1 -1
- package/dist/embed.umd.cjs.map +1 -1
- package/dist/hls.light-YJMge-Mx.js +21849 -0
- package/dist/hls.light-YJMge-Mx.js.map +1 -0
- package/package.json +43 -16
package/dist/embed.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ScarlettPlayer={})}(this,function(e){"use strict";class t{constructor(e){this.subscribers=new Set,this.value=e}get(){return this.value}set(e){Object.is(this.value,e)||(this.value=e,this.notify())}update(e){this.set(e(this.value))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){this.subscribers.forEach(e=>{try{e()}catch(t){console.error("[Scarlett Player] Error in signal subscriber:",t)}})}destroy(){this.subscribers.clear()}getSubscriberCount(){return this.subscribers.size}}function s(e){return new t(e)}const i={playbackState:"idle",playing:!1,paused:!0,ended:!1,buffering:!1,waiting:!1,seeking:!1,currentTime:0,duration:NaN,buffered:null,bufferedAmount:0,mediaType:"unknown",source:null,title:"",poster:"",volume:1,muted:!1,playbackRate:1,fullscreen:!1,pip:!1,controlsVisible:!0,qualities:[],currentQuality:null,audioTracks:[],currentAudioTrack:null,textTracks:[],currentTextTrack:null,live:!1,liveEdge:!0,seekableRange:null,liveLatency:0,lowLatencyMode:!1,chapters:[],currentChapter:null,error:null,bandwidth:0,autoplay:!1,loop:!1,airplayAvailable:!1,airplayActive:!1,chromecastAvailable:!1,chromecastActive:!1,interacting:!1,hovering:!1,focused:!1};class r{constructor(e){this.signals=new Map,this.changeSubscribers=new Set,this.initializeSignals(e)}initializeSignals(e){const t={...i,...e};for(const[i,r]of Object.entries(t)){const e=i,t=s(r);t.subscribe(()=>{this.notifyChangeSubscribers(e)}),this.signals.set(e,t)}}get(e){const t=this.signals.get(e);if(!t)throw new Error(`[StateManager] Unknown state key: ${e}`);return t}getValue(e){return this.get(e).get()}set(e,t){this.get(e).set(t)}update(e){for(const[t,s]of Object.entries(e)){const e=t;this.signals.has(e)&&this.set(e,s)}}subscribeToKey(e,t){const s=this.get(e);return s.subscribe(()=>{t(s.get())})}subscribe(e){return this.changeSubscribers.add(e),()=>this.changeSubscribers.delete(e)}notifyChangeSubscribers(e){const t=this.get(e).get(),s={key:e,value:t,previousValue:t};this.changeSubscribers.forEach(e=>{try{e(s)}catch(t){console.error("[StateManager] Error in change subscriber:",t)}})}reset(){this.update(i)}resetKey(e){const t=i[e];this.set(e,t)}snapshot(){const e={};for(const[t,s]of this.signals)e[t]=s.get();return Object.freeze(e)}getSubscriberCount(e){return this.signals.get(e)?.getSubscriberCount()??0}destroy(){this.signals.forEach(e=>e.destroy()),this.signals.clear(),this.changeSubscribers.clear()}}const n={maxListeners:100,async:!1,interceptors:!0};class a{constructor(e){this.listeners=new Map,this.onceListeners=new Map,this.interceptors=new Map,this.options={...n,...e}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);return this.listeners.get(e).add(t),this.checkMaxListeners(e),()=>this.off(e,t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,new Set);const s=this.onceListeners.get(e);return s.add(t),this.listeners.has(e)||this.listeners.set(e,new Set),()=>{s.delete(t)}}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e));const i=this.onceListeners.get(e);i&&(i.delete(t),0===i.size&&this.onceListeners.delete(e))}emit(e,t){const s=this.runInterceptors(e,t);if(null===s)return;const i=this.listeners.get(e);if(i){Array.from(i).forEach(e=>{this.safeCallHandler(e,s)})}const r=this.onceListeners.get(e);if(r){Array.from(r).forEach(e=>{this.safeCallHandler(e,s)}),this.onceListeners.delete(e)}}async emitAsync(e,t){const s=await this.runInterceptorsAsync(e,t);if(null===s)return;const i=this.listeners.get(e);if(i){const e=Array.from(i).map(e=>this.safeCallHandlerAsync(e,s));await Promise.all(e)}const r=this.onceListeners.get(e);if(r){const t=Array.from(r).map(e=>this.safeCallHandlerAsync(e,s));await Promise.all(t),this.onceListeners.delete(e)}}intercept(e,t){if(!this.options.interceptors)return()=>{};this.interceptors.has(e)||this.interceptors.set(e,new Set);const s=this.interceptors.get(e);return s.add(t),()=>{s.delete(t),0===s.size&&this.interceptors.delete(e)}}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){return(this.listeners.get(e)?.size??0)+(this.onceListeners.get(e)?.size??0)}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.interceptors.clear()}runInterceptors(e,t){if(!this.options.interceptors)return t;const s=this.interceptors.get(e);if(!s||0===s.size)return t;let i=t;for(const n of s)try{if(i=n(i),null===i)return null}catch(r){console.error("[EventBus] Error in interceptor:",r)}return i}async runInterceptorsAsync(e,t){if(!this.options.interceptors)return t;const s=this.interceptors.get(e);if(!s||0===s.size)return t;let i=t;for(const n of s)try{const e=n(i);if(i=e instanceof Promise?await e:e,null===i)return null}catch(r){console.error("[EventBus] Error in interceptor:",r)}return i}safeCallHandler(e,t){try{e(t)}catch(s){console.error("[EventBus] Error in event handler:",s)}}async safeCallHandlerAsync(e,t){try{const s=e(t);s instanceof Promise&&await s}catch(s){console.error("[EventBus] Error in event handler:",s)}}checkMaxListeners(e){const t=this.listenerCount(e);t>this.options.maxListeners&&console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) exceeded for event: ${e}. Current count: ${t}. This may indicate a memory leak.`)}}const o=["debug","info","warn","error"],l=e=>{const t=`${e.scope?`[${e.scope}]`:"[ScarlettPlayer]"} ${e.message}`,s=e.metadata??"";switch(e.level){case"debug":console.debug(t,s);break;case"info":console.info(t,s);break;case"warn":console.warn(t,s);break;case"error":console.error(t,s)}};let h=class e{constructor(e){this.level=e?.level??"warn",this.scope=e?.scope,this.enabled=e?.enabled??!0,this.handlers=e?.handlers??[l]}child(t){return new e({level:this.level,scope:this.scope?`${this.scope}:${t}`:t,enabled:this.enabled,handlers:this.handlers})}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}setEnabled(e){this.enabled=e}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);-1!==t&&this.handlers.splice(t,1)}log(e,t,s){if(!this.enabled||!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),scope:this.scope,metadata:s};for(const n of this.handlers)try{n(i)}catch(r){console.error("[Logger] Handler error:",r)}}shouldLog(e){return o.indexOf(e)>=o.indexOf(this.level)}};var d=(e=>(e.SOURCE_NOT_SUPPORTED="SOURCE_NOT_SUPPORTED",e.SOURCE_LOAD_FAILED="SOURCE_LOAD_FAILED",e.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",e.PROVIDER_SETUP_FAILED="PROVIDER_SETUP_FAILED",e.PLUGIN_SETUP_FAILED="PLUGIN_SETUP_FAILED",e.PLUGIN_NOT_FOUND="PLUGIN_NOT_FOUND",e.PLAYBACK_FAILED="PLAYBACK_FAILED",e.MEDIA_DECODE_ERROR="MEDIA_DECODE_ERROR",e.MEDIA_NETWORK_ERROR="MEDIA_NETWORK_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e))(d||{});class c{constructor(e,t,s){this.errors=[],this.eventBus=e,this.logger=t,this.maxHistory=s?.maxHistory??10}handle(e,t){const s=this.normalizeError(e,t);return this.addToHistory(s),this.logError(s),this.eventBus.emit("error",s),s}throw(e,t,s){const i={code:e,message:t,fatal:s?.fatal??this.isFatalCode(e),timestamp:Date.now(),context:s?.context,originalError:s?.originalError};return this.handle(i,s?.context)}getHistory(){return[...this.errors]}getLastError(){return this.errors[this.errors.length-1]??null}clearHistory(){this.errors=[]}hasFatalError(){return this.errors.some(e=>e.fatal)}normalizeError(e,t){return this.isPlayerError(e)?{...e,context:{...e.context,...t}}:{code:this.getErrorCode(e),message:e.message,fatal:this.isFatal(e),timestamp:Date.now(),context:t,originalError:e}}getErrorCode(e){const t=e.message.toLowerCase();return t.includes("network")?"MEDIA_NETWORK_ERROR":t.includes("decode")?"MEDIA_DECODE_ERROR":t.includes("source")?"SOURCE_LOAD_FAILED":t.includes("plugin")?"PLUGIN_SETUP_FAILED":t.includes("provider")?"PROVIDER_SETUP_FAILED":"UNKNOWN_ERROR"}isFatal(e){return this.isFatalCode(this.getErrorCode(e))}isFatalCode(e){return["SOURCE_NOT_SUPPORTED","PROVIDER_NOT_FOUND","MEDIA_DECODE_ERROR"].includes(e)}isPlayerError(e){return"object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"fatal"in e&&"timestamp"in e}addToHistory(e){this.errors.push(e),this.errors.length>this.maxHistory&&this.errors.shift()}logError(e){const t=`[${e.code}] ${e.message}`;e.fatal?this.logger.error(t,{code:e.code,context:e.context}):this.logger.warn(t,{code:e.code,context:e.context})}}class u{constructor(e,t){this.cleanupFns=[],this.pluginId=e,this.stateManager=t.stateManager,this.eventBus=t.eventBus,this.container=t.container,this.getPluginFn=t.getPlugin,this.logger={debug:(s,i)=>t.logger.debug(`[${e}] ${s}`,i),info:(s,i)=>t.logger.info(`[${e}] ${s}`,i),warn:(s,i)=>t.logger.warn(`[${e}] ${s}`,i),error:(s,i)=>t.logger.error(`[${e}] ${s}`,i)}}getState(e){return this.stateManager.getValue(e)}setState(e,t){this.stateManager.set(e,t)}on(e,t){return this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}emit(e,t){this.eventBus.emit(e,t)}getPlugin(e){return this.getPluginFn(e)}onDestroy(e){this.cleanupFns.push(e)}subscribeToState(e){return this.stateManager.subscribe(e)}runCleanups(){for(const t of this.cleanupFns)try{t()}catch(e){this.logger.error("Cleanup function failed",{error:e})}this.cleanupFns=[]}getCleanupFns(){return this.cleanupFns}}class f{constructor(e,t,s,i){this.plugins=new Map,this.eventBus=e,this.stateManager=t,this.logger=s,this.container=i.container}register(e,t){if(this.plugins.has(e.id))throw new Error(`Plugin "${e.id}" is already registered`);this.validatePlugin(e);const s=new u(e.id,{stateManager:this.stateManager,eventBus:this.eventBus,logger:this.logger,container:this.container,getPlugin:e=>this.getReadyPlugin(e)});this.plugins.set(e.id,{plugin:e,state:"registered",config:t,cleanupFns:[],api:s}),this.logger.info(`Plugin registered: ${e.id}`),this.eventBus.emit("plugin:registered",{name:e.id,type:e.type})}async unregister(e){const t=this.plugins.get(e);t&&("ready"===t.state&&await this.destroyPlugin(e),this.plugins.delete(e),this.logger.info(`Plugin unregistered: ${e}`))}async initAll(){const e=this.resolveDependencyOrder();for(const t of e)await this.initPlugin(t)}async initPlugin(e){const t=this.plugins.get(e);if(!t)throw new Error(`Plugin "${e}" not found`);if("ready"!==t.state){if("initializing"===t.state)throw new Error(`Plugin "${e}" is already initializing (possible circular dependency)`);for(const s of t.plugin.dependencies||[]){const t=this.plugins.get(s);if(!t)throw new Error(`Plugin "${e}" depends on missing plugin "${s}"`);"ready"!==t.state&&await this.initPlugin(s)}try{if(t.state="initializing",t.plugin.onStateChange){const e=this.stateManager.subscribe(t.plugin.onStateChange.bind(t.plugin));t.api.onDestroy(e)}if(t.plugin.onError){const e=this.eventBus.on("error",e=>{t.plugin.onError?.(e.originalError||new Error(e.message))});t.api.onDestroy(e)}await t.plugin.init(t.api,t.config),t.state="ready",this.logger.info(`Plugin ready: ${e}`),this.eventBus.emit("plugin:active",{name:e})}catch(s){throw t.state="error",t.error=s,this.logger.error(`Plugin init failed: ${e}`,{error:s}),this.eventBus.emit("plugin:error",{name:e,error:s}),s}}}async destroyAll(){const e=this.resolveDependencyOrder().reverse();for(const t of e)await this.destroyPlugin(t)}async destroyPlugin(e){const t=this.plugins.get(e);if(t&&"ready"===t.state)try{await t.plugin.destroy(),t.api.runCleanups(),t.state="registered",this.logger.info(`Plugin destroyed: ${e}`),this.eventBus.emit("plugin:destroyed",{name:e})}catch(s){this.logger.error(`Plugin destroy failed: ${e}`,{error:s}),t.state="registered"}}getPlugin(e){const t=this.plugins.get(e);return t?t.plugin:null}getReadyPlugin(e){const t=this.plugins.get(e);return"ready"===t?.state?t.plugin:null}hasPlugin(e){return this.plugins.has(e)}getPluginState(e){return this.plugins.get(e)?.state??null}getPluginIds(){return Array.from(this.plugins.keys())}getReadyPlugins(){return Array.from(this.plugins.values()).filter(e=>"ready"===e.state).map(e=>e.plugin)}getPluginsByType(e){return Array.from(this.plugins.values()).filter(t=>t.plugin.type===e).map(e=>e.plugin)}selectProvider(e){const t=this.getPluginsByType("provider");for(const s of t){const t=s.canPlay;if("function"==typeof t&&t(e))return s}return null}resolveDependencyOrder(){const e=new Set,t=new Set,s=[],i=(r,n=[])=>{if(e.has(r))return;if(t.has(r)){const e=[...n,r].join(" -> ");throw new Error(`Circular dependency detected: ${e}`)}const a=this.plugins.get(r);if(a){t.add(r);for(const e of a.plugin.dependencies||[])this.plugins.has(e)&&i(e,[...n,r]);t.delete(r),e.add(r),s.push(r)}};for(const r of this.plugins.keys())i(r);return s}validatePlugin(e){if(!e.id||"string"!=typeof e.id)throw new Error("Plugin must have a valid id");if(!e.name||"string"!=typeof e.name)throw new Error(`Plugin "${e.id}" must have a valid name`);if(!e.version||"string"!=typeof e.version)throw new Error(`Plugin "${e.id}" must have a valid version`);if(!e.type||"string"!=typeof e.type)throw new Error(`Plugin "${e.id}" must have a valid type`);if("function"!=typeof e.init)throw new Error(`Plugin "${e.id}" must have an init() method`);if("function"!=typeof e.destroy)throw new Error(`Plugin "${e.id}" must have a destroy() method`)}}class g{constructor(e){if(this._currentProvider=null,this.destroyed=!1,this.seekingWhilePlaying=!1,this.seekResumeTimeout=null,"string"==typeof e.container){const t=document.querySelector(e.container);if(!(t&&t instanceof HTMLElement))throw new Error(`ScarlettPlayer: container not found: ${e.container}`);this.container=t}else{if(!(e.container instanceof HTMLElement))throw new Error("ScarlettPlayer requires a valid HTMLElement container or CSS selector");this.container=e.container}if(this.initialSrc=e.src,this.eventBus=new a,this.stateManager=new r({autoplay:e.autoplay??!1,loop:e.loop??!1,volume:e.volume??1,muted:e.muted??!1}),this.logger=new h({level:e.logLevel??"warn",scope:"ScarlettPlayer"}),this.errorHandler=new c(this.eventBus,this.logger),this.pluginManager=new f(this.eventBus,this.stateManager,this.logger,{container:this.container}),e.plugins)for(const t of e.plugins)this.pluginManager.register(t);this.logger.info("ScarlettPlayer initialized",{autoplay:e.autoplay,plugins:e.plugins?.length??0}),this.eventBus.emit("player:ready",void 0)}async init(){this.checkDestroyed();for(const[e,t]of this.pluginManager.plugins)"provider"!==t.plugin.type&&"registered"===t.state&&await this.pluginManager.initPlugin(e);return this.initialSrc&&await this.load(this.initialSrc),Promise.resolve()}async load(e){this.checkDestroyed();try{if(this.logger.info("Loading source",{source:e}),this.stateManager.update({playing:!1,paused:!0,ended:!1,buffering:!0,currentTime:0,duration:0,bufferedAmount:0,playbackState:"loading"}),this._currentProvider){const e=this._currentProvider.id;this.logger.info("Destroying previous provider",{provider:e}),await this.pluginManager.destroyPlugin(e),this._currentProvider=null}const t=this.pluginManager.selectProvider(e);if(!t)return void this.errorHandler.throw(d.PROVIDER_NOT_FOUND,`No provider found for source: ${e}`,{fatal:!0,context:{source:e}});this._currentProvider=t,this.logger.info("Provider selected",{provider:t.id}),await this.pluginManager.initPlugin(t.id),this.stateManager.set("source",{src:e,type:this.detectMimeType(e)}),"function"==typeof t.loadSource&&await t.loadSource(e),this.stateManager.getValue("autoplay")&&await this.play()}catch(t){this.errorHandler.handle(t,{operation:"load",source:e})}}async play(){this.checkDestroyed();try{this.logger.debug("Play requested"),this.stateManager.update({playing:!0,paused:!1,playbackState:"playing"}),this.eventBus.emit("playback:play",void 0)}catch(e){this.errorHandler.handle(e,{operation:"play"})}}pause(){this.checkDestroyed();try{this.logger.debug("Pause requested"),this.seekingWhilePlaying=!1,null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.stateManager.update({playing:!1,paused:!0,playbackState:"paused"}),this.eventBus.emit("playback:pause",void 0)}catch(e){this.errorHandler.handle(e,{operation:"pause"})}}seek(e){this.checkDestroyed();try{this.logger.debug("Seek requested",{time:e});this.stateManager.getValue("playing")&&(this.seekingWhilePlaying=!0),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:seeking",{time:e}),this.stateManager.set("currentTime",e),this.seekingWhilePlaying&&(this.seekResumeTimeout=setTimeout(()=>{this.seekingWhilePlaying&&this.stateManager.getValue("playing")&&(this.logger.debug("Resuming playback after seek"),this.seekingWhilePlaying=!1,this.eventBus.emit("playback:play",void 0)),this.seekResumeTimeout=null},300))}catch(t){this.errorHandler.handle(t,{operation:"seek",time:e})}}setVolume(e){this.checkDestroyed();const t=Math.max(0,Math.min(1,e));this.stateManager.set("volume",t),this.eventBus.emit("volume:change",{volume:t,muted:this.stateManager.getValue("muted")})}setMuted(e){this.checkDestroyed(),this.stateManager.set("muted",e),this.eventBus.emit("volume:mute",{muted:e})}setPlaybackRate(e){this.checkDestroyed(),this.stateManager.set("playbackRate",e),this.eventBus.emit("playback:ratechange",{rate:e})}setAutoplay(e){this.checkDestroyed(),this.stateManager.set("autoplay",e),this.logger.debug("Autoplay set",{autoplay:e})}on(e,t){return this.checkDestroyed(),this.eventBus.on(e,t)}once(e,t){return this.checkDestroyed(),this.eventBus.once(e,t)}getPlugin(e){return this.checkDestroyed(),this.pluginManager.getPlugin(e)}registerPlugin(e){this.checkDestroyed(),this.pluginManager.register(e)}getState(){return this.checkDestroyed(),this.stateManager.snapshot()}getQualities(){if(this.checkDestroyed(),!this._currentProvider)return[];const e=this._currentProvider;return"function"==typeof e.getLevels?e.getLevels():[]}setQuality(e){if(this.checkDestroyed(),!this._currentProvider)return void this.logger.warn("No provider available for quality change");const t=this._currentProvider;"function"==typeof t.setLevel&&(t.setLevel(e),this.eventBus.emit("quality:change",{quality:-1===e?"auto":`level-${e}`,auto:-1===e}))}getCurrentQuality(){if(this.checkDestroyed(),!this._currentProvider)return-1;const e=this._currentProvider;return"function"==typeof e.getCurrentLevel?e.getCurrentLevel():-1}async requestFullscreen(){this.checkDestroyed();try{this.container.requestFullscreen?await this.container.requestFullscreen():this.container.webkitRequestFullscreen&&await this.container.webkitRequestFullscreen(),this.stateManager.set("fullscreen",!0),this.eventBus.emit("fullscreen:change",{fullscreen:!0})}catch(e){this.logger.error("Fullscreen request failed",{error:e})}}async exitFullscreen(){this.checkDestroyed();try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen&&await document.webkitExitFullscreen(),this.stateManager.set("fullscreen",!1),this.eventBus.emit("fullscreen:change",{fullscreen:!1})}catch(e){this.logger.error("Exit fullscreen failed",{error:e})}}async toggleFullscreen(){this.fullscreen?await this.exitFullscreen():await this.requestFullscreen()}requestAirPlay(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.showPicker?e.showPicker():this.logger.warn("AirPlay plugin not available")}async requestChromecast(){this.checkDestroyed();const e=this.pluginManager.getPlugin("chromecast");e&&"function"==typeof e.requestSession?await e.requestSession():this.logger.warn("Chromecast plugin not available")}stopCasting(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.stop&&e.stop();const t=this.pluginManager.getPlugin("chromecast");t&&"function"==typeof t.stopSession&&t.stopSession()}seekToLive(){this.checkDestroyed();if(!this.stateManager.getValue("live"))return void this.logger.warn("Not a live stream");if(this._currentProvider){const e=this._currentProvider;if("function"==typeof e.getLiveInfo){const t=e.getLiveInfo();if(void 0!==t?.liveSyncPosition)return void this.seek(t.liveSyncPosition)}}const e=this.stateManager.getValue("duration");e>0&&this.seek(e)}destroy(){this.destroyed||(this.logger.info("Destroying player"),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("player:destroy",void 0),this.pluginManager.destroyAll(),this.eventBus.destroy(),this.stateManager.destroy(),this.destroyed=!0,this.logger.info("Player destroyed"))}get playing(){return this.stateManager.getValue("playing")}get paused(){return this.stateManager.getValue("paused")}get currentTime(){return this.stateManager.getValue("currentTime")}get duration(){return this.stateManager.getValue("duration")}get volume(){return this.stateManager.getValue("volume")}get muted(){return this.stateManager.getValue("muted")}get playbackRate(){return this.stateManager.getValue("playbackRate")}get bufferedAmount(){return this.stateManager.getValue("bufferedAmount")}get currentProvider(){return this._currentProvider}get fullscreen(){return this.stateManager.getValue("fullscreen")}get live(){return this.stateManager.getValue("live")}get autoplay(){return this.stateManager.getValue("autoplay")}checkDestroyed(){if(this.destroyed)throw new Error("Cannot call methods on destroyed player")}detectMimeType(e){const t=e.split(".").pop()?.toLowerCase();switch(t){case"m3u8":return"application/x-mpegURL";case"mpd":return"application/dash+xml";case"mp4":default:return"video/mp4";case"webm":return"video/webm";case"ogg":return"video/ogg"}}}var m=null,p=null;function v(){if("undefined"==typeof document)return!1;return""!==document.createElement("video").canPlayType("application/vnd.apple.mpegurl")}function y(){return m?m.isSupported():"undefined"!=typeof window&&!(!window.MediaSource&&!window.WebKitMediaSource)}function E(e){if(e.name)return e.name;if(e.height){const t={2160:"4K",1440:"1440p",1080:"1080p",720:"720p",480:"480p",360:"360p",240:"240p",144:"144p"},s=Object.keys(t).map(Number).sort((t,s)=>Math.abs(t-e.height)-Math.abs(s-e.height))[0];return Math.abs(s-e.height)<=20?t[s]:`${e.height}p`}return e.bitrate?function(e){if(e>=1e6)return`${(e/1e6).toFixed(1)} Mbps`;if(e>=1e3)return`${Math.round(e/1e3)} Kbps`;return`${e} bps`}(e.bitrate):"Unknown"}var T="networkError",S="mediaError",L="muxError";function b(e){switch(e){case T:return"network";case S:return"media";case L:return"mux";default:return"other"}}function A(e,t,s){const i=[],r=(t,s)=>{e.on(t,s),i.push({event:t,handler:s})};return r("hlsManifestParsed",(i,r)=>{t.logger.debug("HLS manifest parsed",{levels:r.levels.length});const n=r.levels.map((t,s)=>({id:`level-${s}`,label:E(t),width:t.width,height:t.height,bitrate:t.bitrate,active:s===e.currentLevel}));t.setState("qualities",n),t.emit("quality:levels",{levels:n.map(e=>({id:e.id,label:e.label}))}),s.onManifestParsed?.(r.levels)}),r("hlsLevelSwitched",(i,r)=>{const n=e.levels[r.level],a=s.getIsAutoQuality?.()??e.autoLevelEnabled;if(t.logger.debug("HLS level switched",{level:r.level,height:n?.height,auto:a}),n){const e=a?`Auto (${E(n)})`:E(n);t.setState("currentQuality",{id:a?"auto":`level-${r.level}`,label:e,width:n.width,height:n.height,bitrate:n.bitrate,active:!0})}t.emit("quality:change",{quality:n?E(n):"auto",auto:a}),s.onLevelSwitched?.(r.level)}),r("hlsFragBuffered",()=>{t.setState("buffering",!1),s.onBufferUpdate?.()}),r("hlsFragLoading",()=>{t.setState("buffering",!0)}),r("hlsLevelLoaded",(e,i)=>{void 0!==i.details?.live&&(t.setState("live",i.details.live),s.onLiveUpdate?.())}),r("hlsError",(e,i)=>{const r=function(e){return{type:b(e.type),details:e.details||"Unknown error",fatal:e.fatal||!1,url:e.url,reason:e.reason,response:e.response}}(i);t.logger.warn("HLS error",{error:r}),s.onError?.(r)}),()=>{for(const{event:t,handler:s}of i)e.off(t,s);i.length=0}}function R(e,t){const s=[],i=(t,i)=>{e.addEventListener(t,i),s.push({event:t,handler:i})};i("playing",()=>{t.setState("playing",!0),t.setState("paused",!1),t.setState("playbackState","playing")}),i("pause",()=>{t.setState("playing",!1),t.setState("paused",!0),t.setState("playbackState","paused")}),i("ended",()=>{t.setState("playing",!1),t.setState("ended",!0),t.setState("playbackState","ended"),t.emit("playback:ended",void 0)}),i("timeupdate",()=>{t.setState("currentTime",e.currentTime),t.emit("playback:timeupdate",{currentTime:e.currentTime})}),i("durationchange",()=>{t.setState("duration",e.duration||0),t.emit("media:loadedmetadata",{duration:e.duration||0})}),i("waiting",()=>{t.setState("waiting",!0),t.setState("buffering",!0),t.emit("media:waiting",void 0)}),i("canplay",()=>{t.setState("waiting",!1),t.setState("playbackState","ready"),t.emit("media:canplay",void 0)}),i("canplaythrough",()=>{t.setState("buffering",!1),t.emit("media:canplaythrough",void 0)}),i("progress",()=>{if(e.buffered.length>0){const s=e.buffered.end(e.buffered.length-1),i=e.duration>0?s/e.duration:0;t.setState("bufferedAmount",i),t.setState("buffered",e.buffered),t.emit("media:progress",{buffered:i})}}),i("seeking",()=>{t.setState("seeking",!0)}),i("seeked",()=>{t.setState("seeking",!1),t.emit("playback:seeked",{time:e.currentTime})}),i("volumechange",()=>{t.setState("volume",e.volume),t.setState("muted",e.muted),t.emit("volume:change",{volume:e.volume,muted:e.muted})}),i("ratechange",()=>{t.setState("playbackRate",e.playbackRate),t.emit("playback:ratechange",{rate:e.playbackRate})}),i("loadedmetadata",()=>{t.setState("duration",e.duration),t.setState("mediaType",e.videoWidth>0?"video":"audio")}),i("error",()=>{const s=e.error;s&&(t.logger.error("Video element error",{code:s.code,message:s.message}),t.emit("media:error",{error:new Error(s.message||"Video playback error")}))}),i("enterpictureinpicture",()=>{t.setState("pip",!0),t.logger.debug("PiP: entered (standard)")}),i("leavepictureinpicture",()=>{t.setState("pip",!1),t.logger.debug("PiP: exited (standard)"),e.paused&&!t.getState("playing")||e.play().catch(()=>{})});const r=e;return"webkitPresentationMode"in e&&i("webkitpresentationmodechanged",()=>{const s=r.webkitPresentationMode,i="picture-in-picture"===s;t.setState("pip",i),t.logger.debug(`PiP: mode changed to ${s} (webkit)`),"inline"===s&&e.paused&&e.play().catch(()=>{})}),()=>{for(const{event:t,handler:i}of s)e.removeEventListener(t,i);s.length=0}}var I={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 k(e){const t={...I,...e};let s=null,i=null,r=null,n=!1,a=null,o=null,l=null,h=!0,d=0,c=0,u=null,f=0,g=0;const T=()=>{if(r)return r;const e=s?.container.querySelector("video");return e?(r=e,r):(r=document.createElement("video"),r.style.cssText="width:100%;height:100%;display:block;object-fit:contain;background:#000",r.preload="metadata",r.controls=!1,r.playsInline=!0,s?.container.appendChild(r),r)},S=()=>{o?.(),o=null,l?.(),l=null,u&&(clearTimeout(u),u=null),i&&(i.destroy(),i=null),a=null,n=!1,h=!0,d=0,c=0,f=0,g=0},L=e=>{const s=t.retryDelayMs??1e3,i=t.retryBackoffFactor??2;return s*Math.pow(i,e)},b=(e,t)=>{const i=t?`HLS error: ${e.details} (max retries exceeded)`:`HLS error: ${e.details}`;s?.logger.error(i,{type:e.type,details:e.details}),s?.setState("playbackState","error"),s?.setState("buffering",!1),s?.emit("error",{code:"MEDIA_ERROR",message:i,fatal:!0,timestamp:Date.now()})},k=e=>{if(!m||!i)return;const r=Date.now();if(r-g>5e3?(f=1,g=r):f++,f>=10)return s?.logger.error(`Too many errors (${f} in 5000ms), giving up`),b(e,!0),o?.(),o=null,i.destroy(),void(i=null);if(e.fatal)switch(s?.logger.error("Fatal HLS error",{type:e.type,details:e.details}),e.type){case"network":{const r=t.maxNetworkRetries??3;if(d>=r)return s?.logger.error(`Network error recovery failed after ${d} attempts`),void b(e,!0);d++;const n=L(d-1);s?.logger.info(`Attempting network error recovery (attempt ${d}/${r}) in ${n}ms`),s?.emit("error:network",{error:new Error(e.details)}),u&&clearTimeout(u),u=setTimeout(()=>{i&&i.startLoad()},n);break}case"media":{const r=t.maxMediaRetries??2;if(c>=r)return s?.logger.error(`Media error recovery failed after ${c} attempts`),void b(e,!0);c++;const n=L(c-1);s?.logger.info(`Attempting media error recovery (attempt ${c}/${r}) in ${n}ms`),s?.emit("error:media",{error:new Error(e.details)}),u&&clearTimeout(u),u=setTimeout(()=>{i&&i.recoverMediaError()},n);break}default:b(e,!1)}},D=async e=>{const t=T();return n=!0,s&&(l=R(t,s)),new Promise((i,r)=>{const n=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a),s?.setState("source",{src:e,type:"application/x-mpegURL"}),s?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),i()},a=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a);const e=t.error;r(new Error(e?.message||"Failed to load HLS source"))};t.addEventListener("loadedmetadata",n),t.addEventListener("error",a),t.src=e,t.load()})},P=async e=>{await async function(){return m||p||(p=(async()=>{try{const e=await Promise.resolve().then(()=>mh);if(!(m=e.default).isSupported())throw new Error("hls.js is not supported in this browser");return m}catch(e){throw p=null,new Error(`Failed to load hls.js: ${e instanceof Error?e.message:"Unknown error"}`)}})())}();const r=T();return n=!1,i=function(e){if(!m)throw new Error("hls.js is not loaded. Call loadHlsJs() first.");return new m(e)}({debug:t.debug,autoStartLoad:t.autoStartLoad,startPosition:t.startPosition,startLevel:-1,lowLatencyMode:t.lowLatencyMode,maxBufferLength:t.maxBufferLength,maxMaxBufferLength:t.maxMaxBufferLength,backBufferLength:t.backBufferLength,enableWorker:t.enableWorker,fragLoadingMaxRetry:1,manifestLoadingMaxRetry:1,levelLoadingMaxRetry:1,fragLoadingRetryDelay:500,manifestLoadingRetryDelay:500,levelLoadingRetryDelay:500}),s&&(l=R(r,s)),new Promise((t,n)=>{if(!i||!s)return void n(new Error("HLS not initialized"));let a=!1;o=A(i,s,{onManifestParsed:()=>{a||(a=!0,s?.setState("source",{src:e,type:"application/x-mpegURL"}),s?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),t())},onLevelSwitched:()=>{},onError:e=>{k(e),e.fatal&&!a&&"network"!==e.type&&"media"!==e.type&&(a=!0,n(new Error(e.details)))},getIsAutoQuality:()=>h}),i.attachMedia(r),i.loadSource(e)})};return{id:"hls-provider",name:"HLS Provider",version:"1.0.0",type:"provider",description:"HLS playback provider using hls.js",canPlay(e){if(!v()&&!y())return!1;const t=e.toLowerCase();return!!t.split("?")[0].split("#")[0].endsWith(".m3u8")||(!!t.includes("application/x-mpegurl")||!!t.includes("application/vnd.apple.mpegurl"))},async init(e){s=e,s.logger.info("HLS plugin initialized");const t=s.on("playback:play",async()=>{if(r)try{await r.play()}catch(e){s?.logger.error("Play failed",e)}}),a=s.on("playback:pause",()=>{r?.pause()}),o=s.on("playback:seeking",({time:e})=>{if(!r)return;const t=Math.max(0,Math.min(e,r.duration||0));r.currentTime=t}),l=s.on("volume:change",({volume:e})=>{r&&(r.volume=e)}),d=s.on("volume:mute",({muted:e})=>{r&&(r.muted=e)}),c=s.on("playback:ratechange",({rate:e})=>{r&&(r.playbackRate=e)}),u=s.on("quality:select",({quality:e,auto:t})=>{if(i&&!n)if(t||"auto"===e)h=!0,i.currentLevel=-1,s?.logger.debug("Quality: auto selection enabled"),s?.setState("currentQuality",{id:"auto",label:"Auto",width:0,height:0,bitrate:0,active:!0});else{h=!1;const t=parseInt(e.replace("level-",""),10);!isNaN(t)&&t>=0&&t<i.levels.length&&(i.nextLevel=t,s?.logger.debug(`Quality: queued switch to level ${t}`))}else s?.logger.warn("Quality selection not available")});s.onDestroy(()=>{t(),a(),o(),l(),d(),c(),u()})},async destroy(){s?.logger.info("HLS plugin destroying"),S(),r?.parentNode&&r.parentNode.removeChild(r),r=null,s=null},async loadSource(e){if(!s)throw new Error("Plugin not initialized");if(s.logger.info("Loading HLS source",{src:e}),S(),a=e,s.setState("playbackState","loading"),s.setState("buffering",!0),y())s.logger.info("Using hls.js for HLS playback"),await P(e);else{if(!v())throw new Error("HLS playback not supported in this browser");s.logger.info("Using native HLS playback (hls.js not supported)"),await D(e)}s.setState("playbackState","ready"),s.setState("buffering",!1)},getCurrentLevel:()=>n||!i?-1:i.currentLevel,setLevel(e){!n&&i?i.currentLevel=e:s?.logger.warn("Quality selection not available in native HLS mode")},getLevels(){return n||!i?[]:(e=i.levels,i.currentLevel,e.map((e,t)=>({index:t,width:e.width||0,height:e.height||0,bitrate:e.bitrate||0,label:E(e),codec:e.codecSet})));var e},getHlsInstance:()=>i,isNativeHLS:()=>n,getLiveInfo(){if(n||!i)return null;return s?.getState("live")||!1?{isLive:!0,latency:i.latency||0,targetLatency:i.targetLatency||3,drift:i.drift||0}:null},async switchToNative(){if(n)return void s?.logger.debug("Already using native HLS");if(!v())return void s?.logger.warn("Native HLS not supported in this browser");if(!a)return void s?.logger.warn("No source loaded");s?.logger.info("Switching to native HLS for AirPlay");const e=s?.getState("playing")||!1,t=r?.currentTime||0,i=a;if(S(),await D(i),r&&t>0&&(r.currentTime=t),e&&r)try{await r.play()}catch(o){s?.logger.debug("Could not auto-resume after switch")}s?.logger.info("Switched to native HLS")},async switchToHlsJs(){if(!n)return void s?.logger.debug("Already using hls.js");if(!y())return void s?.logger.warn("hls.js not supported in this browser");if(!a)return void s?.logger.warn("No source loaded");s?.logger.info("Switching back to hls.js");const e=s?.getState("playing")||!1,t=r?.currentTime||0,i=a;if(S(),await P(i),r&&t>0&&(r.currentTime=t),e&&r)try{await r.play()}catch(o){s?.logger.debug("Could not auto-resume after switch")}s?.logger.info("Switched to hls.js")}}}var D={play:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',pause:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/></svg>',replay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>',volumeHigh:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',volumeLow:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',volumeMute:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/></svg>',fullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>',exitFullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/></svg>',pip:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z"/></svg>',settings:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>',chromecast:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',chromecastConnected:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',airplay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 22h12l-6-6-6 6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',spinner:'<svg viewBox="0 0 24 24" fill="currentColor" class="sp-spin"><path d="M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8z"/></svg>'};function P(e,t,s){const i=document.createElement(e);if(t)for(const[r,n]of Object.entries(t))"className"===r?i.className=n:i.setAttribute(r,n);return i}function w(e,t,s){const i=P("button",{className:`sp-control ${e}`,"aria-label":t,type:"button"});return i.innerHTML=s,i}function _(e){return e.querySelector("video")}function C(e){if(!isFinite(e)||isNaN(e))return"0:00";const t=Math.abs(e),s=Math.floor(t/3600),i=Math.floor(t%3600/60),r=Math.floor(t%60),n=e<0?"-":"";return s>0?`${n}${s}:${x(i)}:${x(r)}`:`${n}${i}:${x(r)}`}function x(e){return e<10?`0${e}`:`${e}`}function M(e){return e<=0?"LIVE":`-${C(e)}`}var O=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=w("sp-play","Play",D.play),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){const e=this.api.getState("playing");let t,s;this.api.getState("ended")?(t=D.replay,s="Replay"):e?(t=D.pause,s="Pause"):(t=D.play,s="Play"),this.el.innerHTML=t,this.el.setAttribute("aria-label",s)}toggle(){const e=_(this.api.container);if(!e)return;const t=this.api.getState("ended"),s=this.api.getState("playing");t?(e.currentTime=0,e.play().catch(()=>{})):s?e.pause():e.play().catch(()=>{})}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},F=class{constructor(e){this.isDragging=!1,this.lastSeekTime=0,this.seekThrottleMs=100,this.wasPlayingBeforeDrag=!1,this.onMouseDown=e=>{e.preventDefault();const t=_(this.api.container);this.wasPlayingBeforeDrag=!!t&&!t.paused,this.isDragging=!0,this.el.classList.add("sp-progress--dragging"),this.lastSeekTime=0,this.seek(e.clientX,!0)},this.onDocMouseMove=e=>{this.isDragging&&(this.seek(e.clientX),this.updateVisualPosition(e.clientX))},this.onMouseUp=e=>{if(this.isDragging&&(this.seek(e.clientX,!0),this.isDragging=!1,this.el.classList.remove("sp-progress--dragging"),this.wasPlayingBeforeDrag)){const e=_(this.api.container);if(e&&e.paused){const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t)}}},this.onMouseMove=e=>{this.updateTooltip(e.clientX)},this.onMouseLeave=()=>{this.isDragging||(this.tooltip.style.opacity="0")},this.onKeyDown=e=>{const t=_(this.api.container);if(!t)return;const s=this.api.getState("duration")||0;switch(e.key){case"ArrowLeft":e.preventDefault(),t.currentTime=Math.max(0,t.currentTime-5);break;case"ArrowRight":e.preventDefault(),t.currentTime=Math.min(s,t.currentTime+5);break;case"Home":e.preventDefault(),t.currentTime=0;break;case"End":e.preventDefault(),t.currentTime=s}},this.api=e,this.wrapper=P("div",{className:"sp-progress-wrapper"}),this.el=P("div",{className:"sp-progress"});const t=P("div",{className:"sp-progress__track"});this.buffered=P("div",{className:"sp-progress__buffered"}),this.filled=P("div",{className:"sp-progress__filled"}),this.handle=P("div",{className:"sp-progress__handle"}),this.tooltip=P("div",{className:"sp-progress__tooltip"}),this.tooltip.textContent="0:00",t.appendChild(this.buffered),t.appendChild(this.filled),t.appendChild(this.handle),this.el.appendChild(t),this.el.appendChild(this.tooltip),this.wrapper.appendChild(this.el),this.el.setAttribute("role","slider"),this.el.setAttribute("aria-label","Seek"),this.el.setAttribute("aria-valuemin","0"),this.el.setAttribute("tabindex","0"),this.wrapper.addEventListener("mousedown",this.onMouseDown),this.wrapper.addEventListener("mousemove",this.onMouseMove),this.wrapper.addEventListener("mouseleave",this.onMouseLeave),this.el.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.wrapper}show(){this.wrapper.classList.add("sp-progress-wrapper--visible")}hide(){this.wrapper.classList.remove("sp-progress-wrapper--visible")}update(){const e=this.api.getState("currentTime")||0,t=this.api.getState("duration")||0,s=this.api.getState("buffered");if(t>0){const i=e/t*100;if(this.filled.style.width=`${i}%`,this.handle.style.left=`${i}%`,s&&s.length>0){const e=s.end(s.length-1)/t*100;this.buffered.style.width=`${e}%`}this.el.setAttribute("aria-valuemax",String(Math.floor(t))),this.el.setAttribute("aria-valuenow",String(Math.floor(e))),this.el.setAttribute("aria-valuetext",C(e))}}getTimeFromPosition(e){const t=this.el.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*(this.api.getState("duration")||0)}updateTooltip(e){const t=this.el.getBoundingClientRect(),s=Math.max(0,Math.min(1,(e-t.left)/t.width)),i=this.getTimeFromPosition(e);this.tooltip.textContent=C(i),this.tooltip.style.left=100*s+"%"}updateVisualPosition(e){const t=this.el.getBoundingClientRect(),s=Math.max(0,Math.min(1,(e-t.left)/t.width));this.filled.style.width=100*s+"%",this.handle.style.left=100*s+"%"}seek(e,t=!1){const s=_(this.api.container);if(!s)return;const i=Date.now();if(!t&&this.isDragging&&i-this.lastSeekTime<this.seekThrottleMs)return;this.lastSeekTime=i;const r=this.getTimeFromPosition(e);s.currentTime=r}destroy(){this.wrapper.removeEventListener("mousedown",this.onMouseDown),this.wrapper.removeEventListener("mousemove",this.onMouseMove),this.wrapper.removeEventListener("mouseleave",this.onMouseLeave),document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.wrapper.remove()}},N=class{constructor(e){this.api=e,this.el=P("div",{className:"sp-time"}),this.el.setAttribute("aria-live","off")}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("currentTime")||0,s=this.api.getState("duration")||0;if(e){const e=this.api.getState("seekableRange");if(e){const s=e.end-t;this.el.textContent=M(s)}else this.el.textContent=M(0)}else this.el.textContent=`${C(t)} / ${C(s)}`}destroy(){this.el.remove()}},B=class{constructor(e){this.isDragging=!1,this.onMouseDown=e=>{e.preventDefault(),this.isDragging=!0,this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onDocMouseMove=e=>{this.isDragging&&this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onMouseUp=()=>{this.isDragging=!1},this.onKeyDown=e=>{const t=_(this.api.container);if(!t)return;switch(e.key){case"ArrowUp":case"ArrowRight":e.preventDefault(),this.setVolume(t.volume+.1);break;case"ArrowDown":case"ArrowLeft":e.preventDefault(),this.setVolume(t.volume-.1)}},this.api=e,this.el=P("div",{className:"sp-volume"}),this.btn=P("button",{className:"sp-control sp-volume__btn","aria-label":"Mute",type:"button"}),this.btn.innerHTML=D.volumeHigh,this.btn.onclick=()=>this.toggleMute();const t=P("div",{className:"sp-volume__slider-wrap"});this.slider=P("div",{className:"sp-volume__slider"}),this.slider.setAttribute("role","slider"),this.slider.setAttribute("aria-label","Volume"),this.slider.setAttribute("aria-valuemin","0"),this.slider.setAttribute("aria-valuemax","100"),this.slider.setAttribute("tabindex","0"),this.level=P("div",{className:"sp-volume__level"}),this.slider.appendChild(this.level),t.appendChild(this.slider),this.el.appendChild(this.btn),this.el.appendChild(t),this.slider.addEventListener("mousedown",this.onMouseDown),this.slider.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.el}update(){const e=this.api.getState("volume")??1,t=this.api.getState("muted")??!1;let s,i;t||0===e?(s=D.volumeMute,i="Unmute"):e<.5?(s=D.volumeLow,i="Mute"):(s=D.volumeHigh,i="Mute"),this.btn.innerHTML=s,this.btn.setAttribute("aria-label",i);const r=t?0:e;this.level.style.width=100*r+"%",this.slider.setAttribute("aria-valuenow",String(Math.round(100*r)))}toggleMute(){const e=_(this.api.container);e&&(e.muted=!e.muted)}setVolume(e){const t=_(this.api.container);if(!t)return;const s=Math.max(0,Math.min(1,e));t.volume=s,s>0&&t.muted&&(t.muted=!1)}getVolumeFromPosition(e){const t=this.slider.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))}destroy(){document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.el.remove()}},U=class{constructor(e){this.api=e,this.el=P("div",{className:"sp-live"}),this.el.innerHTML='<div class="sp-live__dot"></div><span>LIVE</span>',this.el.setAttribute("role","button"),this.el.setAttribute("aria-label","Seek to live"),this.el.setAttribute("tabindex","0"),this.el.onclick=()=>this.seekToLive(),this.el.onkeydown=e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.seekToLive())}}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("liveEdge");this.el.style.display=e?"":"none",t?this.el.classList.remove("sp-live--behind"):this.el.classList.add("sp-live--behind")}seekToLive(){const e=_(this.api.container);if(!e)return;const t=this.api.getState("seekableRange");t&&(e.currentTime=t.end)}destroy(){this.el.remove()}},$=class{constructor(e){this.isOpen=!1,this.lastQualitiesJson="",this.api=e,this.el=P("div",{className:"sp-quality"}),this.btn=w("sp-quality__btn","Quality",D.settings),this.btnLabel=P("span",{className:"sp-quality__label"}),this.btnLabel.textContent="Auto",this.btn.appendChild(this.btnLabel),this.btn.addEventListener("click",e=>{e.stopPropagation(),this.toggle()}),this.menu=P("div",{className:"sp-quality-menu"}),this.menu.setAttribute("role","menu"),this.menu.addEventListener("click",e=>{e.stopPropagation()}),this.el.appendChild(this.btn),this.el.appendChild(this.menu),this.closeHandler=e=>{this.el.contains(e.target)||this.close()},document.addEventListener("click",this.closeHandler)}render(){return this.el}update(){const e=this.api.getState("qualities")||[],t=this.api.getState("currentQuality");this.el.style.display=e.length>0?"":"none",this.btnLabel.textContent=t?.label||"Auto";const s=JSON.stringify(e.map(e=>e.id)),i=t?.id||"auto";s!==this.lastQualitiesJson&&(this.lastQualitiesJson=s,this.rebuildMenu(e)),this.updateActiveStates(i)}rebuildMenu(e){this.menu.innerHTML="";const t=this.createMenuItem("Auto","auto");this.menu.appendChild(t);const s=[...e].sort((e,t)=>t.height-e.height);for(const i of s){if("auto"===i.id)continue;const e=this.createMenuItem(i.label,i.id);this.menu.appendChild(e)}}updateActiveStates(e){this.menu.querySelectorAll(".sp-quality-menu__item").forEach(t=>{const s=t.getAttribute("data-quality-id")===e;t.classList.toggle("sp-quality-menu__item--active",s)})}createMenuItem(e,t){const s=P("div",{className:"sp-quality-menu__item"});s.setAttribute("role","menuitem"),s.setAttribute("data-quality-id",t);const i=P("span",{className:"sp-quality-menu__label"});return i.textContent=e,s.appendChild(i),s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.selectQuality(t)}),s}selectQuality(e){this.api.emit("quality:select",{quality:e,auto:"auto"===e}),this.close()}toggle(){this.isOpen?this.close():this.open()}open(){this.isOpen=!0,this.menu.classList.add("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","true")}close(){this.isOpen=!1,this.menu.classList.remove("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","false")}destroy(){document.removeEventListener("click",this.closeHandler),this.el.remove()}};var G=class{constructor(e,t){this.api=e,this.type=t,this.supported="chromecast"===t?function(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent;return/Chrome/.test(e)&&!/Edge|Edg/.test(e)}():"undefined"!=typeof HTMLVideoElement&&"function"==typeof HTMLVideoElement.prototype.webkitShowPlaybackTargetPicker;const s="chromecast"===t?D.chromecast:D.airplay,i="chromecast"===t?"Cast":"AirPlay";this.el=w(`sp-cast sp-cast--${t}`,i,s),this.el.addEventListener("click",()=>this.handleClick()),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(this.supported)if("chromecast"===this.type){const e=this.api.getState("chromecastAvailable"),t=this.api.getState("chromecastActive");this.el.style.display="",this.el.disabled=!e&&!t,this.el.classList.toggle("sp-cast--active",!!t),this.el.classList.toggle("sp-cast--unavailable",!e&&!t),t?(this.el.innerHTML=D.chromecastConnected,this.el.setAttribute("aria-label","Stop casting")):(this.el.innerHTML=D.chromecast,this.el.setAttribute("aria-label",e?"Cast":"No Cast devices found"))}else{const e=this.api.getState("airplayActive");this.el.style.display="",this.el.disabled=!1,this.el.classList.toggle("sp-cast--active",!!e),this.el.classList.remove("sp-cast--unavailable"),this.el.setAttribute("aria-label",e?"Stop AirPlay":"AirPlay")}else this.el.style.display="none"}handleClick(){"chromecast"===this.type?this.handleChromecast():this.handleAirPlay()}handleChromecast(){const e=this.api.getPlugin("chromecast");e&&(e.isConnected()?e.endSession():e.requestSession().catch(()=>{}))}async handleAirPlay(){const e=this.api.getPlugin("airplay");if(e)await e.showPicker();else{const e=_(this.api.container);e?.webkitShowPlaybackTargetPicker?.()}}destroy(){this.el.remove()}},K=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e;const t=document.createElement("video");this.supported="pictureInPictureEnabled"in document||"webkitSetPresentationMode"in t,this.el=w("sp-pip","Picture-in-Picture",D.pip),this.el.addEventListener("click",this.clickHandler),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(!this.supported)return;const e=this.api.getState("pip");this.el.setAttribute("aria-label",e?"Exit Picture-in-Picture":"Picture-in-Picture"),this.el.classList.toggle("sp-pip--active",!!e)}async toggle(){const e=_(this.api.container);if(e)try{document.pictureInPictureElement===e||"picture-in-picture"===e.webkitPresentationMode?(document.pictureInPictureElement?await document.exitPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("inline"),this.api.logger.debug("PiP: exited")):(e.requestPictureInPicture?await e.requestPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("picture-in-picture"),this.api.logger.debug("PiP: entered"))}catch(t){this.api.logger.warn("PiP: failed",{error:t.message})}else this.api.logger.warn("PiP: video element not found")}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},H=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=w("sp-fullscreen","Fullscreen",D.fullscreen),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){this.api.getState("fullscreen")?(this.el.innerHTML=D.exitFullscreen,this.el.setAttribute("aria-label","Exit fullscreen")):(this.el.innerHTML=D.fullscreen,this.el.setAttribute("aria-label","Fullscreen"))}async toggle(){const e=this.api.container,t=_(e);try{document.fullscreenElement?await document.exitFullscreen():e.requestFullscreen?await e.requestFullscreen():t?.webkitEnterFullscreen&&t.webkitEnterFullscreen()}catch{}}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},V=class{constructor(){this.el=P("div",{className:"sp-spacer"})}render(){return this.el}update(){}destroy(){this.el.remove()}},Y=["play","volume","time","live-indicator","spacer","quality","chromecast","airplay","pip","fullscreen"];function q(e,...t){for(const s of t){const t=e.getAttribute(s);if(null!==t)return t}return null}function j(e){const t={},s=q(e,"data-src","src","href");s&&(t.src=s);const i=q(e,"data-autoplay","autoplay");null!==i&&(t.autoplay="false"!==i);const r=q(e,"data-muted","muted");null!==r&&(t.muted="false"!==r);const n=q(e,"data-controls","controls");null!==n&&(t.controls="false"!==n);const a=q(e,"data-keyboard","keyboard");null!==a&&(t.keyboard="false"!==a);const o=q(e,"data-loop","loop");null!==o&&(t.loop="false"!==o);const l=q(e,"data-poster","poster");l&&(t.poster=l);const h=q(e,"data-brand-color","data-color","color");h&&(t.brandColor=h);const d=e.getAttribute("data-primary-color");d&&(t.primaryColor=d);const c=e.getAttribute("data-background-color");c&&(t.backgroundColor=c);const u=e.getAttribute("data-width");u&&(t.width=u);const f=e.getAttribute("data-height");f&&(t.height=f);const g=e.getAttribute("data-aspect-ratio");g&&(t.aspectRatio=g);const m=e.getAttribute("data-class");m&&(t.className=m);const p=e.getAttribute("data-hide-delay");if(p){const e=parseInt(p,10);isNaN(e)||(t.hideDelay=e)}const v=e.getAttribute("data-playback-rate");if(v){const e=parseFloat(v);isNaN(e)||(t.playbackRate=e)}const y=e.getAttribute("data-start-time");if(y){const e=parseFloat(y);isNaN(e)||(t.startTime=e)}return t}function W(e){const t=e.split(":").map(Number),s=t[0],i=t[1];return 2===t.length&&void 0!==s&&void 0!==i&&!isNaN(s)&&!isNaN(i)&&s>0?i/s*100:56.25}function z(e,t){t.className&&e.classList.add(...t.className.split(" ")),t.width&&(e.style.width=t.width),t.height?e.style.height=t.height:t.aspectRatio&&(e.style.position="relative",e.style.paddingBottom=`${W(t.aspectRatio)}%`,e.style.height="0")}async function X(e,t){if(!t.src)return console.error("[Scarlett Player] No source URL provided"),null;try{z(e,t);const s={};t.brandColor&&(s.accentColor=t.brandColor),t.primaryColor&&(s.primaryColor=t.primaryColor),t.backgroundColor&&(s.backgroundColor=t.backgroundColor);const i={};Object.keys(s).length>0&&(i.theme=s),void 0!==t.hideDelay&&(i.hideDelay=t.hideDelay);const r=[k()];!1!==t.controls&&r.push(function(e={}){let t,s=null,i=null,r=null,n=null,a=null,o=[],l=null,h=null,d=!0;const c=e.controls||Y,u=e.hideDelay??3e3,f=e=>{switch(e){case"play":return new O(t);case"volume":return new B(t);case"progress":default:return null;case"time":return new N(t);case"live-indicator":return new U(t);case"quality":return new $(t);case"chromecast":return new G(t,"chromecast");case"airplay":return new G(t,"airplay");case"pip":return new K(t);case"fullscreen":return new H(t);case"spacer":return new V}},g=()=>{o.forEach(e=>e.update()),r?.update();const e=t?.getState("waiting"),s=t?.getState("seeking"),i=t?.getState("playbackState"),a="loading"===i,l=e||s&&!t?.getState("paused")||a;n?.classList.toggle("sp-buffering--visible",!!l)},m=()=>{d||(d=!0,s?.classList.add("sp-controls--visible"),s?.classList.remove("sp-controls--hidden"),i?.classList.add("sp-gradient--visible"),r?.show(),t?.setState("controlsVisible",!0)),v()},p=()=>{const e=t?.getState("paused");e||(d=!1,s?.classList.remove("sp-controls--visible"),s?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),r?.hide(),t?.setState("controlsVisible",!1))},v=()=>{l&&clearTimeout(l),l=setTimeout(p,u)},y=()=>{m()},E=()=>{p()},T=e=>{if(!t.container.contains(document.activeElement))return;const s=t.container.querySelector("video");if(s)switch(e.key){case" ":case"k":e.preventDefault(),s.paused?s.play():s.pause();break;case"m":e.preventDefault(),s.muted=!s.muted;break;case"f":e.preventDefault(),document.fullscreenElement?document.exitFullscreen():t.container.requestFullscreen?.();break;case"ArrowLeft":e.preventDefault(),s.currentTime=Math.max(0,s.currentTime-5),m();break;case"ArrowRight":e.preventDefault(),s.currentTime=Math.min(s.duration||0,s.currentTime+5),m();break;case"ArrowUp":e.preventDefault(),s.volume=Math.min(1,s.volume+.1),m();break;case"ArrowDown":e.preventDefault(),s.volume=Math.max(0,s.volume-.1),m()}};return{id:"ui-controls",name:"UI Controls",type:"ui",version:"1.0.0",async init(l){t=l,a=document.createElement("style"),a.textContent="\n/* ============================================\n Container & Base\n ============================================ */\n.sp-container {\n position: relative;\n width: 100%;\n height: 100%;\n background: #000;\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n}\n\n.sp-container video {\n width: 100%;\n height: 100%;\n display: block;\n object-fit: contain;\n}\n\n.sp-container:focus {\n outline: none;\n}\n\n/* ============================================\n Gradient Overlay\n ============================================ */\n.sp-gradient {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 160px;\n background: linear-gradient(\n to top,\n rgba(0, 0, 0, 0.8) 0%,\n rgba(0, 0, 0, 0.4) 50%,\n transparent 100%\n );\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.25s ease;\n z-index: 5;\n}\n\n.sp-gradient--visible {\n opacity: 1;\n}\n\n/* ============================================\n Controls Container\n ============================================ */\n.sp-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n align-items: center;\n padding: 0 12px 12px;\n gap: 4px;\n opacity: 0;\n transform: translateY(4px);\n transition: opacity 0.25s ease, transform 0.25s ease;\n z-index: 10;\n}\n\n.sp-controls--visible {\n opacity: 1;\n transform: translateY(0);\n}\n\n.sp-controls--hidden {\n opacity: 0;\n transform: translateY(4px);\n pointer-events: none;\n}\n\n/* ============================================\n Progress Bar (Above Controls)\n ============================================ */\n.sp-progress-wrapper {\n position: absolute;\n bottom: 48px;\n left: 12px;\n right: 12px;\n height: 20px;\n display: flex;\n align-items: center;\n cursor: pointer;\n z-index: 10;\n opacity: 0;\n transition: opacity 0.25s ease;\n}\n\n.sp-progress-wrapper--visible {\n opacity: 1;\n}\n\n.sp-progress {\n position: relative;\n width: 100%;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n transition: height 0.15s ease;\n}\n\n.sp-progress-wrapper:hover .sp-progress,\n.sp-progress--dragging {\n height: 5px;\n}\n\n.sp-progress__track {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n border-radius: inherit;\n overflow: hidden;\n}\n\n.sp-progress__buffered {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: rgba(255, 255, 255, 0.4);\n border-radius: inherit;\n transition: width 0.1s linear;\n}\n\n.sp-progress__filled {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: var(--sp-accent, #e50914);\n border-radius: inherit;\n}\n\n.sp-progress__handle {\n position: absolute;\n top: 50%;\n width: 14px;\n height: 14px;\n background: var(--sp-accent, #e50914);\n border-radius: 50%;\n transform: translate(-50%, -50%) scale(0);\n transition: transform 0.15s ease;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__handle,\n.sp-progress--dragging .sp-progress__handle {\n transform: translate(-50%, -50%) scale(1);\n}\n\n/* Progress Tooltip */\n.sp-progress__tooltip {\n position: absolute;\n bottom: calc(100% + 8px);\n padding: 6px 10px;\n background: rgba(20, 20, 20, 0.95);\n color: #fff;\n font-size: 12px;\n font-weight: 500;\n font-variant-numeric: tabular-nums;\n border-radius: 4px;\n white-space: nowrap;\n transform: translateX(-50%);\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.15s ease;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__tooltip {\n opacity: 1;\n}\n\n/* ============================================\n Control Buttons\n ============================================ */\n.sp-control {\n background: none;\n border: none;\n color: rgba(255, 255, 255, 0.9);\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: color 0.15s ease, transform 0.15s ease, background 0.15s ease;\n flex-shrink: 0;\n}\n\n.sp-control:hover {\n color: #fff;\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-control:active {\n transform: scale(0.92);\n}\n\n.sp-control:focus-visible {\n outline: 2px solid var(--sp-accent, #e50914);\n outline-offset: 2px;\n}\n\n.sp-control:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n transform: none;\n}\n\n.sp-control:disabled:hover {\n background: none;\n}\n\n.sp-control svg {\n width: 24px;\n height: 24px;\n fill: currentColor;\n display: block;\n}\n\n.sp-control--small svg {\n width: 20px;\n height: 20px;\n}\n\n/* ============================================\n Spacer\n ============================================ */\n.sp-spacer {\n flex: 1;\n min-width: 0;\n}\n\n/* ============================================\n Time Display\n ============================================ */\n.sp-time {\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n color: rgba(255, 255, 255, 0.9);\n white-space: nowrap;\n padding: 0 4px;\n letter-spacing: 0.02em;\n}\n\n/* ============================================\n Volume Control\n ============================================ */\n.sp-volume {\n display: flex;\n align-items: center;\n position: relative;\n}\n\n.sp-volume__slider-wrap {\n width: 0;\n overflow: hidden;\n transition: width 0.2s ease;\n}\n\n.sp-volume:hover .sp-volume__slider-wrap,\n.sp-volume:focus-within .sp-volume__slider-wrap {\n width: 64px;\n}\n\n.sp-volume__slider {\n width: 64px;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n cursor: pointer;\n position: relative;\n margin: 0 8px 0 4px;\n}\n\n.sp-volume__level {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: #fff;\n border-radius: inherit;\n transition: width 0.1s ease;\n}\n\n/* ============================================\n Live Indicator\n ============================================ */\n.sp-live {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 11px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--sp-accent, #e50914);\n cursor: pointer;\n padding: 6px 10px;\n border-radius: 4px;\n transition: background 0.15s ease, opacity 0.15s ease;\n}\n\n.sp-live:hover {\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-live__dot {\n width: 8px;\n height: 8px;\n background: currentColor;\n border-radius: 50%;\n animation: sp-pulse 2s ease-in-out infinite;\n}\n\n.sp-live--behind {\n opacity: 0.6;\n}\n\n.sp-live--behind .sp-live__dot {\n animation: none;\n}\n\n@keyframes sp-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.4; }\n}\n\n/* ============================================\n Quality / Settings Menu\n ============================================ */\n.sp-quality {\n position: relative;\n}\n\n.sp-quality__btn {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.sp-quality__label {\n font-size: 12px;\n font-weight: 500;\n opacity: 0.9;\n}\n\n.sp-quality-menu {\n position: absolute;\n bottom: calc(100% + 8px);\n right: 0;\n background: rgba(20, 20, 20, 0.95);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border-radius: 8px;\n padding: 8px 0;\n min-width: 150px;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);\n opacity: 0;\n visibility: hidden;\n transform: translateY(8px);\n transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s;\n z-index: 20;\n}\n\n.sp-quality-menu--open {\n opacity: 1;\n visibility: visible;\n transform: translateY(0);\n}\n\n.sp-quality-menu__item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 16px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.8);\n cursor: pointer;\n transition: background 0.1s ease, color 0.1s ease;\n}\n\n.sp-quality-menu__item:hover {\n background: rgba(255, 255, 255, 0.1);\n color: #fff;\n}\n\n.sp-quality-menu__item--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-quality-menu__check {\n width: 16px;\n height: 16px;\n fill: currentColor;\n margin-left: 8px;\n opacity: 0;\n}\n\n.sp-quality-menu__item--active .sp-quality-menu__check {\n opacity: 1;\n}\n\n/* ============================================\n Cast Button States\n ============================================ */\n.sp-cast--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-cast--unavailable {\n opacity: 0.4;\n}\n\n/* ============================================\n Buffering Indicator\n ============================================ */\n.sp-buffering {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 15;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.2s ease;\n}\n\n.sp-buffering--visible {\n opacity: 1;\n}\n\n.sp-buffering svg {\n width: 48px;\n height: 48px;\n fill: rgba(255, 255, 255, 0.9);\n filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));\n}\n\n@keyframes sp-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n}\n\n.sp-spin {\n animation: sp-spin 0.8s linear infinite;\n}\n\n/* ============================================\n Reduced Motion\n ============================================ */\n@media (prefers-reduced-motion: reduce) {\n .sp-gradient,\n .sp-controls,\n .sp-progress-wrapper,\n .sp-progress,\n .sp-progress__handle,\n .sp-progress__tooltip,\n .sp-control,\n .sp-volume__slider-wrap,\n .sp-quality-menu,\n .sp-buffering {\n transition: none;\n }\n\n .sp-live__dot,\n .sp-spin {\n animation: none;\n }\n}\n\n/* ============================================\n CSS Custom Properties (Theming)\n ============================================ */\n:root {\n --sp-accent: #e50914;\n --sp-color: #fff;\n --sp-bg: rgba(0, 0, 0, 0.8);\n --sp-control-height: 48px;\n --sp-icon-size: 24px;\n}\n",document.head.appendChild(a),e.theme&&this.setTheme(e.theme);const d=t.container;if(d){"static"===getComputedStyle(d).position&&(d.style.position="relative"),i=document.createElement("div"),i.className="sp-gradient sp-gradient--visible",d.appendChild(i),n=document.createElement("div"),n.className="sp-buffering",n.innerHTML=D.spinner,n.setAttribute("aria-hidden","true"),d.appendChild(n),r=new F(t),d.appendChild(r.render()),r.show(),s=document.createElement("div"),s.className="sp-controls sp-controls--visible",s.setAttribute("role","toolbar"),s.setAttribute("aria-label","Video controls");for(const e of c){const t=f(e);t&&(o.push(t),s.appendChild(t.render()))}d.appendChild(s),d.addEventListener("mousemove",y),d.addEventListener("mouseenter",y),d.addEventListener("mouseleave",E),d.addEventListener("touchstart",y,{passive:!0}),d.addEventListener("click",y),document.addEventListener("keydown",T),h=t.subscribeToState(g),document.addEventListener("fullscreenchange",g),g(),d.hasAttribute("tabindex")||d.setAttribute("tabindex","0"),t.logger.debug("UI controls plugin initialized")}else t.logger.error("UI plugin: container not found")},async destroy(){l&&(clearTimeout(l),l=null),h?.(),h=null,t?.container&&(t.container.removeEventListener("mousemove",y),t.container.removeEventListener("mouseenter",y),t.container.removeEventListener("mouseleave",E),t.container.removeEventListener("touchstart",y),t.container.removeEventListener("click",y)),document.removeEventListener("keydown",T),document.removeEventListener("fullscreenchange",g),o.forEach(e=>e.destroy()),o=[],r?.destroy(),r=null,s?.remove(),s=null,i?.remove(),i=null,n?.remove(),n=null,a?.remove(),a=null,t?.logger.debug("UI controls plugin destroyed")},show(){m()},hide(){d=!1,s?.classList.remove("sp-controls--visible"),s?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),r?.hide(),t?.setState("controlsVisible",!1)},setTheme(e){const s=t?.container||document.documentElement;e.primaryColor&&s.style.setProperty("--sp-color",e.primaryColor),e.accentColor&&s.style.setProperty("--sp-accent",e.accentColor),e.backgroundColor&&s.style.setProperty("--sp-bg",e.backgroundColor),e.controlBarHeight&&s.style.setProperty("--sp-control-height",`${e.controlBarHeight}px`),e.iconSize&&s.style.setProperty("--sp-icon-size",`${e.iconSize}px`)},getControlBar:()=>s}}(i));const n=await async function(e){const t=new g(e);return await t.init(),t}({container:e,src:t.src,autoplay:t.autoplay||!1,muted:t.muted||!1,poster:t.poster,loop:t.loop||!1,plugins:r}),a=e.querySelector("video");return a&&(t.playbackRate&&(a.playbackRate=t.playbackRate),t.startTime&&(a.currentTime=t.startTime)),n}catch(s){return console.error("[Scarlett Player] Failed to create player:",s),null}}async function Q(e){if(e.hasAttribute("data-scarlett-initialized"))return null;const t=j(e);e.setAttribute("data-scarlett-initialized","true");const s=await X(e,t);return s||e.removeAttribute("data-scarlett-initialized"),s}const J=["[data-scarlett-player]","[data-sp]","[data-video-player]",".scarlett-player"];async function Z(){const e=J.join(", "),t=document.querySelectorAll(e),s=Array.from(t).map(e=>Q(e));await Promise.all(s),t.length>0&&console.log(`[Scarlett Player] Initialized ${t.length} player(s)`)}async function ee(e){let t=null;if("string"==typeof e.container){if(t=document.querySelector(e.container),!t)return console.error(`[Scarlett Player] Container not found: ${e.container}`),null}else t=e.container;return X(t,{...e})}const te={create:ee,initAll:Z,version:"0.1.0"};"undefined"!=typeof window&&(window.ScarlettPlayer=te),"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Z()}):Z());const se=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ie=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=re},re=Number.MAX_SAFE_INTEGER||9007199254740991;let ne=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ae=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),oe=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var le="manifest",he="level",de="audioTrack",ce="subtitleTrack",ue={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class fe{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ge{constructor(e,t,s,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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fe(e),this.fast_=new fe(t),this.defaultTTFB_=i,this.ttfb_=new fe(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new fe(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new fe(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new fe(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function me(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function pe(){return pe=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},pe.apply(null,arguments)}function ve(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function ye(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(s),!0).forEach(function(t){me(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ve(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}class Ee{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Te,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Te=function(){},Se={trace:Te,debug:Te,log:Te,warn:Te,info:Te,error:Te};function Le(){return pe({},Se)}function be(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Te}(e,s)}const Ae=Le();const Re=Ae;function Ie(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ke(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(e=>-1===i.indexOf(e))}function De(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let i,r,n,a="",o=0;for(;o<s;){if(i=e[o++],0===i&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function Pe(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function we(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function _e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ce,xe={exports:{}};var Me,Oe,Fe,Ne,Be,Ue=(Ce||(Ce=1,Me=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Oe=/^(?=([^\/?#]*))\1([^]*)$/,Fe=/(?:\/|^)\.(?=\/)/g,Ne=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,xe.exports=Be={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var i=Be.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=Be.normalizePath(i.path),Be.buildURLFromParts(i)}var r=Be.parseURL(t);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=Be.normalizePath(r.path),Be.buildURLFromParts(r)):t;var n=Be.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Oe.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=Be.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?Be.normalizePath(r.path):r.path),Be.buildURLFromParts(o)},parseURL:function(e){var t=Me.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(Fe,"");e.length!==(e=e.replace(Ne,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),xe.exports);class $e{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 Ge="audio",Ke="video",He="audiovideo";class Ve{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const s=We(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[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={[Ge]:null,[Ke]:null,[He]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new $e),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ue.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ge]=null,e[Ke]=null,e[He]=null}}function Ye(e){return"initSegment"!==e.sn}class qe extends Ve{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(se(e)&&se(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=se(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){se(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Ye(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class je extends Ve{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function We(e,t){const s=Object.getPrototypeOf(e);if(s){const e=Object.getOwnPropertyDescriptor(s,t);return e||We(s,t)}}const ze=Math.pow(2,32)-1,Xe=[].push,Qe={video:1,audio:2,id3:3,text:4};function Je(e){return String.fromCharCode.apply(null,e)}function Ze(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function et(e,t){const s=st(e,t);return s<0?4294967296+s:s}function tt(e,t){let s=et(e,t);return s*=Math.pow(2,32),s+=et(e,t+4),s}function st(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function it(e,t){const s=[];if(!t.length)return s;const i=e.byteLength;for(let r=0;r<i;){const n=et(e,r),a=n>1?r+n:i;if(Je(e.subarray(r+4,r+8))===t[0])if(1===t.length)s.push(e.subarray(r+8,a));else{const i=it(e.subarray(r+8,a),t.slice(1));i.length&&Xe.apply(s,i)}r=a}return s}function rt(e){const t=[],s=e[0];let i=8;const r=et(e,i);i+=4;let n=0,a=0;0===s?(n=et(e,i),a=et(e,i+4),i+=8):(n=tt(e,i),a=tt(e,i+8),i+=16),i+=2;let o=e.length+a;const l=Ze(e,i);i+=2;for(let h=0;h<l;h++){let s=i;const n=et(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return Re.warn("SIDX has hierarchical references (not supported)"),null;const l=et(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function nt(e){const t=[],s=it(e,["moov","trak"]);for(let i=0;i<s.length;i++){const e=s[i],r=it(e,["tkhd"])[0];if(r){let s=r[0];const i=et(r,0===s?12:20),n=it(e,["mdia","mdhd"])[0];if(n){s=n[0];const r=et(n,0===s?12:20),a=it(e,["mdia","hdlr"])[0];if(a){const s=Je(a.subarray(8,12)),n={soun:Ge,vide:Ke}[s],o=at(it(e,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=ye({timescale:r,id:i},o)):t[i]={timescale:r,type:s,stsd:o}}}}}return it(e,["moov","mvex","trex"]).forEach(e=>{const s=et(e,4),i=t[s];i&&(i.default={duration:et(e,12),flags:et(e,20)})}),t}function at(e){const t=e.subarray(8),s=t.subarray(86),i=Je(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=it(t,[i])[0];it(e.subarray("enca"===i?28:78),["sinf"]).forEach(e=>{const t=it(e,["schm"])[0];if(t){const s=Je(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=it(e,["frma"])[0];t&&(n=Je(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=it(s,["avcC"])[0];e&&e.length>3&&(n+="."+ht(e[1])+ht(e[2])+ht(e[3]),r=ot("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=it(t,[i])[0],s=it(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=lt(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=lt(s,e);const i=s[e++];if(64!==i)break;if(n+="."+ht(i),e+=12,5!==s[e++])break;e=lt(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=it(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=et(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}r=ot("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ot(n,s)||n;break;case"vp09":{const e=it(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+dt(t)+"."+dt(s)+"."+dt(i)}break}case"av01":{const e=it(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,v=0;n+="."+t+"."+dt(i)+a+"."+dt(h)+"."+d+"."+c+u+f+"."+dt(g)+"."+dt(m)+"."+dt(p)+"."+v,r=ot("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function ot(e,t){const s=it(t,["dvvC"]),i=s.length?s[0]:it(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+dt(t)+"."+dt(s)}}function lt(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function ht(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function dt(e){return(e<10?"0":"")+e}function ct(e,t){it(e,["moov","trak"]).forEach(e=>{const s=it(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=it(i,["enca"]);const n=r.length>0;n||(r=it(i,["encv"])),r.forEach(e=>{it(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const s=ut(e);s&&t(s,n)})})})}function ut(e){const t=it(e,["schm"])[0];if(t){const s=Je(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=it(e,["schi","tenc"])[0];if(t)return t}}}function ft(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function gt(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return it(i,["moof"]).map(o=>{const l=o.byteOffset-8;it(o,["traf"]).map(o=>{const h=it(o,["tfdt"]).map(e=>{const t=e[0];let s=et(e,4);return 1===t&&(s*=Math.pow(2,32),s+=et(e,8)),s/r})[0];return void 0!==h&&(e=h),it(o,["tfhd"]).map(h=>{const d=et(h,4),c=16777215&et(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=et(h,p),p+=4),f&&(g=et(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=mt(t.codec)),it(o,["trun"]).map(n=>{const o=n[0],h=16777215&et(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=et(n,4);let b=8;d&&(c=et(n,b),b+=4),f&&(b+=4);let A=c+l;for(let l=0;l<L;l++){if(m?(p=et(n,b),b+=4):p=u,v?(y=et(n,b),b+=4):y=g,E&&(b+=4),T&&(S=0===o?et(n,b):st(n,b),b+=4),t.type===Ke){let t=0;for(;t<y;){const n=et(i,A);if(A+=4,pt(a,i[A])){vt(i.subarray(A,A+n),a?2:1,e+S/r,s)}A+=n,t+=n+4}}e+=p/r}}))})})}),s}function mt(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function pt(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function vt(e,t,s,i){const r=yt(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){Re.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=Ze(r,t);if(t+=2,49===e){const e=et(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let s=0;s<n;s++)l[s]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:De(l),userDataBytes:l})}}}function yt(e){const t=e.byteLength,s=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return e;const r=t-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=e[a];return n}function Et(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(e,...t){const s=t.length;let i=8,r=s;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,s)}function Tt(e){const t=e.getUint32(0),s=e.byteOffset,i=e.byteLength;if(i<t)return{offset:s,size:i};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:t};const n=e.buffer,a=Pe(new Uint8Array(n,s+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=e.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,s+32+16*e,16));h=32+16*r}if(!h)return{offset:s,size:t};const d=e.getUint32(h);return t-32<d?{offset:s,size:t}:(l=new Uint8Array(n,s+h+4,d),{version:r,systemId:a,kids:o,data:l,offset:s,size:t})}const St=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Lt={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 bt(e,t){const s=Lt[t];return!!s&&!!s[e.slice(0,4)]}function At(e,t,s=!0){return!e.split(",").some(e=>!Rt(e,t,s))}function Rt(e,t,s=!0){var i;const r=Ie(s);return null!=(i=null==r?void 0:r.isTypeSupported(It(e,t)))&&i}function It(e,t){return`${t}/mp4;codecs=${e}`}function kt(e){if(e){const t=e.substring(0,4);return Lt.video[t]}return 2}function Dt(e){const t=St();return e.split(",").reduce((e,s)=>{const i=t&&mt(s)?9:Lt.video[s];return i?(2*i+e)/(e?3:2):(Lt.audio[s]+e)/(e?2:1)},0)}const Pt={};const wt=/flac|opus|mp4a\.40\.34/i;function _t(e,t=!0){return e.replace(wt,e=>function(e,t=!0){if(Pt[e])return Pt[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(Rt(s[r],"audio",t))return Pt[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=Ie(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function Ct(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(xt(e,"audio")||xt(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function xt(e,t){return bt(e,t)&&Rt(e,t)}function Mt(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function Ot(e){const t=Ie(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ft(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Nt={supported:!1,smooth:!1,powerEfficient:!1},Bt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ut(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Nt],error:e}}function $t(e,t,s,i,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,s)=>{if(s){const i=t.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(t=>{e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(u){return!0}return void 0!==a&&(a.split(",").some(e=>mt(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(r,8e6))||!!c&&se(d)&&Object.keys(c).some(e=>parseInt(e)>d)}function Gt(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(Bt);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Ht(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map(e=>{const t={contentType:It(Mt(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Ht(e);if(r&&e.audioGroups)return e.audioGroups.reduce((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:It(t,"audio"),bitrate:s?Kt(t,n):n};i&&(r.channels=""+i),e.push(r)})}return e},e):e},[]);return[]}(e,t,o>0),h=l.length;for(let d=o||1*h||1;d--;){const e={type:"media-source"};if(o&&(e.video=a[d%o]),h){e.audio=l[d%h];const t=e.audio.bitrate;e.video&&t&&(e.video.bitrate-=t)}n.push(e)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>mt(e))&&St())return Promise.resolve(Ut(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:s,video:i}=e;if(i){t+=`${Ft(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){t+=`${i?"_":""}${Ft(s.contentType)}_c${s.channels}`}return t}(e);return i[t]||(i[t]=s.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Kt(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Ht(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const Vt=["NONE","TYPE-0","TYPE-1",null];const Yt=["SDR","PQ","HLG"];var qt={No:"",Yes:"YES",v2:"v2"};function jt(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?qt.v2:qt.Yes:qt.No}class Wt{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class zt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Xt(this._audioGroups,e)}hasSubtitleGroup(e){return Xt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Xt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Qt(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||Yt.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Jt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}})(t));function Zt(e,t){Re.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function es(e){return e.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ts(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function ss(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let i=0;i<t.length;i++){if(is(e,t[i],s))return i}return-1}function is(e,t,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const s=e.split(","),i=t.split(",");return s.length===i.length&&!s.some(e=>-1===i.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===s||s(e,t))}function rs(e,t){const{audioCodec:s,channels:i}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function ns(e,t,s){for(let i=t;i>-1;i--)if(s(e[i]))return i;for(let i=t+1;i<e.length;i++)if(s(e[i]))return i;return-1}function as(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}class os extends Ee{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!e||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(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=r.levels,A=b[u],R=Math.max(l.loaded,Math.round(h*(s.bitrate||A.averageBitrate)/8));let I=S?d-T:d;I<1&&S&&(I=Math.min(d,8*l.loaded/L));const k=S?1e3*l.loaded/I:0,D=v/1e3,P=k?(R-l.loaded)/k:8*R/L+D;if(P<=E)return;const w=k?8*k:L,_=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),C=this.hls.config.abrBandWidthUpFactor;let x,M=Number.POSITIVE_INFINITY;for(x=u-1;x>c;x--){const e=b[x].maxBitrate,t=!b[x].details||_;if(M=this.getTimeToLoadFrag(D,w,h*e,t),M<Math.min(E,h+D))break}if(M>=P)return;if(M>10*h)return;S?this.bwEstimator.sample(d-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(d);const O=b[x].maxBitrate;this.getBwEstimate()*C>O&&this.resetEstimator(O);const F=this.findBestLevel(O,c,x,0,E,1,1);F>-1&&(x=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${P.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: ${se(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${x} @ ${0|O} bps`),r.nextLoadLevel=r.nextAutoLevel=x,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===x&&x>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${x>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,x>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,x,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||P>2*M?N():this.timer=self.setInterval(N,1e3*M),r.trigger(oe.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ge(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ae.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;se(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===ue.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(oe.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ue.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===h;let T,S="SDR",L=(null==v?void 0:v.frameRate)||0;const{audioPreference:b,videoPreference:A}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=es(g));let I=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce((e,s,i)=>{if(!s.codecSet)return e;const r=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]}))}),e},{})}(f,R,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Qt(t,r);for(let b=n.length;b--;){const t=e[n[b]];d||(d=t.channels[2]>0),u=Math.min(u,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),E.filter(e=>t.videoRanges[e]>0).length>0&&(c=!0)}u=se(u)?u:0,f=se(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=se(g)?g:s,s=Math.max(g,s),c||(t=void 0);const L=n.length>1;return{codecSet:n.reduce((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?E.filter(e=>r.videoRanges[e]>0):[],L){if(r.minBitrate>s)return Zt(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return Zt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Zt(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return Zt(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return Zt(i,"no renditions with stereo sound found"),t;if(r.minHeight>T)return Zt(i,`min resolution of ${r.minHeight} > maximum of ${T}`),t;if(r.minFramerate>S)return Zt(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),t;if(!v.some(e=>r.videoRanges[e]>0))return Zt(i,`no variants with VIDEO-RANGE of ${Jt(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Zt(i,`video codec preference "${l}" not found`),t;if(r.maxScore<p)return Zt(i,`max score of ${r.maxScore} < selected max of ${p}`),t}return t&&(Dt(i)>=Dt(t)||r.fragmentError>e[t].fragmentError)?t:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(i,S,e,b,A),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;I=h,T=n,S=d?a[a.length-1]:a[0],L=o,e=Math.max(e,l),this.log(`picked start tier ${Jt(r)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let _=s;_>=t;_--){var w;const t=f[_],o=_>d;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&$t(t,R,S,L,e,b)?(t.supportedPromise=Gt(t,R,s,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,i=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${Jt(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${Jt(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${Jt(e)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=Bt}if((T&&t.codecSet!==T||S&&t.videoRange!==S||o&&L>t.frameRate||!o&&L>0&&L<t.frameRate||null!=(w=t.supportedResult)&&null!=(w=w.decodingInfoResults)&&w.some(e=>!1===e.smooth))&&(!E||_!==I)){P.push(_);continue}const c=t.details,g=(u?null==c?void 0:c.partTarget:null==c?void 0:c.averagetargetduration)||k;let v;v=o?a*e:n*e;const A=k&&i>=2*k&&0===r?t.averageBitrate:t.maxBitrate,C=this.getTimeToLoadFrag(D,v,A*g,void 0===c);if(v>=A&&(_===h||0===t.loadError&&0===t.fragmentError)&&(C<=D||!se(C)||y&&!this.bitrateTestDelay||C<l)){const e=this.forcedAutoLevel;return _===m||-1!==e&&e===m||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${d}->${_} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-A)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=_),_}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const ls=function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function hs(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===ds(s,i,n)||function(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=ls(t,ds.bind(null,s,i));return!a||a===e&&n?n:a}function ds(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function cs(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function us(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),ls(i,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0)),n||null}return null}function fs(e){switch(e.details){case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_TIMEOUT:case ae.LEVEL_LOAD_TIMEOUT:case ae.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function gs(e){return e.details.startsWith("key")}function ms(e){return gs(e)&&!!e.frag&&!e.frag.decryptdata}function ps(e,t){const s=fs(t);return e.default[(s?"timeout":"error")+"Retry"]}function vs(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function ys(e){return ye(ye({},e),{errorRetry:null,timeoutRetry:null})}function Es(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return Ts(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function Ts(e){return 0===e&&!1===navigator.onLine}var Ss={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ls={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class bs extends Ee{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.ERROR,this.onError,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.ERROR,this.onError,this),e.off(oe.ERROR,this.onErrorOut,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===ue.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i){return this.hls.allAudioTracks.filter(e=>i.indexOf(e.groupId)>=0).some(e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ae.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=As());case ae.FRAG_GAP:case ae.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Ss.SendAlternateToPenaltyBox);case ae.LEVEL_EMPTY_ERROR:case ae.LEVEL_PARSING_ERROR:{var n;const e=t.parent===ue.MAIN?t.level:i.loadLevel;t.details===ae.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case ae.AUDIO_TRACK_LOAD_ERROR:case ae.AUDIO_TRACK_LOAD_TIMEOUT:case ae.SUBTITLE_LOAD_ERROR:case ae.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===de&&e.hasAudioGroup(r.groupId)||r.type===ce&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ss.SendAlternateToPenaltyBox,void(t.errorAction.flags=Ls.MoveAllAlternatesMatchingHost)}return;case ae.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingHDCP});case ae.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ae.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ae.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingKey});case ae.BUFFER_ADD_CODEC_ERROR:case ae.REMUX_ALLOC_ERROR:case ae.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:i.loadLevel);return;case ae.INTERNAL_EXCEPTION:case ae.BUFFER_APPENDING_ERROR:case ae.BUFFER_FULL_ERROR:case ae.LEVEL_SWITCH_ERROR:case ae.BUFFER_STALLED_ERROR:case ae.BUFFER_SEEK_OVER_HOLE:case ae.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=As())}t.type===ne.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=As())}getPlaylistRetryOrSwitchAction(e,t){const s=ps(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Es(s,i,fs(e),e.response))return{action:Ss.RetryRequest,flags:Ls.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=ps(gs(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(i&&(e.details!==ae.FRAG_GAP&&i.fragmentError++,!ms(e))){if(Es(a,o,fs(e),e.response))return{action:Ss.RetryRequest,flags:Ls.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,t===ae.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===ue.AUDIO&&t===ae.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:e})=>i.audioCodec!==e),m="video"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR)&&h.some(({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(t===ae.FRAG_GAP&&f===ue.MAIN&&e.frag){const t=h[r].details;if(t){const s=hs(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===de&&s.hasAudioGroup(v)||p===ce&&s.hasSubtitleGroup(v))continue;if(f===ue.AUDIO&&null!=(a=i.audioGroups)&&a.some(e=>s.hasAudioGroup(e))||f===ue.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(e=>s.hasSubtitleGroup(e))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Ss.SendAlternateToPenaltyBox,flags:Ls.None,nextAutoLevel:l}}return{action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case Ss.DoNothing:break;case Ss.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ae.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ls.None:this.switchLevel(e,r);break;case Ls.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=Vt[Vt.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ls.MoveAllAlternatesMatchingKey:{const t=e.decryptdata;if(t){const i=this.hls.levels,r=i.length;for(let s=r;s--;){var n,a;if(this.variantHasKey(i[s],t))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${Pe(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s)}const o=e.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==ue.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ae.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=Ft(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}}function As(e){const t={action:Ss.DoNothing,flags:Ls.None};return e&&(t.resolved=!0),t}var Rs="NOT_LOADED",Is="APPENDING",ks="PARTIAL",Ds="OK";class Ps{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const t=s[i];if(!t)break;if(t.start<=e&&e<=t.end&&t.loaded)return t}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,i=_s(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(i=>{const a=s.elementaryStreams[i];if(!a)return;const o=t[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,e.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),ws(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Cs(s,t=>t.fragment.sn>=e))}fragBuffered(e,t){const s=_s(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const e=i.start(h)-this.bufferPadding,t=i.end(h)+this.bufferPadding;if(l>=e&&o<=t){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(n<t&&a>e){const e=Math.max(n,i.start(h)),t=Math.min(a,i.end(h));t>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:t}))}else if(a<=e)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&ws(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ws(t))}getState(e){const t=_s(e),s=this.fragments[t];return s?s.buffered?ws(s)?ks:Ds:Is:Rs}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=_s(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(i){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_s(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=_s(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=Cs(s,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function ws(e){var t,s,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial)}function _s(e){return`${e.type}_${e.level}_${e.sn}`}function Cs(e,t){return e.filter(e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s})}var xs=0,Ms=1;class Os{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case xs:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ms:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Fs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(4*i);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),v=new Int32Array(p.length);let y,E,T,S,L,b,A,R,I,k,D,P,w,_;const C=this.networkToHostOrderSwap;for(;t<p.length;){for(I=C(p[t]),k=C(p[t+1]),D=C(p[t+2]),P=C(p[t+3]),L=I^r[0],b=P^r[1],A=D^r[2],R=k^r[3],w=4,_=1;_<i;_++)y=o[L>>>24]^l[b>>16&255]^h[A>>8&255]^d[255&R]^r[w],E=o[b>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&L]^r[w+1],T=o[A>>>24]^l[R>>16&255]^h[L>>8&255]^d[255&b]^r[w+2],S=o[R>>>24]^l[L>>16&255]^h[b>>8&255]^d[255&A]^r[w+3],L=y,b=E,A=T,R=S,w+=4;y=n[L>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^r[w],E=n[b>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&L]^r[w+1],T=n[A>>>24]<<24^n[R>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^r[w+2],S=n[R>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[w+3],v[t]=C(y^u),v[t+1]=C(S^f),v[t+2]=C(T^g),v[t+3]=C(E^m),u=I,f=k,g=D,m=P,t+=4}return v.buffer}}class Ns{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case xs:return"AES-CBC";case Ms:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class Bs{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(s){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==xs||16!==t.byteLength)return Re.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=ft(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Fs),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Ns(this.subtle,t,i)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Os(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)}).catch(r=>(Re.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Re.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Us=Math.pow(2,17);class $s{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(Ks(e));e.gap=!1}const l=this.loader=r?new r(i):new n(i),h=Gs(e);e.loader=l;const d=ys(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Us};e.stats=l.stats;const u={onSuccess:(t,s,i,r)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,i,r,n)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ye({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:t}))}};t&&(u.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(h,c,u)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Ks(e,t));const l=this.loader=r?new r(i):new n(i),h=Gs(e,t);e.loader=l;const d=ys(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Us};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ye({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Gs(e,t=null){const s=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(se(r)&&se(n)){var a;let t=r,s=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(s=n+(16-e%16)),0!==r&&(i.resetIV=!0,t=r-16)}i.rangeStart=t,i.rangeEnd=s}var o;return i}function Ks(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:ne.MEDIA_ERROR,details:ae.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Hs(i)}class Hs extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Vs extends Ee{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ys{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}const qs={length:0,start:()=>0,end:()=>0};class js{static isBuffered(e,t){if(e){const s=js.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=js.getBuffered(e);return js.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=js.bufferedRanges(e);if(i.length)return js.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const n=r.length;if(n){const t=r[n-1].end;e[h].start-t<s?e[h].end>t&&(r[n-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n,a=0,o=t,l=t;for(let h=0;h<r.length;h++){const e=r[h].start,d=r[h].end;if(-1===i&&t>=e&&t<=d&&(i=h),t+s>=e&&t<d)o=e,l=d,a=l-t;else if(t+s<e){n=e;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||qs}catch(t){return Re.log("failed to get media.buffered",t),qs}}}const Ws=/\{\$([a-zA-Z0-9-_]+)\}/g;function zs(e){return Ws.test(e)}function Xs(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(Ws,t=>{const i=t.substring(2,t.length-1),r=null==s?void 0:s[i];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),t):r})}return t}function Qs(e,t,s){let i,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=e.get(i)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=t.NAME,r=t.VALUE;i in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Js(e,t,s){const i=t.IMPORT;if(s&&i in s){let t=e.variableList;t||(e.variableList=t={}),t[i]=s[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const Zs=/^(\d+)x(\d+)$/,ei=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ti{constructor(e,t){"string"==typeof e&&(e=ti.parseAttrList(e,t)),pe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Zs.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(ei.lastIndex=0;null!==(s=ei.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=Xs(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Re.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function si(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ii(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class ri{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){Re.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=pe(new ti({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);se(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Re.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(se(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&se(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 ni{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&se(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ai(e,t){return e.length===t.length&&!e.some((e,s)=>e!==t[s])}function oi(e,t){return!e&&!t||!(!e||!t)&&ai(e,t)}function li(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function hi(e){switch(e){case"AES-128":case"AES-256":return xs;case"AES-256-CTR":return Ms;default:throw new Error(`invalid full segment method ${e}`)}}function di(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ci(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function ui(e){const t=function(e,t,s){const i=e[t];e[t]=e[s],e[s]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function fi(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),i=e[e.length-1].split(",");if(2===i.length){const t="base64"===i[0],r=i[1];t?(e.splice(-1,1),s=di(r)):s=function(e){const t=ci(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}(r)}}return s}const gi="undefined"!=typeof self?self:void 0;var mi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},pi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function vi(e){switch(e){case pi.FAIRPLAY:return mi.FAIRPLAY;case pi.PLAYREADY:return mi.PLAYREADY;case pi.WIDEVINE:return mi.WIDEVINE;case pi.CLEARKEY:return mi.CLEARKEY}}function yi(e){switch(e){case mi.FAIRPLAY:return pi.FAIRPLAY;case mi.PLAYREADY:return pi.PLAYREADY;case mi.WIDEVINE:return pi.WIDEVINE;case mi.CLEARKEY:return pi.CLEARKEY}}function Ei(e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?[mi.FAIRPLAY,mi.WIDEVINE,mi.PLAYREADY,mi.CLEARKEY].filter(e=>!!t[e]):[];return!i[mi.WIDEVINE]&&s&&i.push(mi.WIDEVINE),i}const Ti=null!=gi&&null!=(Si=gi.navigator)&&Si.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Si;function Li(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(t)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=di(e).subarray(0,16);return ui(t),t}}return null}let bi={};class Ai{static clearKeyUriToKeyIdMap(){bi={}}static setKeyIdForUri(e,t){bi[e]=t}static addKeyIdForUri(e){const t=Object.keys(bi).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),bi[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!li(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(we(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ai(e.keyFormatVersions,this.keyFormatVersions)&&oi(e.iv,this.iv)&&oi(e.keyId,this.keyId)}isSupported(){if(this.method){if(li(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case pi.FAIRPLAY:case pi.WIDEVINE:case pi.PLAYREADY:case pi.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(li(this.method)){let t=this.iv;t||("number"!=typeof e&&(Re.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(e));return new Ai(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=bi[this.uri];if(e&&!ai(this.keyId,e)&&Ai.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=fi(this.uri);if(s)switch(this.keyFormat){case pi.WIDEVINE:if(this.pssh=s,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let i=0;for(;i+32<s;){const s=Tt(new DataView(e,i));t.push(s),i+=s.size}}return t}(s.buffer);if(e.length){var i;const t=e[0];this.keyId=null!=(i=t.kids)&&i.length?t.kids[0]:null}}this.keyId||(this.keyId=Ri(t));break;case pi.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Et(e,0,s),this.keyId=Li(s);break}default:{let e=s.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[pi.WIDEVINE];if(t)return t.keyId;return null}(t),e||(e=Ri(t),e||(e=bi[this.uri])),e&&(this.keyId=e,Ai.setKeyIdForUri(this.uri,e))}return this}}function Ri(e){const t=null==e?void 0:e[pi.PLAYREADY];if(t){const e=fi(t.uri);if(e)return Li(e)}return null}const Ii=/#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,ki=/#EXT-X-MEDIA:(.*)/g,Di=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),wi=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 _i{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Ue.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Di.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:zs(e)},i=[];if(Ii.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=Ii.exec(e));)if(r[1]){var n;const e=new ti(r[1],s),a=Xs(s,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:_i.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Fi(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Fi(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const e=r[3],i=r[4];switch(e){case"SESSION-DATA":{const e=new ti(i,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=Mi(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):Re.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":Qs(s,new ti(i,s),t);break;case"CONTENT-STEERING":{const e=new ti(i,s);s.contentSteering={uri:_i.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Oi(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(ki.lastIndex=0;null!==(i=ki.exec(e));){const e=new ti(i[1],s),n=e.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?_i.resolve(e.URI,t):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=_i.findGroup(s,f.groupId)||s[0];Ni(f,e,"audioCodec"),Ni(f,e,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new ni(t),h=l.fragments,d=[];let c,u,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,L=new qe(i,o),b=-1,A=!1,R=null;if(Pi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=zs(e),"#EXTM3U"!==(null==(a=Pi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Pi.exec(e));){A&&(A=!1,L=new qe(i,o),L.playlistOffset=y,L.setStart(y),L.sn=p,L.cc=E,T&&(L.bitrate=T),L.level=s,m&&(L.initSegment=m,m.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(L.setByteRange(R),R=null)));const e=c[1];if(e){L.duration=parseFloat(e);const t=(" "+c[2]).slice(1);L.title=t||null,L.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(se(L.duration)){L.playlistOffset=y,L.setStart(y),f&&$i(L,f,l),L.sn=p,L.level=s,L.cc=E,h.push(L);const e=(" "+c[3]).slice(1);L.relurl=Xs(l,e),Bi(L,S,d),S=L,y+=L.duration,p++,v=0,A=!0}}else{if(c=c[0].match(wi),!c){Re.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":S?L.setByteRange(r,S):L.setByteRange(r);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=r,L.tagList.push(["PROGRAM-DATE-TIME",r]),-1===b&&(b=h.length);break;case"PLAYLIST-TYPE":l.type&&Gi(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Gi(l,e,c):h.length>0&&Ki(l,e,c),p=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&Gi(l,e,c);const t=new ti(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(se(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);p+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Gi(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Gi(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Gi(l,e,c),l.live=!1;break;case"#":(r||a)&&L.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([e]);break;case"BITRATE":L.tagList.push([e,r]),T=1e3*parseInt(r),se(T)?L.bitrate=T:T=0;break;case"DATERANGE":{const e=new ti(r,l),t=new ri(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Re.warn(`Ignoring invalid DATERANGE tag: "${r}"`),L.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new ti(r,l);"IMPORT"in e?Js(l,e,n):Qs(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Gi(l,e,c):h.length>0&&Ki(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=Mi(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=pe({},f)),f[e.keyFormat]=e)}else Re.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Oi(r);break;case"MAP":{const e=new ti(r,l);if(L.duration){const t=new qe(i,o);Ui(t,e,s,f),m=t,L.initSegment=m,m.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime)}else{const t=L.byteRangeEndOffset;if(t){const e=L.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;Ui(L,e,s,f),m=L,A=!0}m.cc=E;break}case"SERVER-CONTROL":g&&Gi(l,e,c),g=new ti(r),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&&Gi(l,e,c);const t=new ti(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new ti(r,l),n=new je(i,L,o,s,t);e.push(n),L.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new ti(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new ti(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Re.warn(`line parsed but not handled: ${c}`)}}}S&&!S.relurl?(h.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(Bi(L,S,d),L.cc=E,l.fragmentHint=L,f&&$i(L,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const I=h.length,k=h[0],D=h[I-1];if(y+=l.skippedSegments*l.targetduration,y>0&&I&&D){l.averagetargetduration=y/I;const e=D.sn;l.endSN="initSegment"!==e?e:0,l.live||(D.endList=!0),b>0&&(!function(e,t){let s=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,b),k&&d.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&k&&Ci(d,l),l.endCC=E,l}}function Ci(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=xi(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function xi(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(t>=o||0===i){var a;if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length){for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function Mi(e,t,s){var i,r;const n=new ti(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Re.error(`Invalid IV: ${n.IV}`);const c=o?_i.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ai(a,c,d,u,l,n.KEYID)}function Oi(e){const t=new ti(e).decimalFloatingPoint("TIME-OFFSET");return se(t)?t:null}function Fi(e,t){let s=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const i=s.filter(t=>bt(t,e));i.length&&(t[`${e}Codec`]=i.map(e=>e.split("/")[0]).join(","),s=s.filter(e=>-1===i.indexOf(e)))}),t.unknownCodecs=s}function Ni(e,t,s){const i=t[s];i&&(e[s]=i)}function Bi(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ui(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function $i(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||i.push(e)}function Gi(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Ki(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function Hi(e,t){const s=t.startPTS;if(se(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Vi(e,t,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let o=s,l=i;const h=t.startPTS,d=t.endPTS;if(se(h)){const c=Math.abs(h-s);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):se(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(s,h),s=Math.min(s,h),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(i,d),i=Math.max(i,d),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=r,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,m=e.fragments;for(m[g]=t,f=g;f>0;f--)Hi(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Hi(m[f],m[f+1]);return e.fragmentHint&&Hi(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function Yi(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let d=r.length-1;d>=0;d--){const e=r[d].initSegment;if(e){i=e;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){const i=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=t.fragments[h]=r),r&&n){s(r,n,h,o);const i=r.relurl,a=n.relurl;if(i&&er(i,a))return void(t.playlistParsingError=qi(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=qi(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,(e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}se(e.startPTS)&&se(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=pe({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(e=>{const t=n[e],r=new ri(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Jt(i[e].attr)}"`)}),n}(e.dateRanges,t,s));const i=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&Bi(o[e],o[e-1],i);Ci(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=Xi(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?Vi(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):ji(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function qi(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function ji(e,t,s=!0){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Wi(t,a)}function Wi(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function zi(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function Xi(e,t,s){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t?i:t<e.startSN&&s&&s.sn===t?s:null)}function Qi(e,t,s){return e?Ji(e.partList,t,s):null}function Ji(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Zi(e){e.forEach((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function er(e,t){return!(e===t||!t)&&tr(e)!==tr(t)}function tr(e){return e.replace(/\?[^?]*$/,"")}function sr(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function ir(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function rr(e,t){const s=t.fragments;for(let i=0,r=s.length;i<r;i++)ir(s[i],e);t.fragmentHint&&ir(t.fragmentHint,e),t.alignedSliding=!0}function nr(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const s=Math.min(t.endCC,e.endCC),i=sr(t.fragments,s),r=sr(e.fragments,s);if(!i||!r)return;Re.log(`Aligning playlist at start of dicontinuity sequence ${s}`);rr(i.start-r.start,e)}function ar(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=sr(i,a),n=sr(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=sr(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;rr((l-o)/1e3-(n.start-r.start),e)}function or(e,t,s){lr(e,t,s),e.addEventListener(t,s)}function lr(e,t,s){e.removeEventListener(t,s)}const hr=function(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t},dr="STOPPED",cr="IDLE",ur="KEY_LOADING",fr="FRAG_LOADING",gr="FRAG_LOADING_WAITING_RETRY",mr="WAITING_TRACK",pr="PARSING",vr="PARSED",yr="ENDED",Er="ERROR",Tr="WAITING_INIT_PTS",Sr="WAITING_LEVEL";class Lr extends Vs{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=dr,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=js.bufferInfo(i||s,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${se(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===yr)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(o||r<a.start||i>a.end){const e=n>r;(n<i||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===cr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new $s(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Bs(e.config)}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===dr)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=dr}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=js.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return js.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;or(s,"seeking",this.onMediaSeeking),or(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===dr&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),lr(i,"seeking",this.onMediaSeeking),lr(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=dr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===fr||!this.fragCurrent&&t===pr)&&(this.fragmentTracker.removeFragment(s),this.state=cr):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(oe.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Is){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ks&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(oe.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&li(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,hi(r.method)).catch(e=>{throw t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e}).then(i=>{const r=self.performance.now();return t.trigger(oe.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==dr&&(this.state=cr),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(s.message),!e||e.mediaKeys?!1:(this.hls.trigger(oe.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?hr(js.getBuffered(s)):"(detached)"})`),Ye(e)){var i;if(e.type!==ue.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=cr)}const t=null==(i=this.levels)?void 0:i[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=cr}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),a=new Ys(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ur,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(oe.KEY_LOADED,e),this.state===ur&&(this.state=cr),e}),this.hls.trigger(oe.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Ye(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&Ye(e)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,s);if(o>-1){const l=r[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=fr,h=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,i)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,i).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(Ye(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),se(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=fr;const h=this.config.progressive&&e.type!==ue.SUBTITLE;let d;return d=h&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,i)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,h?i:void 0),a]).then(([e])=>(!h&&i&&i(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then(i=>{o[t.index]=i;const n=i.part;this.hls.trigger(oe.FRAG_LOADED,i);const a=Qi(s.details,e.sn,t.index+1)||Ji(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ae.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ne.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(oe.ERROR,t)}else this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==pr)return void(this.fragCurrent||this.state===dr||this.state===Er||(this.state=cr));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===ue.SUBTITLE)return!1;if(t>=r.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Qi(o,r,n):null,h=l?l.fragment:Xi(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==pr)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=ft(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(oe.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!js.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=js.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!se(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=js.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return js.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=ue.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(s[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ds||s===ks&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(br(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(br(this.config)&&e.type!==ue.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let t=r.length;t--;){const s=r[t].interstitial;if(s.appendInPlace&&e.start>=s.startTime&&e.end<=s.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!se(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(cs(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=us(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=hs(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Ds||t===ks&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Ds?t:null}}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&se(r);if(n||!a&&!r){!function(e,t){e&&(nr(t,e),t.alignedSliding||ar(t,e),t.alignedSliding||t.skippedSegments||ji(e,t,!1))}(s,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&se(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ye(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===gr)||(this.state=cr)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===ae.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a)return void(this.state=Er);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===Ss.RetryRequest,f=c&&!a.resolved&&l===Ls.MoveAllAlternatesMatchingHost,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&Ye(i)&&!i.endList&&g&&!ms(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var m;const s=Ts(null==(m=t.response)?void 0:m.code),r=vs(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=gr,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===Ss.RemoveAlternatePermanently||(a.resolved=!0)}else this.state=o===Ss.SendAlternateToPenaltyBox?Sr:Er;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ts(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=cr)}reduceLengthAndFlushBuffer(e){if(this.state===pr||this.state===vr){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===ue.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dr&&(this.state=cr)}afterBufferFlushed(e,t,s){if(!e)return;const i=js.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===yr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dr&&(this.state=cr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i?0:Vi(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(oe.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var n;const t=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||t&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=vr,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(oe.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ue.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN).toFixed(3)}-${(null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function br(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Ar{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let r=0;r<e.length;r++){const t=e[r];s.set(t,i),i+=t.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Rr,Ir={exports:{}};var kr=(Rr||(Rr=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(Ir)),Ir.exports),Dr=_e(kr);const Pr="1.6.15",wr={};function _r(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Cr(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function xr(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function Mr(e,t){const s=t;let i=0;for(;Cr(e,t);){i+=10;i+=xr(e,t+6),_r(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(s,s+i)}function Or(e,t){return 255===e[t]&&240==(246&e[t+1])}function Fr(e,t){return 1&e[t+1]?7:9}function Nr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Br(e,t){return t+1<e.length&&Or(e,t)}function Ur(e,t){if(Br(e,t)){const s=Fr(e,t);if(t+s>=e.length)return!1;const i=Nr(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||Br(e,r)}return!1}function $r(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const c=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return Re.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(t,s,i,r);if(!n)return;pe(e,n)}}function Gr(e){return 9216e4/e}function Kr(e,t,s,i,r){const n=i+r*Gr(e.samplerate),a=function(e,t){const s=Fr(e,t);if(t+s<=e.length){const i=Nr(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Hr(e,t){return Cr(e,t)&&xr(e,t+6)+10<=e.length-t}function Vr(e,t=0,s=1/0){return function(e,t,s,i){const r=(n=e,n instanceof ArrayBuffer?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(u=e,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,h=(o+t)/a,d=Math.floor(Math.max(0,Math.min(h,l))),c=Math.floor(Math.min(d+Math.max(s,0),l));var u;return new i(r,d,c-d)}(e,t,s,Uint8Array)}function Yr(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=De(Vr(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=De(Vr(e.data,3+s,n));let o;var l;return o="--\x3e"===i?De(Vr(e.data,4+s+n)):(l=e.data.subarray(4+s+n))instanceof ArrayBuffer?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}function qr(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=De(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=De(e.data.subarray(t),!0);t+=s.length+1;const i=De(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=De(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Yr(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=De(e.data.subarray(t),!0);t+=s.length+1;const i=De(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=De(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function jr(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=xr(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}function Wr(e){let t=0;const s=[];for(;Cr(e,t);){const i=xr(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+i;for(;t+10<r;){const i=jr(e.subarray(t)),r=qr(i);r&&s.push(r),t+=i.size+10}_r(e,t)&&(t+=10)}return s}function zr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Xr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function Qr(e){const t=Wr(e);for(let s=0;s<t.length;s++){const e=t[s];if(zr(e))return Xr(e)}}let Jr=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Zr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class en{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=ft(this.cachedData,e),this.cachedData=null);let s,i=Mr(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?Qr(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&se(o))&&(this.basePTS=tn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Jr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else Hr(e,r)?(i=Mr(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Jr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=ft(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:Zr(),id3Track:a,textTrack:Zr()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Zr(),id3Track:this._id3Track,textTrack:Zr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const tn=(e,t,s)=>{if(se(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let sn=null;const rn=[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],nn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],an=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],on=[0,1,1,4];function ln(e,t,s,i,r){if(s+24>t.length)return;const n=hn(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function hn(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*rn[14*(3===s?3-i:3===i?3:4)+r-1],h=nn[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=an[s][i],u=on[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===sn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sn=e?parseInt(e[1]):0}return!!sn&&sn<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function dn(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function cn(e,t){return t+1<e.length&&dn(e,t)}function un(e,t){if(t+1<e.length&&dn(e,t)){const s=4,i=hn(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||cn(e,n)}return!1}const fn=(e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s};class gn extends en{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=mn(e,t,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}static probe(e){if(!e)return!1;const t=Mr(e,0);if(!t)return!1;const s=t.length;return 11===e[s]&&119===e[s+1]&&void 0!==Qr(t)&&fn(e,s)<16}}function mn(e,t,s,i,r){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const h=t[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(t[s+6]<<8|t[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}const pn=/\/emsg[-/]ID3/i;function vn(e,t){return se(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class yn{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Bs(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xs)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=yt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}}class En{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,d=1);d<i;)if(o=t[d++],r)if(1!==r)if(o)if(1===o){if(l=d-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=ft(s.data,t.subarray(0,l)),s.state=0))}d<i?(h=this.getNALuType(t,d),c=d,u=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,i),type:u,state:r};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=ft(s.data,t))}return e.naluState=r,a}}class Tn{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&Re.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Sn extends En{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 1:{let t=!1;n=!0;const r=i.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,vt(i.data,1,s.pts,t.samples);break;case 7:{var d,c;n=!0,o=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(d=e.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Tn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new Tn(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const E=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let L=[1,1];if(u()&&u()){switch(h()){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=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:L}}}class Ln extends En{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,vt(i.data,2,s.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=pe(e.params,this.readVPS(i.data)),this.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],i.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(i.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const s in t.params)e.params[s]=t.params[s]}this.pushParameterSet(e.sps,i.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(i.data);for(const s in t)e.params[s]=t[s]}this.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Tn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Tn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[];for(let Y=0;Y<s;Y++)v.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let Y=s;Y<8;Y++)t.readBits(2);for(let Y=0;Y<s;Y++)v[Y]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[Y]&&t.readUByte();t.readUEG();const E=t.readUEG();3==E&&t.skipBits(1);const T=t.readUEG(),S=t.readUEG(),L=t.readBoolean();let b=0,A=0,R=0,I=0;L&&(b+=t.readUEG(),A+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());const k=t.readUEG(),D=t.readUEG(),P=t.readUEG();for(let Y=t.readBoolean()?0:s;Y<=s;Y++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++){if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const w=t.readUEG();let _=0;for(let Y=0;Y<w;Y++){let e=!1;if(0!==Y&&(e=t.readBoolean()),e){Y===w&&t.readUEG(),t.readBoolean(),t.readUEG();let e=0;for(let s=0;s<=_;s++){const s=t.readBoolean();let i=!1;s||(i=t.readBoolean()),(s||i)&&e++}_=e}else{const e=t.readUEG(),s=t.readUEG();_=e+s;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let i=0;i<s;i++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let B=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(x=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),B=t.readBoolean(),B&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),i=t.readBoolean();let r=!1;(e||i)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){O=t.readBoolean();let s=!1;O||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(i)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let U=T,$=S;if(L){let e=1,t=1;1===E?e=t=2:2==E&&(e=2),U=T-e*A-e*b,$=S-t*I-t*R}const G=i?["A","B","C"][i]:"",K=a<<24|o<<16|l<<8|h;let H=0;for(let Y=0;Y<32;Y++)H=(H|(K>>Y&1)<<31-Y)>>>0;let V=H.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:U,height:$,pixelRatio:[x,M]}}readPPS(e){const t=new Tn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),i=t.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const bn=188;class An{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=An.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-bn)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=bn){if(71!==e[o]||t-o!==bn&&71!==e[o+bn]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-bn)+1)),r||(r=0===Rn(e,o)),r&&a>1&&(0===n&&a>2||o+bn>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=An.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=An.createTrack("audio",i),this._id3Track=An.createTrack("id3"),this._txtTrack=An.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=ft(this.remainderData,e)).length,this.remainderData=null),y<bn&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,An.syncOffset(e));y-=(y-E)%bn,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let L=E;L<y;L+=bn)if(71===e[L]){const t=!!(64&e[L+1]),i=Rn(e,L);let y;if((48&e[L+3])>>4>1){if(y=L+5+e[L+4],y===L+bn)continue}else y=L+4;switch(i){case h:t&&(d&&(r=wn(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(y,L+bn)),d.size+=L+bn-y);break;case c:if(t){if(f&&(r=wn(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(y,L+bn)),f.size+=L+bn-y);break;case u:t&&(g&&(r=wn(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(y,L+bn)),g.size+=L+bn-y);break;case 0:t&&(y+=e[y]+1),v=this._pmtId=In(e,y);break;case v:{t&&(y+=e[y]+1);const i=kn(e,y,this.typeSupported,s,this.observer,this.logger);h=i.videoPid,h>0&&(n.pid=h,n.segmentCodec=i.segmentVideoCodec),c=i.audioPid,c>0&&(a.pid=c,a.segmentCodec=i.segmentAudioCodec),u=i.id3Pid,u>0&&(o.pid=u),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&&Dn(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=wn(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=wn(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=wn(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new yn(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new Sn:"hevc"===e&&(this.videoParser=new Ln))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,r=i.sample.unit.byteLength;if(-1===t)o=ft(i.sample.unit,o);else{const n=r-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Br(o,r);r++);if(r!==s){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Dn(this.observer,new Error(e),t,this.logger),!t)return}if($r(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Gr(e.samplerate);a=i.sample.pts+t}}let l,h=0;for(;r<n;){if(l=Kr(e,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!Br(o,r);r++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(cn(s,n)){const t=ln(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=mn(e,s,o,i,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=pe({},t,{type:this._videoTrack?Jr.emsg:Jr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Rn(e,t){return((31&e[t+1])<<8)+e[t+2]}function In(e,t){return(31&e[t+10])<<8|e[t+11]}function kn(e,t,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Rn(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Pn("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){Pn("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.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){Pn("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let i=t+5,r=l;for(;r>2;){if(106===e[i])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[i+1]+2;i+=t,r-=t}}break;case 194:case 135:return Dn(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Dn(e,t,s,i){i.warn(`parsing error: ${t.message}`),e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function Pn(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function wn(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ft(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class _n{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Cn=Math.pow(2,32)-1;class xn{static init(){let e;for(e in xn.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:[]},xn.types)xn.types.hasOwnProperty(e)&&(xn.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);xn.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);xn.STTS=xn.STSC=xn.STCO=r,xn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),xn.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]);xn.FTYP=xn.box(xn.types.ftyp,n,o,n,a),xn.DINF=xn.box(xn.types.dinf,xn.box(xn.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return xn.box(xn.types.hdlr,xn.HDLR_TYPES[e])}static mdat(e){return xn.box(xn.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Cn+1)),i=Math.floor(t%(Cn+1));return xn.box(xn.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return xn.box(xn.types.mdia,xn.mdhd(e.timescale||0,e.duration||0),xn.hdlr(e.type),xn.minf(e))}static mfhd(e){return xn.box(xn.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?xn.box(xn.types.minf,xn.box(xn.types.smhd,xn.SMHD),xn.DINF,xn.stbl(e)):xn.box(xn.types.minf,xn.box(xn.types.vmhd,xn.VMHD),xn.DINF,xn.stbl(e))}static moof(e,t,s){return xn.box(xn.types.moof,xn.mfhd(e),xn.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=xn.trak(e[t]);return xn.box.apply(null,[xn.types.moov,xn.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(xn.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=xn.trex(e[t]);return xn.box.apply(null,[xn.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Cn+1)),i=Math.floor(t%(Cn+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,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 xn.box(xn.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return xn.box(xn.types.sdtp,s)}static stbl(e){return xn.box(xn.types.stbl,xn.stsd(e),xn.box(xn.types.stts,xn.STTS),xn.box(xn.types.stsc,xn.STSC),xn.box(xn.types.stsz,xn.STSZ),xn.box(xn.types.stco,xn.STCO))}static avc1(e){let t,s,i,r=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=xn.box(xn.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return xn.box(xn.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,xn.box(xn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xn.box(xn.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return xn.box(xn.types.mp4a,xn.audioStsd(e),xn.box(xn.types.esds,xn.esds(e)))}static mp3(e){return xn.box(xn.types[".mp3"],xn.audioStsd(e))}static ac3(e){return xn.box(xn.types["ac-3"],xn.audioStsd(e),xn.box(xn.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return xn.box(xn.types.stsd,xn.STSD,xn.mp4a(e));if("ac3"===t&&e.config)return xn.box(xn.types.stsd,xn.STSD,xn.ac3(e));if("mp3"===t&&"mp3"===e.codec)return xn.box(xn.types.stsd,xn.STSD,xn.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return xn.box(xn.types.stsd,xn.STSD,xn.avc1(e));if("hevc"===t&&e.vps)return xn.box(xn.types.stsd,xn.STSD,xn.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Cn+1)),a=Math.floor(s%(Cn+1));return xn.box(xn.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const s=xn.sdtp(e),i=e.id,r=Math.floor(t/(Cn+1)),n=Math.floor(t%(Cn+1));return xn.box(xn.types.traf,xn.box(xn.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),xn.box(xn.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),xn.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,xn.box(xn.types.trak,xn.tkhd(e),xn.mdia(e))}static trex(e){const t=e.id;return xn.box(xn.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return xn.box(xn.types.trun,n)}static initSegment(e){xn.types||xn.init();const t=xn.moov(e);return ft(xn.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let r=i.length;for(let u=0;u<s.length;u+=1){r+=3;for(let e=0;e<s[u].length;e+=1)r+=2+s[u][e].length}const n=new Uint8Array(r);n.set(i,0),r=i.length;const a=s.length-1;for(let u=0;u<s.length;u+=1){n.set(new Uint8Array([32+u|(u===a?128:0),0,s[u].length]),r),r+=3;for(let e=0;e<s[u].length;e+=1)n.set(new Uint8Array([s[u][e].length>>8,255&s[u][e].length]),r),r+=2,n.set(s[u][e],r),r+=s[u][e].length}const o=xn.box(xn.types.hvcC,n),l=e.width,h=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return xn.box(xn.types.hvc1,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,l>>8&255,255&l,h>>8&255,255&h,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]),o,xn.box(xn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xn.box(xn.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}xn.types=void 0,xn.HDLR_TYPES=void 0,xn.STTS=void 0,xn.STSC=void 0,xn.STCO=void 0,xn.STSZ=void 0,xn.VMHD=void 0,xn.SMHD=void 0,xn.STSD=void 0,xn.FTYP=void 0,xn.DINF=void 0;function Mn(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}function On(e,t=!1){return Mn(e,1e3,1/9e4,t)}function Fn(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}let Nn,Bn=null,Un=null;function $n(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Gn extends Ee{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===Bn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bn=e?parseInt(e[1]):0}if(null===Un){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Un=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Fn(t):t} > ${e?Fn(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=Kn(r,s),n=r-e),n>0?e:r},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.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 e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(L=e.pixelRatio)?void 0:L[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(A=e.pixelRatio)?void 0:A[1]))||!e&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.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 s=this.getVideoStartPts(t.samples),i=(Kn(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||T||o===ue.AUDIO?m:void 0),T){const i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,m,s,i)}}else T&&(l=this.remuxVideo(t,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Hn(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Vn(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Kn(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(h=d=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):xn.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:h=d=this.computeInitPts(r[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:xn.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Kn(n[0].dts,e),i=this.computeInitPts(t,c,s,"video"),r=this.computeInitPts(e,c,s,"video");d=Math.min(d,i),h=Math.min(h,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${h/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/c} (${h}/${c}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:c,trackId:g},this._initDTS={baseTime:d,timescale:c,trackId:g}):h=c=void 0,{tracks:o,initPTS:h,timescale:c,trackId:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let d,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const e=h+t*r,i=n[0].pts-Kn(n[0].dts,n[0].pts);Bn&&null!==u&&Math.abs(e-i-(u+h))<15e3?s=!0:u=e-i-h}const y=u+h;for(let O=0;O<o;O++){const e=n[O];e.pts=Kn(e.pts,y),e.dts=Kn(e.dts,y),e.dts<n[O>0?O-1:O].dts&&(v=!0)}v&&n.sort(function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i}),d=n[0].dts,c=n[n.length-1].dts;const E=c-d,T=E?Math.round(E/(o-1)):g||e.inputTimeScale/30;if(s){const s=d-y,i=s>T,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${On(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${On(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||y>=n[0].pts||Bn)){d=y;const e=n[0].pts-s;if(i)n[0].dts=d,n[0].pts=e;else{let t=!0;for(let i=0;i<n.length&&!(n[i].dts>e&&t);i++){const e=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;t=s<=n[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${On(e,!0)}/${On(d,!0)}, delta: ${On(s,!0)} ms`)}}d=Math.max(0,d);let S=0,L=0,b=d;for(let O=0;O<o;O++){const e=n[O],t=e.units,s=t.length;let i=0;for(let r=0;r<s;r++)i+=t[r].data.length;L+=i,S+=s,e.length=i,e.dts<b?(e.dts=b,b+=T/4|0||1):b=e.dts,m=Math.min(e.pts,m),p=Math.max(e.pts,p)}c=n[o-1].dts;const A=L+4*S+8;let R;try{R=new Uint8Array(A)}catch(M){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:A,reason:`fail allocating video mdat ${A}`})}const I=new DataView(R.buffer);I.setUint32(0,A),R.set(xn.types.mdat,4);let k=!1,D=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,w=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let O=0;O<o;O++){const e=n[O],t=e.units;let s,l=0;for(let i=0,r=t.length;i<r;i++){const e=t[i],s=e.data,r=e.data.byteLength;I.setUint32(f,r),f+=4,R.set(s,f),f+=r,l+=4+r}if(O<o-1)g=n[O+1].dts-e.dts,s=n[O+1].pts-e.pts;else{const t=this.config,a=O>0?e.dts-n[O-1].dts:T;if(s=O>0?e.pts-n[O-1].pts:T,t.stretchShortVideoTrack&&null!==this.nextAudioTs){const s=Math.floor(t.maxBufferHole*r),n=(i?m+i*r:this.nextAudioTs+h)-e.pts;n>s?(g=n-a,g<0?g=a:k=!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 d=Math.round(e.pts-e.dts);D=Math.min(D,g),w=Math.max(w,g),P=Math.min(P,s),_=Math.max(_,s),a.push($n(e.key,g,l,d))}if(a.length)if(Bn){if(Bn<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Un&&_-P<w-D&&T/w<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,s=a.length;t<s;t++){const i=e+a[t].duration,r=e+a[t].cts;if(t<s-1){const e=i+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:T;a[t].cts=0,e=i}}g=k||!g?T:g;const C=c+g;this.nextVideoTs=u=C-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const x={data1:xn.moof(e.sequenceNumber++,d,pe(e,{samples:a})),data2:R,startPTS:(m-h)/r,endPTS:(p+g-h)/r,startDTS:(d-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,x}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=d?0:8,m=this.nextAudioTs||-1;const p=h.baseTime*n/h.timescale,v=p+t*n;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(v-(m+p))<9e3||Math.abs(Kn(f[0].pts,v)-(m+p))<20*l),f.forEach(function(e){e.pts=Kn(e.pts,v)}),!s||m<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:i&&!u?Math.max(0,v-p):f[0].pts-p}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=m+p;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(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>=t*l&&h<1e4&&u){let t=Math.round(o/l);for(i=a-t*l;i<0&&t&&l;)t--,i+=l;0===s&&(this.nextAudioTs=m=i-p),this.warn(`Injecting ${t} audio frames @ ${((i-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=_n.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(s,0,{unit:t,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,T=null,S=0,L=f.length;for(;L--;)S+=f[L].unit.byteLength;for(let w=0,_=f.length;w<_;w++){const t=f[w],i=t.unit;let r=t.pts;if(null!==T){c[w-1].duration=Math.round((r-T)/a)}else{if(s&&"aac"===e.segmentCodec&&(r=m+p),E=r,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(P){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:P,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(y.buffer).setUint32(0,S),y.set(xn.types.mdat,4)}}y.set(i,g);const n=i.byteLength;g+=n,c.push($n(!0,o,n,0)),T=r}const b=c.length;if(!b)return;const A=c[c.length-1];m=T-p,this.nextAudioTs=m+a*A.duration;const R=d?new Uint8Array(0):xn.moof(e.sequenceNumber++,E/a,pe({},e,{samples:c}));e.samples=[];const I=(E-p)/n,k=this.nextAudioTs/n,D={data1:R,data2:y,startPTS:I,endPTS:k,startDTS:I,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,D}}function Kn(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function Hn(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let o=0;o<r;o++){const r=e.samples[o];r.pts=Kn(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=Kn(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Vn(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=Kn(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function Yn(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function qn(e,t,s){const i=e.codec;if(i&&i.length>4)return i;if(t===Ge){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return _t(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{Nn=self.performance.now.bind(self.performance)}catch(ph){Nn=Date.now}const jn=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Zr("video",1),n=this.audioTrack=Zr("audio",1),a=this.txtTrack=Zr("text",1);if(this.id3Track=Zr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=nt(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=Qe.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=et(e,s);if(i>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=ft(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=it(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(s);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=gt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=gt(e,t),{videoTrack:t,audioTrack:Zr(),id3Track:i,textTrack:Zr()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=it(e.samples,["emsg"]);i&&i.forEach(e=>{const i=function(e){const t=e[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==Je(e.subarray(h,h+1));)s+=Je(e.subarray(h,h+1)),h+=1;for(s+=Je(e.subarray(h,h+1)),h+=1;"\0"!==Je(e.subarray(h,h+1));)i+=Je(e.subarray(h,h+1)),h+=1;i+=Je(e.subarray(h,h+1)),h+=1,r=et(e,12),n=et(e,16),o=et(e,20),l=et(e,24),h=28}else if(1===t){h+=4,r=et(e,h),h+=4;const t=et(e,h);h+=4;const n=et(e,h);for(h+=4,a=2**32*t+n,ie(a)||(a=Number.MAX_SAFE_INTEGER,Re.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=et(e,h),h+=4,l=et(e,h),h+=4;"\0"!==Je(e.subarray(h,h+1));)s+=Je(e.subarray(h,h+1)),h+=1;for(s+=Je(e.subarray(h,h+1)),h+=1;"\0"!==Je(e.subarray(h,h+1));)i+=Je(e.subarray(h,h+1)),h+=1;i+=Je(e.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(pn.test(i.schemeIdUri)){const e=vn(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Jr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=vn(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:Jr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends Ee{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=nt(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&ct(e,(e,t)=>{const i=e.subarray(8,24);i.some(e=>0!==e)||(Re.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Pe(i)} -> ${Pe(s)}`),e.set(s,8))})}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(s=qn(r,Ge,this)),n&&(i=qn(n,Ke,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};se(h)||(h=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return d;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,s){const i={},r=it(e,["moof","traf"]);for(let n=0;n<r.length;n++){const e=r[n],a=it(e,["tfhd"])[0],o=et(a,4),l=t[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=i[o],d=it(e,["tfdt"])[0];if(d){const e=d[0];let t=et(d,4);1===e&&(t===ze?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=ze+1,t+=et(d,8))),se(t)&&(!se(h.start)||t<h.start)&&(h.start=t)}const c=l.default,u=et(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=et(a,2&u?12:8));const g=it(e,["trun"]);let m=h.start||0,p=0,v=f;for(let t=0;t<g.length;t++){const e=g[t],s=et(e,4),i=h.sampleCount;h.sampleCount+=s;const r=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],d=8&e[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&e[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=i),c+=4,a?(v=et(e,c),c+=4):v=f,o&&(c+=4),d&&(c+=4),m+=v,p+=v,u--);u--;)a?(v=et(e,c),c+=4):v=f,o&&(c+=4),l&&(1&e[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=m),c+=4),d&&(c+=4),m+=v,p+=v;!p&&f&&(p+=f*s)}h.duration+=p}if(!Object.keys(i).some(e=>i[e].duration)){let t=1/0,s=0;const r=it(e,["sidx"]);for(let e=0;e<r.length;e++){const i=rt(r[e]);if(null!=i&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);const e=i.references.reduce((e,t)=>e+t.info.duration||0,0);s=Math.max(s,e+i.earliestPresentationTime/i.timescale)}}s&&se(s)&&Object.keys(i).forEach(e=>{i[e].duration||(i[e].duration=s*i[e].timescale-i[e].start)})}return i}(c,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Yn(p,1/0),y=Yn(m,1/0),E=Yn(p,0,!0),T=Yn(m,0,!0);let S=r,L=0;const b=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),A=b?m:p;if(A){const e=A.timescale,t=A.start-r*e,s=b?f.audio.id:f.video.id;S=A.start/e,L=b?T-y:E-v,!n&&l||!function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>r}(l,S,r,L)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${t}/${e}) trackId: ${s}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=S,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const R=S-l.baseTime/l.timescale,I=R+L;L>0?this.lastEndTime=I:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!f.audio,D=!!f.video;let P="";k&&(P+="audio"),D&&(P+="video");const w={data1:c,startPTS:R,startDTS:R,endPTS:I,endDTS:I,type:P,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=k&&!D?w:void 0,d.video=D?w:void 0;const _=null==p?void 0:p.sampleCount;if(_){const e=p.keyFrameIndex,t=-1!==e;w.nb=_,w.dropped=0===e||this.isVideoContiguous?0:t?e:_,w.independent=t,w.firstKeyFrame=e,t&&p.keyFrameStart&&(w.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${_} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return d.initSegment=u,d.id3=Hn(s,r,l,l),i.samples.length&&(d.text=Vn(i,r,l)),d}}},{demux:An,remux:Gn},{demux:class extends en{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Mr(e,0);let i=(null==s?void 0:s.length)||0;if(un(e,i))return!1;for(let r=e.length;i<r;i++)if(Ur(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Or(e,t)&&Nr(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){$r(e,this.observer,t,s,e.manifestCodec);const i=Kr(e,t,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:Gn},{demux:class extends en{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Mr(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==Qr(t)&&fn(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(un(e,s))return Re.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return dn(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return ln(e,t,s,this.basePTS,this.frameIndex)}},remux:Gn}];jn.splice(2,0,{demux:gn,remux:Gn});class Wn{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Nn();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(e,t){let s=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t);return s}(n,t);if(E&&li(E.method)){const e=this.getDecrypter(),t=hi(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,t).then(e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t}),this.decryptionPromise;{let i=e.softwareDecrypt(n,E.key.buffer,E.iv.buffer,t);if(s.part>-1){const t=e.flush();i=t?t.buffer:t}if(!i)return r.executeEnd=Nn(),zn(s);n=new Uint8Array(i)}}const T=this.needsProbing(h,d);if(T){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Nn(),zn(s)}(h||d||f||T)&&this.resetInitSegment(y,g,m,v,t),(h||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,s);this.asyncResult=Xn(S);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=Nn(),S}flush(e){const t=e.transmuxing;t.executeStart=Nn();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Nn();const s=[zn(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return Xn(h)?(this.asyncResult=!0,h.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===ue.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Nn()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,i),a.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let d=0,c=jn.length;d<c;d++){var n;if(null!=(n=jn[d].demux)&&n.probe(e,this.logger)){r=jn[d];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(s,t,i,this.logger)),a&&a instanceof h||(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Bs(this.config)),e}}const zn=e=>({remuxResult:{},chunkMeta:e});function Xn(e){return"then"in e&&e.then instanceof Function}class Qn{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Jn{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Zn=0;class ea{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Zn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===oe.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Dr,this.observer.on(oe.FRAG_DECRYPTED,n),this.observer.on(oe.ERROR,n);const a=Ot(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=wr[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return wr[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=wr[Pr];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return wr[Pr]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Jt(r)})}catch(ph){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,ph),this.terminateWorker(),this.error=null,this.transmuxer=new Wn(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Wn(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Zn++;const t=this.hls.config,s=Ot(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Jt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=wr[e||Pr];if(t&&1===t.clientCount--){const{worker:s,objectURL:i}=t;delete wr[e||Pr],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.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===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!T&&L||(n.stats.parsing.start=b);const A=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),R=new Jn(v,L,o,y,g,A);if(!L||v||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===ue.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 e=new Qn(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,R);Xn(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);Xn(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class ta extends Lr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",ue.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(oe.BUFFER_RESET,this.onBufferReset,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(oe.BUFFER_RESET,this.onBufferReset,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){if(s===ue.MAIN){const e=t.cc,s=this.fragCurrent;if(this.initPTS[e]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===Tr){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==e)&&this.syncWithAnchor(t,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==e?(s.abortRequests(),this.syncWithAnchor(t,s)):this.state===cr&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(t&&(null==i?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=us(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===cr&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=dr);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=cr):this.state=mr,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case cr:this.doTickIdle();break;case mr:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Tr}break}case gr:this.checkRetryDate();break;case Tr:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=fr;const e={frag:t,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=cr}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=mr,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ge,ue.AUDIO));const h=this.getFwdBufferInfo(l,ue.AUDIO);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(oe.BUFFER_EOS,{type:"audio"}),void(this.state=yr);const d=h.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:h.end;if(this.switchingTrack&&i){const e=g;o.PTSKnown&&e<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(d>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,h,ue.MAIN,c)),!p)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Ye(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ds&&(this.mainFragLoading=v=null),v&&Ye(v))){if(p.start>v.end){const e=this.fragmentTracker.getFragAtPos(m,ue.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new zt(e))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==dr&&(this.setInterval(100),this.state=cr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(oe.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=t;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dr&&(this.state=mr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||null!=(s=h.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(h.details)d=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(nr(r,l),r.alignedSliding||ar(r,l),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(oe.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==mr||this.waitForCdnTuneIn(r)||(this.state=cr),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new ea(this.hls,ue.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=i?i.index:-1,n=-1!==t,a=new Ys(s.level,s.sn,s.stats.chunkCount,r.byteLength,t,n);c.push(r,f,d,"",s,i,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ar,complete:!1};e.push(new Uint8Array(r)),this.state!==dr&&(this.state=Tr)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ue.MAIN&&Ye(t.frag)&&(this.mainFragLoading=t,this.state===cr&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type===ue.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Ye(s)){this.fragPrevious=s;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(oe.AUDIO_TRACK_SWITCHED,ye({},e)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==ue.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var s;if(t.fatal)this.state=Er;else switch(t.details){case ae.FRAG_GAP:case ae.FRAG_PARSING_ERROR:case ae.FRAG_DECRYPT_ERROR:case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ue.AUDIO,t);break;case ae.AUDIO_TRACK_LOAD_ERROR:case ae.AUDIO_TRACK_LOAD_TIMEOUT:case ae.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==mr||(null==(s=t.context)?void 0:s.type)!==de||(this.state=cr);break;case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ae.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ae.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Ke&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ke){this.flushing=!1,this.bufferFlushed=!0,this.state===yr&&(this.state=cr);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,ue.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=pr,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,e,n),i.trigger(oe.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Ge]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Ge,e,t,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=pe({id:s,frag:o,details:d},f);i.trigger(oe.FRAG_PARSING_METADATA,e)}if(u){const e=pe({id:s,frag:o,details:d},u);i.trigger(oe.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,s,i){if(this.state!==pr)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=ue.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(oe.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(oe.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||i===Rs||i===ks)if(Ye(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Tr;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&ar(t.details,s)}else super.loadFragment(e,t,s);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;is({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},e,rs)||(as(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(oe.AUDIO_TRACK_SWITCHED,ye({},e))}}class sa extends Ee{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let n=-1;for(let s=0;s<i.length;s++){const a=i[s];let o;try{o=new self.URL(a.URI,t.url).href}catch(r){this.warn(`Could not construct new URL for Rendition Report: ${r}`),o=a.URI||""}if(o===e){n=s;break}o===e.substring(0,o.length)&&(n=s)}if(-1!==n){const e=i[n],r=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&jt(s);return new Wt(r,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const e=Math.max(o||0,0);i.appliedTimelineOffset=e,i.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(i.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){Yi(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void s.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=zi(i,1e3*(i.edge-d));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=e?0:l):(f=r,g=e?l+1:i.maxPartIndex):f=a+1;const d=i.age,c=d+i.ageHeader;let m=Math.min(c-i.partTarget,1.5*i.targetduration);if(m>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${i.age}`),m=0;else{const e=Math.floor(m/i.targetduration);if(f+=e,void 0!==g){g+=Math.round(m%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${m} skip sn ${e} to part ${g}`)}i.tuneInGoal=m}if(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g),e||!h)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,i){let r=jt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=qt.No),new Wt(s,i,r)}checkRetry(e){const t=e.details,s=fs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Ss.RetryRequest||!i.resolved&&r===Ss.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=vs(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}function ia(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!ra(e[s].attrs,t[s].attrs))return!1;return!0}function ra(e,t,s){const i=e["STABLE-RENDITION-ID"];return i&&!s?i===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>e[s]!==t[s])}function na(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class aa extends sa{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(oe.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!s||-1!==s.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const s=ss(t,e,rs);if(s>-1)r=e[s];else{const e=ss(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(oe.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==de||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&is(e,i,rs))return i;const r=ss(e,this.tracksInGroup,rs);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(i){let i=t.loadLevel;-1===i&&(i=t.firstAutoLevel);const r=function(e,t,s,i,r){const n=t[i],a=t.reduce((e,t,s)=>{const i=t.uri;return(e[i]||(e[i]=[])).push(s),e},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ns(t,i,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const i=t.audioGroups,n=s.filter(e=>!i||-1!==i.indexOf(e.groupId));return ss(e,n,r)>-1});return d>-1?d:ns(t,i,t=>{const i=t.audioGroups,n=s.filter(e=>!i||-1!==i.indexOf(e.groupId));return ss(e,n,r)>-1})}(e,t.levels,s,i,rs);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=ss(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(oe.AUDIO_TRACK_SWITCHING,ye({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||is(e,i,rs)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(is({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],rs))return e}for(let l=0;l<t.length;l++){const s=t[l];if(ra(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const s=t[l];if(ra(e.attrs,s.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&as(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(oe.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class oa{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(i){var s;if(r.onError(i),null===this.queues||null===this.tracks)return;const t=null==(s=this.tracks[e])?void 0:s.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const la=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ha="HlsJsTrackRemovedError";class da extends Error{constructor(e){super(e),this.name=ha}}class ca extends Ee{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(oe.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=Ie(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.BUFFER_RESET,this.onBufferReset,this),e.on(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.BUFFER_EOS,this.onBufferEos,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.FRAG_PARSED,this.onFragParsed,this),e.on(oe.FRAG_CHANGED,this.onFragChanged,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.BUFFER_RESET,this.onBufferReset,this),e.off(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.BUFFER_EOS,this.onBufferEos,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.FRAG_PARSED,this.onFragParsed,this),e.off(oe.FRAG_CHANGED,this.onFragChanged,this),e.off(oe.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?pe(s,i.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(s[t]=pe({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Ie(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&n instanceof t,ua(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(r){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&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: ${Jt(s,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${Jt(i,(e,t)=>"initSegment"===e?void 0:t)}}`),!ke(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(oe.MEDIA_DETACHING,{}),this.onMediaAttaching(oe.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=js.getBuffered(e);i.detectEvictedFragments(t,s,r,null,!0)}const n=fa(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(ph){this.warn(`onMediaDetaching: ${ph.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&ua(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(oe.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(ph){this.warn(`onBufferReset ${e}`,ph)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fa(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new oa(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!i[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=Ct(m,p),y=null==v?void 0:v.replace(la,"$1");let E=Ct(o,l);const T=null==(r=E)?void 0:r.replace(la,"$1");E&&v&&y!==T&&("audio"===e.slice(0,5)&&(E=_t(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(e,h,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,ue.MAIN))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>i||null!=t&&t.buffer&&js.isBuffered(t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,ue.MAIN))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();d.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=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||js.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!js.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const T=(o||a).start,S={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,T,.1,r,c,u):void 0!==h&&se(h)&&this.updateTimestampOffset(t,h,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);const t={};this.sourceBuffers.forEach(([e,s])=>{e&&(t[e]=js.getBuffered(s))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(oe.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:ne.MEDIA_ERROR,parent:a.type,details:ae.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},i=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)s.details=ae.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=As(!0);else if(e.name===ha&&0===this.sourceBufferCount)s.errorAction=As(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger(oe.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===ue.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[He]?r.push("audiovideo"):(n[Ge]&&r.push("audio"),n[Ke]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.hls.trigger(oe.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type})},r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ae.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;se(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(se(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=i.frontBufferFlushThreshold;if(se(o)&&o>0){const e=Math.max(i.maxBufferLength,o),t=Math.max(e,n),s=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([e,t])=>{if(t){const r=js.getBuffered(t);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger(oe.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(oe.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([t,i])=>{if(i){const r=js.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return se(r)?{duration:r}:null;const n=this.media.duration;return i>(se(s.duration)?s.duration:0)&&i>n||!se(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==e&&(se(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Jt(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(oe.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const e=this.getTrackCodec(o,a),n=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${Jt(o)}`);try{const e=s.addSourceBuffer(n),i=fa(a),r=[a,e];t[i]=r,o.buffer=e}catch(r){var i;return this.error(`error while trying to add sourceBuffer: ${r.message}`),this.shiftAndExecuteNext(a),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[a],void this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:r,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&At(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)bt(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=Ct(i,e.levelCodec);return r?"audio"===t.slice(0,5)?_t(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=se(i.duration)?i.duration:1/0,l=se(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),a.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new da(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(e=>{s.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}function ua(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function fa(e){return"audio"===e?1:0}class ga{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&se(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((t,s)=>this.isLevelAllowed(t)&&s<=e);return this.clientRect=null,ga.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;const i=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let r=e.length-1;const n=Math.max(t,s);for(let a=0;a<e.length;a+=1){const t=e[a];if((t.width>=n||t.height>=n)&&i(t,e[a+1])){r=a;break}}return r}}const ma={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},pa={HLS:"h"};class va{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof va?e:new va(e))),this.value=e,this.params=t}}function ya(e,t,s,i){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}function Ea(e,t,s){return ya("serialize",e,t,s)}class Ta{constructor(e){this.description=e}}const Sa="Bare Item";function La(e){if(!1===ArrayBuffer.isView(e))throw Ea(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function ba(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Ea(e,"Integer");return e.toString()}function Aa(e,t){if(e<0)return-Aa(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}function Ra(e){const t=Aa(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ea(e,"Decimal");const s=t.toString();return s.includes(".")?s:`${s}.0`}const Ia=/[\x00-\x1f\x7f]+/;function ka(e){const t=(s=e).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Ea(t,"Token");return t}function Da(e){switch(typeof e){case"number":if(!se(e))throw Ea(e,Sa);return Number.isInteger(e)?ba(e):Ra(e);case"string":return function(e){if(Ia.test(e))throw Ea(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return ka(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Ea(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${ba(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return La(e);if(e instanceof Ta)return ka(e);default:throw Ea(e,Sa)}}function Pa(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Ea(e,"Key");return e}function wa(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${Pa(e)}`:`;${Pa(e)}=${Da(t)}`).join("")}function _a(e){return e instanceof va?`${Da(e.value)}${wa(e.params)}`:Da(e)}function Ca(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Ea(e,"Dict");const s=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(s).map(([e,t])=>{t instanceof va==!1&&(t=new va(t));let s=Pa(e);var i;return!0===t.value?s+=wa(t.params):(s+="=",Array.isArray(t.value)?s+=`(${(i=t).value.map(_a).join(" ")})${wa(i.params)}`:s+=_a(t)),s}).join(`,${i}`)}function xa(e,t){return Ca(e,t)}const Ma="CMCD-Object",Oa="CMCD-Request",Fa="CMCD-Session",Na="CMCD-Status",Ba={br:Ma,ab:Ma,d:Ma,ot:Ma,tb:Ma,tpb:Ma,lb:Ma,tab:Ma,lab:Ma,url:Ma,pb:Oa,bl:Oa,tbl:Oa,dl:Oa,ltc:Oa,mtp:Oa,nor:Oa,nrr:Oa,rc:Oa,sn:Oa,sta:Oa,su:Oa,ttfb:Oa,ttfbb:Oa,ttlb:Oa,cmsdd:Oa,cmsds:Oa,smrt:Oa,df:Oa,cs:Oa,ts:Oa,cid:Fa,pr:Fa,sf:Fa,sid:Fa,st:Fa,v:Fa,msd:Fa,bs:Na,bsd:Na,cdn:Na,rtp:Na,bg:Na,pt:Na,ec:Na,e:Na},Ua=Oa;function $a(e,t){const s={};if(!e)return s;const i=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var s;return null===(s=n[t])||void 0===s||s.forEach(s=>e[s]=t),e},{})):{};var n;return i.reduce((t,s)=>{var i;const n=Ba[s]||r[s]||Ua;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[s]=e[s],t},s)}const Ga="event";const Ka=e=>Math.round(e),Ha=(e,t)=>Array.isArray(e)?e.map(e=>Ha(e,t)):e instanceof va&&"string"==typeof e.value?new va(Ha(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const s=new URL(e),i=new URL(t);if(s.origin!==i.origin)return e;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),Va=e=>100*Ka(e/100),Ya={br:Ka,d:Ka,bl:Va,dl:Va,mtp:Va,nor:(e,t)=>{let s=e;return t.version>=2&&(e instanceof va&&"string"==typeof e.value?s=new va([e]):"string"==typeof e&&(s=[e])),Ha(s,t)},rtp:Va,tb:Ka},qa="request",ja="response",Wa=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],za=["e"],Xa=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Qa(e){return Xa.test(e)}const Ja=["d","dl","nor","ot","rtp","su"];const Za=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const eo=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function to(e){return eo.includes(e)||Qa(e)}const so={[ja]:function(e){return Wa.includes(e)||Ja.includes(e)||Za.includes(e)||Qa(e)},[Ga]:function(e){return Wa.includes(e)||za.includes(e)||Qa(e)},[qa]:function(e){return Wa.includes(e)||Ja.includes(e)||Qa(e)}};function io(e,t={}){const s={};if(null==e||"object"!=typeof e)return s;const i=t.version||e.v||1,r=t.reportingMode||qa,n=1===i?to:so[r];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ja||r===Ga;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const h=pe({},Ya,t.formatters),d={version:i,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let r=e[t];const n=h[t];if("function"==typeof n&&(r=n(r,d)),"v"===t){if(1===i)return;r=i}"pr"==t&&1===r||(l&&"ts"===t&&!se(r)&&(r=Date.now()),function(e){return"number"==typeof e?se(e):null!=e&&""!==e&&!1!==e}(r)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof r&&(r=new Ta(r)),s[t]=r))}),s}function ro(e,t,s){return pe(e,function(e,t={}){const s={};if(!e)return s;const i=$a(io(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce((e,[t,s])=>{const i=xa(s,{whitespace:!1});return i&&(e[t]=i),e},s)}(t,s))}function no(e,t={}){if(!e)return"";const s=function(e,t={}){return e?xa(io(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(s)}const ao=/CMCD=[^&#]+/;function oo(e,t,s){const i=function(e,t={}){return e?`CMCD=${no(e,t)}`:""}(t,s);if(!i)return e;if(ao.test(e))return e.replace(ao,i);const r=e.includes("?")?"&":"?";return`${e}${r}${i}`}class lo{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:ma.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=e=>{try{const{frag:t,part:s}=e,i=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(s||t).duration,ot:r};r!==ma.VIDEO&&r!==ma.AUDIO&&r!=ma.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHED,this.onMediaDetached,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHED,this.onMediaDetached,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=null==(s=t.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}createData(){var e;return{v:1,sf:pa.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){pe(t,this.createData());const s=t.ot===ma.INIT||t.ot===ma.VIDEO||t.ot===ma.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((e,s)=>(i.includes(s)&&(e[s]=t[s]),e),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),ro(e.headers,t,r)):e.url=oo(e.url,t,r)}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=i;for(let t=r.length-1;t>=0;t--){const i=r[t];if(i.index===s&&i.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?ma.TIMED_TEXT:"initSegment"===e.sn?ma.INIT:"audio"===t?ma.AUDIO:"main"===t?this.hls.audioTracks.length?ma.VIDEO:ma.MUXED:void 0}getTopBandwidth(e){let t,s=0;const i=this.hls;if(e===ma.AUDIO)t=i.audioTracks;else{const e=i.maxAutoLevel,s=e>-1?e+1:i.levels.length;t=i.levels.slice(0,s)}return t.forEach(e=>{e.bitrate>s&&(s=e.bitrate)}),s>0?s:NaN}getBufferLength(e){const t=this.media,s=e===ma.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!t)return NaN;return 1e3*js.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}}class ho extends Ee{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===Ss.SendAlternateToPenaltyBox&&s.flags===Ls.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),t.details!==ae.BUFFER_APPEND_ERROR||t.fatal?s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${Jt(i)} penalized: ${Jt(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(e=>{i-s[e]>3e5&&delete s[e]});for(let r=0;r<e.length;r++){const i=e[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Zi(t),this.hls.trigger(oe.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===de&&i[r].hasAudioGroup(e)||t===ce&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new ti(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=uo(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new zt({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let s=1;s<e.audioGroups.length;s++)h.addGroupId("audio",`${e.audioGroups[s]}_clone_${r}`);if(e.subtitleGroups)for(let s=1;s<e.subtitleGroups.length;s++)h.addGroupId("text",`${e.subtitleGroups[s]}_clone_${r}`);return h});t.push(...o),co(this.audioTracks,s,a,r),co(this.subtitleTracks,i,a,r)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(h){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(h){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:i.toString()};this.hls.trigger(oe.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}}function co(e,t,s,i){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=pe({},e);return n.details=void 0,n.attrs=new ti(n.attrs),n.url=n.attrs.URI=uo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n});e.push(...n)})}function uo(e,t,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class fo extends Ee{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=fo.CDMCleanupPromise?[fo.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,i=`"${e.type}" event: init data type: "${t}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ei(this.config));const t=e.map(yi).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{const n=vi(r);if("sinf"!==t||n!==mi.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=Je(new Uint8Array(s)),t=ut(di(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(c){return void this.warn(`${i} Failed to parse sinf: ${c}`)}const o=Pe(a),{keyIdToKeySessionPromise:l,mediaKeySessions:h}=this;let d=l[o];for(let e=0;e<h.length;e++){const i=h[e],r=i.decryptdata;if(!r.keyId)continue;const n=Pe(r.keyId);if(ai(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(d=l[n],!d)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(s),r.keyId=a,d=l[o]=d.then(()=>this.generateRequestWithPreferredKeySession(i,t,s,"encrypted-event-key-match")),d.catch(e=>this.handleError(e));break}}d||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(oe.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(oe.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(oe.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(oe.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=null==t?void 0:t[e];return i?i.licenseUrl:e===mi.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=null==t?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,i=t.map(e=>e.audioCodec).filter(s),r=t.map(e=>e.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,i,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):s(t instanceof po?t:new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===Ti&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=function(e,t,s,i){let r;switch(e){case mi.FAIRPLAY:r=["cenc","sinf"];break;case mi.WIDEVINE:case mi.PLAYREADY:r=["cenc"];break;case mi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,s,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,t,s,i)}(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Jt(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,i.then(t=>t?this.setMediaKeysServerCertificate(s,e,t):s)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Pe(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=go(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Pe(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>yi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const i=yi(e);i?t(i):s(new Error(`Unable to find format for key-system "${e}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Ei(this.config),s=e.map(vi).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=mo(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=go(t),i=this.bannedKeyIds[s];if(i||"internal-error"===this.getKeyStatus(t)){const s=vo(i||"internal-error",t);return this.handleError(s,e.frag),Promise.reject(s)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const i=this.getKeySystemForKeyPromise(t).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:t}))))).then(e=>{const s=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",s,"playlist-key")});return i.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[s]=i,i}return n.catch(s=>{if(s instanceof po){const i=ye({},s.data);"internal-error"===this.getKeyStatus(t)&&(i.decryptdata=t);const r=new po(i,s.message);this.handleError(r,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof po){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Pe(s.keyId||[])})`:""}`),this.hls.trigger(oe.ERROR,e.data)}else this.error(e.message),this.hls.trigger(oe.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=go(e),s=this.keyIdToKeySessionPromise[t];if(!s){const t=vi(e.keyFormat),s=t?[t]:Ei(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ei(this.config)),0===e.length)throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Jt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(s)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===s.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(n)try{const i=n.call(this.hls,t,s,e);if(!i)throw new Error("Invalid response from configured generateRequest filter");t=i.initDataType,s=i.initData?i.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const a=go(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${s.byteLength})`);const l=new Dr,h=e._onmessage=t=>{const s=e.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:i,message:r}=t;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(e,r).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===i?e.keySystem===mi.FAIRPLAY&&this.updateKeySession(e,ci("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${i}"`)},d=(e,t)=>{let s;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?s=vo(e,t.decryptdata):"expired"===e?s=new Error(`key expired (keyId: ${a})`):"released"===e?s=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),s&&(l.eventNames().length?l.emit("error",s):this.handleError(s))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const s=this.getKeyStatuses(e);if(!Object.keys(s).some(e=>"status-pending"!==s[e]))return;if("expired"===s[a])return this.log(`Expired key ${Jt(s)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let i=s[a];if(i)d(i,e);else{var r;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const s=this.getKeyStatus(e.decryptdata);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${s} from other session.`),d(s,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),i="internal-error",d(i,e)},t)),this.log(`No status for keyId ${a} (${Jt(s)}).`)}};or(e.mediaKeysSession,"message",h),or(e.mediaKeysSession,"keystatuseschange",c);const u=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>u).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if("string"==typeof i&&"object"==typeof s){const e=i;i=s,s=e}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===mi.PLAYREADY&&16===r.length){const e=Pe(r);t[e]=s,ui(r)}const n=Pe(r);"internal-error"===s&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{r(e.data)},onError:(t,s,r,o)=>{n(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:ye({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,r)=>{n(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(e=>{r(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let s=0,i=r.length;s<i;s++){var n,a;t=r[s];const i=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;i&&o&&e.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ci(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(s=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:s||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const s=this.config.licenseResponseCallback;if(s)try{t=s.call(this.hls,a,n,e)}catch(o){this.error(o)}i(t)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then(({xhr:t,licenseChallenge:s})=>{e.keySystem==mi.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,or(s,"encrypted",this.onMediaEncrypted),or(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(lr(e,"encrypted",this.onMediaEncrypted),lr(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ai.clearKeyUriToKeyIdMap();const r=i.length;fo.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((null==s||null==(e=s.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Pe((null==i?void 0:i.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(s)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function go(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Pe(e.keyId)}function mo(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}fo.CDMCleanupPromise=void 0;class po extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function vo(e,t){const s="output-restricted"===e,i=s?ae.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ae.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new po({type:ne.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}class yo{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(oe.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(oe.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Eo(e,t){let s;try{s=new Event("addtrack")}catch(ph){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function To(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(ph){Re.debug(`[texttrack-utils]: ${ph}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(i){Re.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}"disabled"===s&&(e.mode=s)}function So(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===s&&(e.mode=s)}function Lo(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function bo(e){const t=[];for(let s=0;s<e.length;s++){const i=e[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[s])}return t}class Ao extends sa{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=bo(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const s=this.findTrackForTextTrack(e);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(oe.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;bo(s.textTracks).forEach(e=>{So(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!s||-1!==s.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const s=ss(t,e);if(s>-1)r=e[s];else{const e=ss(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(oe.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if((!s||r.default)&&(s||e)&&(!e||is(r,e)))return i}if(e){for(let s=0;s<t.length;s++){const i=t[s];if(ra(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(ra(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){if(na(t[s],e))return s}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==ce||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&is(e,s))return s;const i=ss(e,this.tracksInGroup);if(i>-1){const e=this.tracksInGroup[i];return this.setSubtitleTrack(i),e}if(s)return null;{const s=ss(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(oe.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=bo(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(e=>na(s,e))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==i&&(e.mode="disabled")}),i){const e=this.subtitleDisplay?"showing":"hidden";i.mode!==e&&(i.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!se(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(oe.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(oe.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}}function Ro(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}const Io=.025;let ko=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Do(e,t,s){return`${e.identifier}-${s+1}-${Ro(t)}`}class Po{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;if(e<=0||isNaN(s))return!1;if(0===s)return!0;return((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return wo(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-wo(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=se(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return wo(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Io))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?ko.Range:ko.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function wo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Io)?t.start:t.start+t.duration}function _o(e,t,s){const i=new self.URL(e,s);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",t),i}function Co(e,t){for(;null!=(s=e.assetList[++t])&&s.error;)var s;return t}function xo(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}class Mo{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(oe.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(oe.LEVEL_LOADED,n),r.once(oe.AUDIO_TRACK_LOADED,n),r.once(oe.SUBTITLE_TRACK_LOADED,n),r.on(oe.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(oe.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(oe.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let s=this.assetItem.uri;try{s=_o(s,e.config.primarySessionId||"").href}catch(t){}e.loadSource(s)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=js.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=js.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;null==(i=this.hls)||i.on(e,t)}once(e,t,s){var i;null==(i=this.hls)||i.once(e,t)}off(e,t,s){var i;null==(i=this.hls)||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xo(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Oo extends Ee{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const e=s[i].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if((null==(s=t[i].event)?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const e=s[r];if(!e.error){const s=e.timelineStart;if(t===s||t>s&&(t<s+(e.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,s=e[e.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),a=Object.keys(i),o=r?r.filter(e=>!a.includes(e.identifier)):[];n.length&&n.sort((e,t)=>{const s=e.cue.pre,i=e.cue.post,r=t.cue.pre,n=t.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=e.startTime,i=t.startTime;if(s!==i)return s-i}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||(null==r?void 0:r.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new Po(o,t),this.eventMap[a]=e,!1===s&&(e.appendInPlace=s)),i.push(e)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let i=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,h=t.cue.post,d=e[a-1]||null,c=t.appendInPlace,u=h?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===ko.Range?f:0,m=t.resumptionOffset,p=(null==d?void 0:d.startTime)===u,v=u+t.cumulativeDuration;let y=c?v+f:u+m;if(l||!h&&u<=0){const e=o;o+=g,t.timelineStart=v;const i=n;n+=f,s.push({event:t,start:v,end:y,playout:{start:i,end:n},integrated:{start:e,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,h=o;o+=r;const d=n;n+=r;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:d,end:n},integrated:{start:h,end:o}};s.push(c)}else r>0&&d&&(d.cumulativeDuration+=r,s[s.length-1].end=u)}h&&(y=v),t.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:t,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=t.resumeTime;i=h||E>r?r:E}),i<r){var a;const e=i,t=o,l=r-i;o+=l;const h=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:i,end:e+l,playout:{start:h,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;s.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,d=l?0:h?i:a.startTime;this.updateAssetDurations(a);if(n===d?a.cumulativeDuration=r:(r=0,n=d),!h&&a.snapOptions.in&&(a.resumeAnchor=hs(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=se(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;if(Math.abs(s-i)>Io)return this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;return!Object.keys(t).some(i=>{const r=t[i].details,n=r.edge;if(s>=n)return this.log(`"${e.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=hs(null,r.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Io+o||Math.abs(a.end-s)<Io+o)&&(this.log(`"${e.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error);s+=a.error?0:a.duration||0}e.duration=i&&!r?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Fo(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class No{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=_o(s,this.hls.sessionId,e.baseUrl)}catch(d){const t=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_ERROR,d,s);return void this.hls.trigger(oe.ERROR,t)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,s,i,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,ae.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(oe.ERROR,t)}e.assetListResponse=n,this.hls.trigger(oe.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,s,i,r)=>{const n=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,r,i);this.hls.trigger(oe.ERROR,n)},onTimeout:(t,s,i)=>{const r=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,i);this.hls.trigger(oe.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(oe.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:ne.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Bo(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Uo(e,t){return`[${e}] Advancing timeline position to ${t}`}class $o extends Lr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",ue.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(oe.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(oe.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=cr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(Ye(s)&&(this.fragPrevious=s),this.state=cr),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(0===s&&i!==Number.POSITIVE_INFINITY){const e=i-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}}),this.fragmentTracker.removeFragmentsInRange(s,e,ue.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===ue.SUBTITLE&&(t.details===ae.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dr&&(this.state=cr))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&ia(this.levels,t)?this.levels=t.map(e=>new zt(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new zt(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ue.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==dr&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Wi(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(ar(n,e),l=n.fragmentStart):t&&(l=t.start,Wi(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger(oe.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===cr)){hs(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&li(i.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,hi(i.method)).catch(e=>{throw r.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(s=>{const i=performance.now();r.trigger(oe.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:e,tdecrypt:i}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=cr})}}doTick(){if(this.media){if(this.state===cr){const{currentTrackId:e,levels:t}=this,s=null==t?void 0:t[e];if(!s||!t.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=js.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=i.maxFragLookUpTolerance,t=a>c-e?0:e;u=hs(f,h,Math.max(h[0].start,a),t),!u&&f&&f.start<h[0].start&&(u=h[0])}else u=h[d-1];if(u=this.filterReplacedPrimary(u,s.details),!u)return;const g=h[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===Rs&&(u=g),this.fragmentTracker.getState(u)===Rs){const e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,s,a)}}}else this.state=cr}loadFragment(e,t,s){Ye(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Go(this.tracksBuffered[this.currentTrackId]||[])}}class Go{constructor(e){this.buffered=void 0;const t=(t,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}const Ko={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ho=e=>String.fromCharCode(Ko[e]||e),Vo=15,Yo=100,qo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},jo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Wo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Xo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Qo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;Re.log(`${this.time} [${e}] ${s}`)}}}const Jo=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Zo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class el{constructor(){this.uchar=" ",this.penState=new Zo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class tl{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Zo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Yo;t++)this.chars.push(new el);this.logger=e}equals(e){for(let t=0;t<Yo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Yo;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Yo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Yo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Yo)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ho(e);this.pos>=Yo?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<Yo;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Yo;s++){const i=this.chars[s].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class sl{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Vo;t++)this.rows.push(new tl(e));this.logger=e}reset(){for(let e=0;e<Vo;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<Vo;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Vo;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Vo;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Jt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let t=0;t<Vo;t++)this.rows[t].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[e].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(s.rows[e+n])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,i=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[i].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Jt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Vo;r++){const s=this.rows[r].getTextString();s&&(i=r+1,e?t.push("Row "+i+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}}class il{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new sl(s),this.nonDisplayedMemory=new sl(s),this.lastOutputScreen=new sl(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+Jt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class rl{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new Qo;this.channels=[null,new il(e,t,i),new il(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const e=127&t[s],i=127&t[s+1];let r=!1,n=null;if(0===e&&0===i)continue;this.logger.log(3,()=>"["+Jo([t[s],t[s+1]])+"] -> ("+Jo([e,i])+")");const a=this.cmdHistory;if(e>=16&&e<=31){if(al(e,i,a)){nl(null,null,a),this.logger.log(3,()=>"Repeated command ("+Jo([e,i])+") is dropped");continue}nl(e,i,this.cmdHistory),r=this.parseCmd(e,i),r||(r=this.parseMidrow(e,i)),r||(r=this.parsePAC(e,i)),r||(r=this.parseBackgroundAttributes(e,i))}else nl(null,null,a);if(!r&&(n=this.parseChars(e,i),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Jo([e,i])+" orig: "+Jo([t[s],t[s+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,i=this.channels[s];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Jo([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const i=e<=23?1:2;s=t>=64&&t<=95?1===i?qo[e]:Wo[e]:1===i?jo[e]:zo[e];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,t)),this.currentChannel=i,!0)}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+Ho(e)+"' in channel "+s),i=[e]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Jo(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let s;const i={};16===e||24===e?(s=Math.floor((t-32)/2),i.background=Xo[s],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}nl(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function nl(e,t,s){s.a=e,s.b=t}function al(e,t,s){return s.a===e&&s.b===t}var ol=function(){if(null!=gi&&gi.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function i(e){return s(t,e)}function r(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=t,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const i=function(t){return s(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");L=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class ll{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function hl(e){function t(e,t,s,i){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(i||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}class dl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function cl(e,t,s,i){const r=i?e.split(i):[e];for(const n in r){if("string"!=typeof r[n])continue;const e=r[n].split(s);if(2!==e.length)continue;t(e[0],e[1])}}const ul=new ol(0,0,""),fl="middle"===ul.align?"middle":"center";function gl(e,t,s){const i=e;function r(){const t=hl(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const i=new dl;cl(e,function(e,t){let r;switch(e){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===t){i.set(e,s[r].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),i.integer(e,r[0]),i.percent(e,r[0])&&i.set("snapToLines",!1),i.alt(e,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",fl,"end"]);break;case"position":r=t.split(","),i.percent(e,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",fl,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",fl,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===ul.line&&(r=-1),t.line=r,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",fl);let n=i.get("position","auto");"auto"===n&&50===ul.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function ml(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class pl{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ll,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=ml(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const i=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),i}function i(e){cl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const i=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:e=s(),t.state){case"HEADER":/:/.test(e)?i(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new ol(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{gl(e,t.cue,t.regionList)}catch(r){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(r){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const vl=/\r\n|\n\r|\n|\r/g,yl=function(e,t,s=0){return e.slice(s,s+t.length)===t};function El(e,t,s){return Ro(e.toString())+Ro(t.toString())+Ro(s)}function Tl(e,t,s,i,r,n,a){const o=new pl,l=De(new Uint8Array(e)).trim().replace(vl,"\n").split("\n"),h=[],d=t?function(e,t=1){return Mn(e,9e4,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s}(s,i,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=e.endTime-e.startTime,u=Kn(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=El(e.startTime,e.endTime,m)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(h)},l.forEach(e=>{if(m){if(yl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach(e=>{yl(e,"LOCAL:")?u=e.slice(6):yl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(se(t)&&se(s)&&se(i)&&se(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*i,t+=36e5*r,t}(u)/1e3}catch(t){c=t}return}""===e&&(m=!1)}o.parse(e+"\n")}),o.flush()}const Sl="stpp.ttml.im1t",Ll=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,bl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Al={left:"start",center:"center",right:"end",start:"start",end:"end"};function Rl(e,t,s,i){const r=it(new Uint8Array(e),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>De(e)),a=function(e,t,s=1,i=!1){return Mn(e,t,1/s,i)}(t.baseTime,1,t.timescale);try{n.forEach(e=>s(function(e,t){const s=(new DOMParser).parseFromString(e,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),o=kl(Il(i,"styling","style")),l=kl(Il(i,"layout","region")),h=Il(i,"body","[begin]");return[].map.call(h,e=>{const s=Dl(e,a);if(!s||!e.hasAttribute("begin"))return null;const i=_l(e.getAttribute("begin"),n),r=_l(e.getAttribute("dur"),n);let h=_l(e.getAttribute("end"),n);if(null===i)throw wl(e);if(null===h){if(null===r)throw wl(e);h=i+r}const d=new ol(i-t,h-t,s);d.id=El(d.startTime,d.endTime,d.text);const c=function(e,t,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce((s,n)=>{const a=Pl(t,i,n)||Pl(e,i,n)||Pl(r,i,n);return a&&(s[n]=a),s},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=c;if(u){const e=Al[u];e&&(d.lineAlign=e),d.align=u}return pe(d,c),d}).filter(e=>null!==e)}(e,a)))}catch(o){i(o)}}function Il(e,t,s){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function kl(e){return e.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Dl(e,t){return[].slice.call(e.childNodes).reduce((e,s,i)=>{var r;return"br"===s.nodeName&&i?e+"\n":null!=(r=s.childNodes)&&r.length?Dl(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent},"")}function Pl(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function wl(e){return new Error(`Could not parse ttml timestamp ${e}`)}function _l(e,t){if(!e)return null;let s=hl(e);return null===s&&(Ll.test(e)?s=function(e,t){const s=Ll.exec(e),i=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/t.frameRate}(e,t):bl.test(e)&&(s=function(e,t){const s=bl.exec(e),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),s}class Cl{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class xl{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this),e.on(oe.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(oe.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(oe.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this),e.off(oe.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(oe.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(oe.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Cl(this,"textTrack1"),t=new Cl(this,"textTrack2"),s=new Cl(this,"textTrack3"),i=new Cl(this,"textTrack4");this.cea608Parser1=new rl(1,e,t),this.cea608Parser2=new rl(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let a=r.length;a--;){const e=r[a],i=Fl(e[0],e[1],t,s);if(i>=0&&(e[0]=Math.min(e[0],t),e[1]=Math.max(e[1],s),n=!0,i/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,s,i)}else{const r=this.Cues.newCue(null,t,s,i);this.hls.trigger(oe.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;s===ue.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(oe.FRAG_LOADED,e):this.hls.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Ol(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)s[e]=a,So(s[e]),Eo(s[e],i);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,s[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(oe.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(e=>{So(i[e]),delete i[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)So(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(e=>e.textCodec===Sl);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ia(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const e=this.media,t=e?bo(e.textTracks):null;if(this.tracks.forEach((e,s)=>{let i;if(t){let s=null;for(let i=0;i<t.length;i++)if(t[i]&&Ol(t[i],e)){s=t[i],t[i]=null;break}s&&(i=s)}if(i)So(i);else{const t=Ml(e);i=this.createTextTrack(t,e.name,e.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(oe.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,i=this.captionsProperties[s];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ue.MAIN){var s,i;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(i=t.part)?void 0:i.index)?s:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===ue.SUBTITLE)if(i.byteLength){const e=s.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),e&&e.textCodec===Sl?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Rl(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),s.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{s.logger.log(`Failed to parse IMSC1: ${t}`),s.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(e);const o=this.hls;Tl(null!=(t=s.initSegment)&&t.data?ft(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,e=>{this._appendCues(e,s.level),o.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>s.cc||o.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:t})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Rl(t,this.initPTS[e.cc],()=>{s.textCodec=Sl,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||"disabled"===s.mode)return;e.forEach(e=>To(s,e))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(oe.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===ue.SUBTITLE&&this.onFragLoaded(oe.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(s.type!==ue.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let r=0;r<i.length;r++){const e=i[r].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const t=this.extractCea608Data(e);this.cea608Parser1.addData(i[r].pts,t[0]),this.cea608Parser2.addData(i[r].pts,t[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach(i=>Lo(e[i],t,s))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==i){const{textTracks:e}=this;Object.keys(e).forEach(s=>Lo(e[s],t,i))}}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let i=2;for(let r=0;r<s;r++){const s=e[i++],r=127&e[i++],n=127&e[i++];if(0===r&&0===n)continue;if(!!(4&s)){const e=3&s;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}}function Ml(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ol(e,t){return!!e&&e.kind===Ml(t)&&na(t,e)}function Fl(e,t,s,i){return Math.min(t,i)-Math.max(e,s)}const Nl=/\s/,Bl={newCue(e,t,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)Nl.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const i=ml(h.trim()),f=El(t,s,i);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new d(t,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>To(e,t))),r}};function Ul(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const $l=/(\d+)-(\d+)\/(\d+)/;class Gl{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Kl,this.controller=new self.AbortController,this.stats=new $e}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(pe({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&se(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout);(Xn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Hl(t||"fetch, bad network response",e,s)}i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=$l.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(se(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&se(t.highWaterMark)?this.loadProgressively(s,i,e,t.highWaterMark,o):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()}).then(s=>{var r,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=s[a];l&&(i.loaded=i.total=l);const h={url:o.url,data:s,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!se(t.highWaterMark)&&d(i,e,s,o),null==(n=this.callbacks)||n.onSuccess(h,i,e,o)}).catch(t=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},e,t?t.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new Ar,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function Kl(e,t){return new self.Request(e.url,t)}class Hl extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Vl=/^age:\s*[\d.]+\s*$/im;class Yl{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new $e,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)}).catch(e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&se(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;if(Es(h,s.retry,!1,{url:e.url,data:void 0,code:i}))this.retry(h);else Re.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Es(e,this.stats.retry,!0))this.retry(e);else{var t;Re.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=vs(e,s.retry),s.retry++,Re.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Vl.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const ql=ye(ye({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Yl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:os,bufferController:ca,capLevelController:ga,errorController:bs,fpsController:yo,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:Ti,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Bl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:$o,subtitleTrackController:Ao,timelineController:xl,audioStreamController:ta,audioTrackController:aa,emeController:fo,cmcdController:lo,contentSteeringController:ho,interstitialsController:class extends Ee{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),s&&e<i.start||e>=i.end){var r;const t=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const t=i.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&e<a||e>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;if(!s)return;e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>Fo(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,d=null;i&&(h=this.updateItem(i,this.timelinePos),this.itemsMatch(i,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(d=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,d)?this.bufferingItem=d:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const s=e.assetItem.timelineStart,i=e.timelineOffset-s;if(i)try{e.timelineOffset=s}catch(t){Math.abs(i)>Io&&this.warn(`${t} ("${e.assetId}" ${e.timelineOffset}->${s})`)}}}),l||t){if(this.hls.trigger(oe.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(h,i),c&&d!==h&&this.trimInPlace(d,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new No(e),this.schedule=new Oo(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(oe.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(oe.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(oe.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(oe.MEDIA_ENDED,this.onMediaEnded,this),e.on(oe.ERROR,this.onError,this),e.on(oe.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(oe.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(oe.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(oe.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(oe.MEDIA_ENDED,this.onMediaEnded,this),e.off(oe.ERROR,this.onError,this),e.off(oe.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){lr(e,"play",this.onPlay),lr(e,"pause",this.onPause),lr(e,"seeking",this.onSeeking),lr(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;or(s,"seeking",this.onSeeking),or(s,"timeupdate",this.onTimeupdate),or(s,"play",this.onPlay),or(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=t=>t?e.getAssetPlayer(t.identifier):t,i=(t,i,n,a,o)=>{if(t){let l=t[i].start;const h=t.event;if(h){if("playout"===i||h.timelineOccupancy!==ko.Point){const e=s(n);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?r():e[a])-t.start}return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var s,i;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,r),d=null==(a=e.schedule.items)?void 0:a[h],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){const n=s(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=t;if("primary"!==r){const e=t-d[r].start;s=d.start+e}const i=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(i)e.timelinePos=s,e.checkBuffer();else{const e=d.event.assetList,s=t-(d[r]||d).start;for(let t=e.length;t--;){const i=e[t];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=t;break}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=s)}}},o=()=>{const s=e.effectivePlayingItem;if(e.isInterstitial(s))return s;const i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=t(),r=e.bufferingItem;var n;return r&&r===s&&(i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),s=e.effectivePlayingItem;return s&&s===t?i(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(t){const s=o(),i=e.effectivePlayingItem;i&&i===s&&a(t+i.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const s=null==(t=o())?void 0:t.event.assetList;return s?s.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const s=null==(t=o())?void 0:t.event;return s&&e.effectivePlayingAsset?s.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,s)=>{var i;if(0!==t&&"primary"!==s&&null!=(i=e.schedule)&&i.length){var r;const i=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[i];if(n)return t+(n[s].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,s=null==t?void 0:t.event;if(s&&!s.restrictions.skip){const i=e.findItemIndex(t);if(s.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&s)&&this.findItemIndex(t)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);const r=null==(t=i)?void 0:t.currentTime;return void 0!==r&&se(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Jt(s)}`),this.detachedData=s}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),h=`${e}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Jt(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=d&&r?r:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(c===r&&u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.log(Uo("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const t=this.timelinePos=s>0?s:0,i=e.findItemIndexAtTime(t);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Co(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,s){const i=Co(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=t+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.log(Uo("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(i)}}}else{if(e.appendInPlace){const t=e.assetList[i];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const t=s.findEventIndex(i),n=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?Fo(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,h=this.playingAsset,d=null==h?void 0:h.identifier,c=d?this.getAssetPlayer(d):null;if(c&&d&&(!this.eventItemsMatch(n,r)||void 0!==t&&d!==s.assetList[t].identifier)){var o;const t=s.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${xo(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(oe.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:e,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(d,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Fo(n)}`),s.hasPlayed=!0,this.hls.trigger(oe.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:e}),s.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const s=this.findItemIndex(r);this.advanceSchedule(s,e,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const s=t.interstitial,i=n.findEventIndex(s.identifier);(i<e||i>e+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const t=Co(r,(s=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,s);s=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Fo(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(oe.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=r.assetList[s];if(!d)return void this.advanceAfterAssetEnded(r,e,s||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){const e=r.assetList.length;this.warn(`asset ${s+1}/${e} player destroyed ${r}`),h=this.createAssetPlayer(r,d,s),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,s,t,e,o),this.shouldPlay&&Bo(h.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&Bo(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Fo(e)}`),null==(i=this.detachedData)||!i.mediaSource){let s=this.timelinePos;(s<e.start||s>=e.end)&&(s=this.getPrimaryResumption(e,t),this.log(Uo("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,e)}if(!s)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Fo(e)}`),this.hls.trigger(oe.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(s<e.fragmentStart||s>e.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return js.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Uo("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(oe.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=ye(ye({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=ye(ye({},this.altSelection),{},{audio:s}));const r=ye(ye({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=ye(ye({},this.altSelection),{},{subtitles:s}));const r=ye(ye({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=ts(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=ts(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const i=t[e];if(i.cue.post){var s;const e=this.schedule.findEventIndex(i.identifier),t=null==(s=this.schedule.items)?void 0:s[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(e&&i){return i[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,s)=>{e.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(t.identifier,null)});const s=e.end+.25,i=js.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${Fo(e)} (was ${Fo(t)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&(null==(t=this.schedule)||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=null==(t=this.schedule)?void 0:t.items;if(!s)return;const i=js.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(r),i=Math.min(s+1,t.length-1),n=t[i];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=i),this.isInterstitial(r)){const e=r.event;if(i-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const s=this.getAssetPlayer(e.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Fo(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,s)=>{const i=this.getAssetPlayer(e.identifier);i&&(s===t&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(oe.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=0===i&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(e,0,0,r,e.duration,s);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&i){for(let r=t;r<i;r++){const t=e.assetList[r],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,r)}const s=e.assetList[t];if(s){const e=this.getAssetPlayer(s.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,i,r,n){const a={parentIdentifier:e.identifier,identifier:Do(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=pe({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const s=t.duration;s&&e<s&&(h=e)}}const d=t.identifier,c=ye(ye({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=pe({},u,{contentId:Ro(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const f=new Mo(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[s]=t;let g=!0;const m=i=>{if(i.live){var r;const t=new Error(`Interstitials MUST be VOD assets ${e}`),i={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(i,e,n,s,t.message)}const n=i.edge-i.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${d}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(oe.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(oe.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(oe.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(e,t)=>{const s=this.getAssetPlayer(d);if(s&&t.tracks){s.off(oe.BUFFER_CODECS,p),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};f.on(oe.BUFFER_CODECS,p);f.on(oe.BUFFERED_TO_END,()=>{var s;const i=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${i}`),!i||!this.schedule)return;const r=this.schedule.findEventIndex(e.identifier),n=null==(s=this.schedule.items)?void 0:s[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)});const v=t=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return f.once(oe.MEDIA_ENDED,v(s)),f.once(oe.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(oe.ERROR,(t,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(d);if(i.details===ae.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(i,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${i.error} ${e}`)}),f.on(oe.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${d}`),i={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(i,e,this.schedule.findEventIndex(e.identifier),s,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xo(t)}`),this.hls.trigger(oe.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){const e=this.playerQueue[s];this.log(`clear ${e} toSegment: ${t?Fo(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xo(a)}`),this.hls.trigger(oe.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=null==(s=this.schedule.items)?void 0:s[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const d=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(d&&!ke(d,e.tracks)){const t=new Error(`Asset ${xo(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),s={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,a,i,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const s=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===ae.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?xo(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,d=pe({},e,{fatal:!1,errorAction:As(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(oe.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let g=i;g<t.assetList.length;g++)this.resetAssetPlayer(t.assetList[g].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===a?this.advanceAfterAssetEnded(t,s,i):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Fo(s)} error: ${e.error}`),-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);this.itemsMatch(s,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===i)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(r,t,h,o+h,s,e.URI),h+=s}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ae.ASSET_LIST_PARSING_ERROR:case ae.ASSET_LIST_LOAD_ERROR:case ae.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ae.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function jl(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(jl):Object.keys(e).reduce((t,s)=>(t[s]=jl(e[s]),t),{}):e}class Wl extends Vs{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;or(s,"playing",this.onMediaPlaying),or(s,"waiting",this.onMediaWaiting),or(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(lr(s,"playing",this.onMediaPlaying),lr(s,"waiting",this.onMediaWaiting),lr(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1})));if(!js.getBuffered(n).length)return void(this.nudgeRetry=0);const d=js.bufferInfo(n,e,0),c=d.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=zl(this.hls.inFlightFragments,e),s=d.len>2,i=!c||t||c-e>2&&!u.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(d.len>0)&&!c)return;const t=Math.max(c,d.start||0)-e,s=!(null==f||!f.live)?2*f.targetduration:2,i=Ql(e,u);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.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(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(oe.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const T=js.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(T,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(oe.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=js.bufferedInfo(js.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=js.timeRangesToArray(i),r=js.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=js.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Ql(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=js.bufferInfo(this.media,e,0);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=Ql(s,n);if(h||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,ue.MAIN),r=s.getFragAtPos(i,ue.MAIN);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Jt(e)})`);this.warn(i.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=null==(t=this.hls)?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=js.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&i.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>r.maxBufferHole){let t=!1;if(0===n){const e=s.getAppendedFrag(0,ue.MAIN);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(zl(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=Ql(i,s);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,i.currentTime=t,null==e||!e.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),i={type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?i.part=e:i.frag=e),this.hls.trigger(oe.ERROR,i)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}}function zl(e,t){const s=Xl(e.main);if(s&&s.start<=t)return s;const i=Xl(e.audio);return i&&i.start<=t?i:null}function Xl(e){if(!e)return null;switch(e.state){case cr:case dr:case yr:case Er:return null}return e.frag}function Ql(e,t){return t.getAppendedFrag(e,ue.MAIN)||t.getPartialFragment(e)}function Jl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Zl(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,Jt(r?ye({type:r},i):i))}return n}const eh=(()=>{const e=Jl();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class th{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(oe.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,!1===(null==(s=t.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&So(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return Eo(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Jl();if(n)for(let a=0;a<r.length;a++){const e=r[a].type;if(e===Jr.emsg&&!s||!i)continue;const t=Wr(r[a].data),o=r[a].pts;let l=o+r[a].duration;l>eh&&(l=eh);l-o<=0&&(l=o+.25);for(let s=0;s<t.length;s++){const i=t[s];if(!zr(i)){this.updateId3CueEnds(o,e);const t=Zl(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===t&&s.startTime<e&&s.endTime===eh&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===Jr.audioId3&&o:"video"===i?e=>e.type===Jr.emsg&&a:e=>e.type===Jr.audioId3&&o||e.type===Jr.emsg&&a,Lo(r,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Jl();if(s&&i&&!n){const{fragmentStart:t,fragmentEnd:i}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=i):a&&(r=this.assetCue=Zl(a,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(d).filter(e=>!h.includes(e));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach(e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(s){}}})}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&se(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=eh;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const e=h.reduce((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(s.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!si(l))continue;const h=o[l];if(h)!c||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=u):h.endTime=u;else if(a){let e=s.attr[l];ii(l)&&(e=we(e));const r=Zl(a,i,u,{key:l,data:e},Jr.dateRange);r&&(r.id=t,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}d[t]={cues:o,dateRange:s,durationKnown:c}}}}}class sh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ae.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class ih extends sa{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=_t(h,s)||void 0),d&&(d=e.videoCodec=function(e){const t=e.split(",");for(let s=0;s<t.length;s++){const e=t[s].split(".");e.length>2&&"avc1"===e[0]&&(t[s]=`avc1.${parseInt(e[1]).toString(16)}${("000"+parseInt(e[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!d),l||(l=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=t,S=`${`${y||"."}-`}${e.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",t.AUDIO),r[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[S]=s,i.push(s)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,i.push(t)}}),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new zt(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=Ut(e,[])}return t}isAudioSupported(e){return At(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return At(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let a=[],o=[],l=e;const h=(null==(n=t.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&(!!(r=t)&&Yt.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${Jt(t.levels.map(e=>e.attrs.CODECS).filter((e,t,s)=>s.indexOf(e)===t))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}}),void(h.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),rh(a)),t.subtitles&&(o=t.subtitles,rh(o));const d=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Yt.indexOf(e.videoRange)-Yt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=kt(e.videoCodec),i=kt(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=Dt(e.codecSet),i=Dt(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length))for(let v=0;v<d.length;v++)if(d[v].pathwayId===l[0].pathwayId){c=d[v];break}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===c){var u;this._firstLevel=v;const e=c.bitrate,t=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${e}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const s=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);s>t&&t===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=s)}break}const f=r&&!i,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:m&&!f&&a.some(e=>!!e.url)};h.end=performance.now(),this.hls.trigger(oe.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(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(oe.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===he&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===ue.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(oe.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Zi(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(oe.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(oe.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function rh(e){const t={};e.forEach(e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++})}function nh(){return self.SourceBuffer||self.WebKitSourceBuffer}function ah(){if(!Ie())return!1;const e=nh();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function oh(){if(!ah())return!1;const e=Ie();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(It(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(It(t,"audio"))))}class lh extends Lr{constructor(e,t,s){super(e,t,s,"stream-controller",ue.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!se(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,ue.MAIN,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=cr,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=dr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Sr:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=cr;break}if(this.hls.nextLoadLevel!==this.level){this.state=cr;break}break}case gr:this.checkRetryDate()}this.state===cr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(oe.BUFFER_EOS,e),void(this.state=yr)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===Sr||this.waitForLive(n))return this.level=r,this.state=Sr,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&Ye(u)&&this.fragmentTracker.getState(u)!==Ds){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Ge:Ke,t=(e===Ke?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,ue.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,ue.MAIN,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Rs||i===ks?Ye(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ue.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ur:case fr:case gr:case pr:case vr:this.state=cr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;or(s,"playing",this.onMediaPlaying),or(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(lr(s,"playing",this.onMediaPlaying),lr(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(oe.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const e=t.levels[r].audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=nh();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==cr)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Sr)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==fr&&this.state!==gr||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(oe.LEVEL_UPDATED,{details:a,level:n}),this.state===Sr){if(this.waitForCdnTuneIn(a))return;this.state=cr}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=js.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=js.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new ea(this.hls,ue.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new Ys(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const s=this.hls,i=0!==this.altAudio;if(as(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(oe.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(oe.AUDIO_TRACK_SWITCHED,t)}),void s.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(oe.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=as(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const a in s){const e=s[a];if("main"===e.id){if(r=a,i=e,"video"===a){const e=s[a];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===ue.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===vr&&(this.state=cr));const e=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),Ye(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&js.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=Er;else switch(t.details){case ae.FRAG_GAP:case ae.FRAG_PARSING_ERROR:case ae.FRAG_DECRYPT_ERROR:case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ue.MAIN,t);break;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:case ae.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Sr||(null==(s=t.context)?void 0:s.type)!==he||(this.state=cr);break;case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ae.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ae.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=cr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ge||!this.altAudio){const e=(t===Ke?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,ue.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=js.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=cr,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(oe.FRAG_LOADED,e),i.bitrateTest=!1}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=pr,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger(oe.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(se(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e},s.trigger(oe.INIT_PTS_FOUND,{frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Ge]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Ge,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(oe.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger(oe.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Ye(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==pr)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=Ct(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=ue.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=ue.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(oe.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(oe.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ue.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=cr}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(js.isBuffered(e,s)?t=this.getAppendedFrag(s):js.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger(oe.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger(oe.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return se(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(se(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?hs(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class hh extends Ee{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ae.KEY_LOAD_ERROR,s,i,r){return new Hs({type:ne.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Ye(e)||!Ye(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=vi(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=Ei(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=dh(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:s}=t;return r.key=s.decryptdata.key,{frag:e,keyInfo:s}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+Pe(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){const s=function(e){const t=[];return ct(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(s.length){let t=s[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${Pe(t)}`),Ai.setKeyIdForUri(e.decryptdata.uri,t)):(t=Ai.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Pe(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!Ye(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(t=>(e.mediaKeySessionContext=t,s))).catch(s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=new(0,s.loader)(s);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{const{frag:a,keyInfo:o}=s,l=dh(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,ae.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,ye({url:a.url,data:void 0},e)))},onTimeout:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=dh(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function dh(e){if(e.keyFormat!==pi.FAIRPLAY){const t=e.keyId;if(t)return Pe(t)}return e.uri}function ch(e){const{type:t}=e;switch(t){case de:return ue.AUDIO;case ce:return ue.SUBTITLE;default:return ue.MAIN}}function uh(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class fh{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:le,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:he,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:de,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ce,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[he];if(s){const e=s.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(s.abort(),delete this.loaders[he])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===le?s.manifestLoadPolicy.default:pe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),se(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===he&&null!==e.level?t=this.hls.levels[e.level].details:e.type===de&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ce&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=pe({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),_i.isMediaPlaylist(n)||s.type!==le?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=uh(e,s),o=_i.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,h.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];At(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,Lt.audio[i.substring(0,4)]=2,t.splice(n,1)):At(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,Lt.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=_i.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!h[0].audioCodec||h[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 ti({}),bitrate:0,url:""}))}r.trigger(oe.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=uh(e,s),d=se(o)?o:se(a)?a:0,c=ch(s),u=_i.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===le){const e={attrs:new ti({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+zi(u,0),n.trigger(oe.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.MANIFEST_PARSING_ERROR,fatal:t.type===le,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===he?n+=`: ${e.level} id: ${e.id}`:e.type!==de&&e.type!==ce||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ae.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case le:o=s?ae.MANIFEST_LOAD_TIMEOUT:ae.MANIFEST_LOAD_ERROR,l=!0;break;case he:o=s?ae.LEVEL_LOAD_TIMEOUT:ae.LEVEL_LOAD_ERROR,l=!1;break;case de:o=s?ae.AUDIO_TRACK_LOAD_TIMEOUT:ae.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ce:o=s?ae.SUBTITLE_TRACK_LOAD_TIMEOUT:ae.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:ne.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){const s=(null==t?void 0:t.url)||e.url;d.response=ye({url:s,data:void 0},i)}this.hls.trigger(oe.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=uh(t,i),g=ch(i);let m="number"==typeof i.level&&g===ue.MAIN?l:void 0;const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case le:case he:if(m)if(h){if(h!==a.levels[m]){const e=a.levels.indexOf(h);e>-1&&(m=e)}}else m=0;a.trigger(oe.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:m||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===le});break;case de:a.trigger(oe.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case ce:a.trigger(oe.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}}}class gh{static get version(){return Pr}static isMSESupported(){return ah()}static isSupported(){return oh()}static getMediaSource(){return Ie()}static get Events(){return oe}static get MetadataSchema(){return Jr}static get ErrorTypes(){return ne}static get ErrorDetails(){return ae}static get DefaultConfig(){return gh.defaultConfig?gh.defaultConfig:ql}static set DefaultConfig(e){gh.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Dr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,s){const i=Le();if("object"==typeof console&&!0===e||"object"==typeof e){const n=["debug","log","info","warn","error"];n.forEach(t=>{i[t]=be(t,e,s)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(r){return Le()}n.forEach(t=>{Ae[t]=be(t,e)})}else pe(Ae,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=function(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=jl(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Jt(t[n])}`)}),ye(ye({},i),t)}(gh.DefaultConfig,e,t);this.userConfig=e,s.progressive&&function(e,t){const s=e.loader;s!==Gl&&s!==Yl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):Ul()&&(e.loader=Gl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),h=this.abrController=new i(this),d=new Ps(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,gh):null,f=this.bufferController=new r(this,d),g=this.capLevelController=new n(this),m=new o(this),p=new fh(this),v=s.contentSteeringController,y=v?new v(this):null,E=this.levelController=new ih(this,y),T=new th(this),S=new hh(this.config,this.logger),L=this.streamController=new lh(this,d,S),b=this.gapController=new Wl(this,d);g.setStreamController(L),m.setStreamController(L);const A=[p,E,L];u&&A.splice(1,0,u),y&&A.splice(1,0,y),this.networkControllers=A;const R=[h,f,b,g,m,T,d];this.audioTrackController=this.createController(s.audioTrackController,A);const I=s.audioStreamController;I&&A.push(this.audioStreamController=new I(this,d,S)),this.subtitleTrackController=this.createController(s.subtitleTrackController,A);const k=s.subtitleStreamController;k&&A.push(this.subtititleStreamController=new k(this,d,S)),this.createController(s.timelineController,R),S.emeController=this.emeController=this.createController(s.emeController,R),this.cmcdController=this.createController(s.cmcdController,R),this.latencyController=this.createController(sh,R),this.coreComponents=R,A.push(l);const D=l.onErrorOut;"function"==typeof D&&this.on(oe.ERROR,D,l),this.on(oe.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const t=e===oe.ERROR;this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:t,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(oe.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(oe.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(oe.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(oe.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Ue.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(oe.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ue.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ue.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ue.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Vt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let r=i;r--;){const t=e[r].attrs["HDCP-LEVEL"];if(t&&t<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Gt(e,es(t),navigator.mediaCapabilities)}}gh.defaultConfig=void 0;const mh=Object.freeze(Object.defineProperty({__proto__:null,AbrController:os,AttrList:ti,AudioStreamController:ta,AudioTrackController:aa,BasePlaylistController:sa,BaseSegment:Ve,BaseStreamController:Lr,BufferController:ca,CMCDController:lo,CapLevelController:ga,ChunkMetadata:Ys,ContentSteeringController:ho,Cues:Bl,DateRange:ri,EMEController:fo,ErrorActionFlags:Ls,ErrorController:bs,ErrorDetails:ae,ErrorTypes:ne,Events:oe,FPSController:yo,FetchLoader:Gl,Fragment:qe,Hls:gh,HlsSkip:qt,HlsUrlParameters:Wt,KeySystemFormats:pi,KeySystems:mi,Level:zt,LevelDetails:ni,LevelKey:Ai,LoadStats:$e,M3U8Parser:_i,MetadataSchema:Jr,NetworkErrorAction:Ss,Part:je,PlaylistLevelType:ue,SubtitleStreamController:$o,SubtitleTrackController:Ao,TimelineController:xl,XhrLoader:Yl,default:gh,fetchSupported:Ul,getMediaSource:Ie,isMSESupported:ah,isSupported:oh,requestMediaKeySystemAccess:Ti},Symbol.toStringTag,{value:"Module"}));e.applyContainerStyles=z,e.aspectRatioToPercent=W,e.create=ee,e.createEmbedPlayer=X,e.default=te,e.initAll=Z,e.initElement=Q,e.parseDataAttributes=j,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ScarlettPlayer={})}(this,function(e){"use strict";class t{constructor(e){this.subscribers=new Set,this.value=e}get(){return this.value}set(e){Object.is(this.value,e)||(this.value=e,this.notify())}update(e){this.set(e(this.value))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){this.subscribers.forEach(e=>{try{e()}catch(t){console.error("[Scarlett Player] Error in signal subscriber:",t)}})}destroy(){this.subscribers.clear()}getSubscriberCount(){return this.subscribers.size}}function s(e){return new t(e)}const i={playbackState:"idle",playing:!1,paused:!0,ended:!1,buffering:!1,waiting:!1,seeking:!1,currentTime:0,duration:NaN,buffered:null,bufferedAmount:0,mediaType:"unknown",source:null,title:"",poster:"",volume:1,muted:!1,playbackRate:1,fullscreen:!1,pip:!1,controlsVisible:!0,qualities:[],currentQuality:null,audioTracks:[],currentAudioTrack:null,textTracks:[],currentTextTrack:null,live:!1,liveEdge:!0,seekableRange:null,liveLatency:0,lowLatencyMode:!1,chapters:[],currentChapter:null,error:null,bandwidth:0,autoplay:!1,loop:!1,airplayAvailable:!1,airplayActive:!1,chromecastAvailable:!1,chromecastActive:!1,interacting:!1,hovering:!1,focused:!1};class r{constructor(e){this.signals=new Map,this.changeSubscribers=new Set,this.initializeSignals(e)}initializeSignals(e){const t={...i,...e};for(const[i,r]of Object.entries(t)){const e=i,t=s(r);t.subscribe(()=>{this.notifyChangeSubscribers(e)}),this.signals.set(e,t)}}get(e){const t=this.signals.get(e);if(!t)throw new Error(`[StateManager] Unknown state key: ${e}`);return t}getValue(e){return this.get(e).get()}set(e,t){this.get(e).set(t)}update(e){for(const[t,s]of Object.entries(e)){const e=t;this.signals.has(e)&&this.set(e,s)}}subscribeToKey(e,t){const s=this.get(e);return s.subscribe(()=>{t(s.get())})}subscribe(e){return this.changeSubscribers.add(e),()=>this.changeSubscribers.delete(e)}notifyChangeSubscribers(e){const t=this.get(e).get(),s={key:e,value:t,previousValue:t};this.changeSubscribers.forEach(e=>{try{e(s)}catch(t){console.error("[StateManager] Error in change subscriber:",t)}})}reset(){this.update(i)}resetKey(e){const t=i[e];this.set(e,t)}snapshot(){const e={};for(const[t,s]of this.signals)e[t]=s.get();return Object.freeze(e)}getSubscriberCount(e){return this.signals.get(e)?.getSubscriberCount()??0}destroy(){this.signals.forEach(e=>e.destroy()),this.signals.clear(),this.changeSubscribers.clear()}}const n={maxListeners:100,async:!1,interceptors:!0};class a{constructor(e){this.listeners=new Map,this.onceListeners=new Map,this.interceptors=new Map,this.options={...n,...e}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);return this.listeners.get(e).add(t),this.checkMaxListeners(e),()=>this.off(e,t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,new Set);const s=this.onceListeners.get(e);return s.add(t),this.listeners.has(e)||this.listeners.set(e,new Set),()=>{s.delete(t)}}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e));const i=this.onceListeners.get(e);i&&(i.delete(t),0===i.size&&this.onceListeners.delete(e))}emit(e,t){const s=this.runInterceptors(e,t);if(null===s)return;const i=this.listeners.get(e);if(i){Array.from(i).forEach(e=>{this.safeCallHandler(e,s)})}const r=this.onceListeners.get(e);if(r){Array.from(r).forEach(e=>{this.safeCallHandler(e,s)}),this.onceListeners.delete(e)}}async emitAsync(e,t){const s=await this.runInterceptorsAsync(e,t);if(null===s)return;const i=this.listeners.get(e);if(i){const e=Array.from(i).map(e=>this.safeCallHandlerAsync(e,s));await Promise.all(e)}const r=this.onceListeners.get(e);if(r){const t=Array.from(r).map(e=>this.safeCallHandlerAsync(e,s));await Promise.all(t),this.onceListeners.delete(e)}}intercept(e,t){if(!this.options.interceptors)return()=>{};this.interceptors.has(e)||this.interceptors.set(e,new Set);const s=this.interceptors.get(e);return s.add(t),()=>{s.delete(t),0===s.size&&this.interceptors.delete(e)}}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){return(this.listeners.get(e)?.size??0)+(this.onceListeners.get(e)?.size??0)}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.interceptors.clear()}runInterceptors(e,t){if(!this.options.interceptors)return t;const s=this.interceptors.get(e);if(!s||0===s.size)return t;let i=t;for(const n of s)try{if(i=n(i),null===i)return null}catch(r){console.error("[EventBus] Error in interceptor:",r)}return i}async runInterceptorsAsync(e,t){if(!this.options.interceptors)return t;const s=this.interceptors.get(e);if(!s||0===s.size)return t;let i=t;for(const n of s)try{const e=n(i);if(i=e instanceof Promise?await e:e,null===i)return null}catch(r){console.error("[EventBus] Error in interceptor:",r)}return i}safeCallHandler(e,t){try{e(t)}catch(s){console.error("[EventBus] Error in event handler:",s)}}async safeCallHandlerAsync(e,t){try{const s=e(t);s instanceof Promise&&await s}catch(s){console.error("[EventBus] Error in event handler:",s)}}checkMaxListeners(e){const t=this.listenerCount(e);t>this.options.maxListeners&&console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) exceeded for event: ${e}. Current count: ${t}. This may indicate a memory leak.`)}}const o=["debug","info","warn","error"],l=e=>{const t=`${e.scope?`[${e.scope}]`:"[ScarlettPlayer]"} ${e.message}`,s=e.metadata??"";switch(e.level){case"debug":console.debug(t,s);break;case"info":console.info(t,s);break;case"warn":console.warn(t,s);break;case"error":console.error(t,s)}};let h=class e{constructor(e){this.level=e?.level??"warn",this.scope=e?.scope,this.enabled=e?.enabled??!0,this.handlers=e?.handlers??[l]}child(t){return new e({level:this.level,scope:this.scope?`${this.scope}:${t}`:t,enabled:this.enabled,handlers:this.handlers})}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}setEnabled(e){this.enabled=e}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);-1!==t&&this.handlers.splice(t,1)}log(e,t,s){if(!this.enabled||!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),scope:this.scope,metadata:s};for(const n of this.handlers)try{n(i)}catch(r){console.error("[Logger] Handler error:",r)}}shouldLog(e){return o.indexOf(e)>=o.indexOf(this.level)}};var d=(e=>(e.SOURCE_NOT_SUPPORTED="SOURCE_NOT_SUPPORTED",e.SOURCE_LOAD_FAILED="SOURCE_LOAD_FAILED",e.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",e.PROVIDER_SETUP_FAILED="PROVIDER_SETUP_FAILED",e.PLUGIN_SETUP_FAILED="PLUGIN_SETUP_FAILED",e.PLUGIN_NOT_FOUND="PLUGIN_NOT_FOUND",e.PLAYBACK_FAILED="PLAYBACK_FAILED",e.MEDIA_DECODE_ERROR="MEDIA_DECODE_ERROR",e.MEDIA_NETWORK_ERROR="MEDIA_NETWORK_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e))(d||{});class c{constructor(e,t,s){this.errors=[],this.eventBus=e,this.logger=t,this.maxHistory=s?.maxHistory??10}handle(e,t){const s=this.normalizeError(e,t);return this.addToHistory(s),this.logError(s),this.eventBus.emit("error",s),s}throw(e,t,s){const i={code:e,message:t,fatal:s?.fatal??this.isFatalCode(e),timestamp:Date.now(),context:s?.context,originalError:s?.originalError};return this.handle(i,s?.context)}getHistory(){return[...this.errors]}getLastError(){return this.errors[this.errors.length-1]??null}clearHistory(){this.errors=[]}hasFatalError(){return this.errors.some(e=>e.fatal)}normalizeError(e,t){return this.isPlayerError(e)?{...e,context:{...e.context,...t}}:{code:this.getErrorCode(e),message:e.message,fatal:this.isFatal(e),timestamp:Date.now(),context:t,originalError:e}}getErrorCode(e){const t=e.message.toLowerCase();return t.includes("network")?"MEDIA_NETWORK_ERROR":t.includes("decode")?"MEDIA_DECODE_ERROR":t.includes("source")?"SOURCE_LOAD_FAILED":t.includes("plugin")?"PLUGIN_SETUP_FAILED":t.includes("provider")?"PROVIDER_SETUP_FAILED":"UNKNOWN_ERROR"}isFatal(e){return this.isFatalCode(this.getErrorCode(e))}isFatalCode(e){return["SOURCE_NOT_SUPPORTED","PROVIDER_NOT_FOUND","MEDIA_DECODE_ERROR"].includes(e)}isPlayerError(e){return"object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"fatal"in e&&"timestamp"in e}addToHistory(e){this.errors.push(e),this.errors.length>this.maxHistory&&this.errors.shift()}logError(e){const t=`[${e.code}] ${e.message}`;e.fatal?this.logger.error(t,{code:e.code,context:e.context}):this.logger.warn(t,{code:e.code,context:e.context})}}class u{constructor(e,t){this.cleanupFns=[],this.pluginId=e,this.stateManager=t.stateManager,this.eventBus=t.eventBus,this.container=t.container,this.getPluginFn=t.getPlugin,this.logger={debug:(s,i)=>t.logger.debug(`[${e}] ${s}`,i),info:(s,i)=>t.logger.info(`[${e}] ${s}`,i),warn:(s,i)=>t.logger.warn(`[${e}] ${s}`,i),error:(s,i)=>t.logger.error(`[${e}] ${s}`,i)}}getState(e){return this.stateManager.getValue(e)}setState(e,t){this.stateManager.set(e,t)}on(e,t){return this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}emit(e,t){this.eventBus.emit(e,t)}getPlugin(e){return this.getPluginFn(e)}onDestroy(e){this.cleanupFns.push(e)}subscribeToState(e){return this.stateManager.subscribe(e)}runCleanups(){for(const t of this.cleanupFns)try{t()}catch(e){this.logger.error("Cleanup function failed",{error:e})}this.cleanupFns=[]}getCleanupFns(){return this.cleanupFns}}class f{constructor(e,t,s,i){this.plugins=new Map,this.eventBus=e,this.stateManager=t,this.logger=s,this.container=i.container}register(e,t){if(this.plugins.has(e.id))throw new Error(`Plugin "${e.id}" is already registered`);this.validatePlugin(e);const s=new u(e.id,{stateManager:this.stateManager,eventBus:this.eventBus,logger:this.logger,container:this.container,getPlugin:e=>this.getReadyPlugin(e)});this.plugins.set(e.id,{plugin:e,state:"registered",config:t,cleanupFns:[],api:s}),this.logger.info(`Plugin registered: ${e.id}`),this.eventBus.emit("plugin:registered",{name:e.id,type:e.type})}async unregister(e){const t=this.plugins.get(e);t&&("ready"===t.state&&await this.destroyPlugin(e),this.plugins.delete(e),this.logger.info(`Plugin unregistered: ${e}`))}async initAll(){const e=this.resolveDependencyOrder();for(const t of e)await this.initPlugin(t)}async initPlugin(e){const t=this.plugins.get(e);if(!t)throw new Error(`Plugin "${e}" not found`);if("ready"!==t.state){if("initializing"===t.state)throw new Error(`Plugin "${e}" is already initializing (possible circular dependency)`);for(const s of t.plugin.dependencies||[]){const t=this.plugins.get(s);if(!t)throw new Error(`Plugin "${e}" depends on missing plugin "${s}"`);"ready"!==t.state&&await this.initPlugin(s)}try{if(t.state="initializing",t.plugin.onStateChange){const e=this.stateManager.subscribe(t.plugin.onStateChange.bind(t.plugin));t.api.onDestroy(e)}if(t.plugin.onError){const e=this.eventBus.on("error",e=>{t.plugin.onError?.(e.originalError||new Error(e.message))});t.api.onDestroy(e)}await t.plugin.init(t.api,t.config),t.state="ready",this.logger.info(`Plugin ready: ${e}`),this.eventBus.emit("plugin:active",{name:e})}catch(s){throw t.state="error",t.error=s,this.logger.error(`Plugin init failed: ${e}`,{error:s}),this.eventBus.emit("plugin:error",{name:e,error:s}),s}}}async destroyAll(){const e=this.resolveDependencyOrder().reverse();for(const t of e)await this.destroyPlugin(t)}async destroyPlugin(e){const t=this.plugins.get(e);if(t&&"ready"===t.state)try{await t.plugin.destroy(),t.api.runCleanups(),t.state="registered",this.logger.info(`Plugin destroyed: ${e}`),this.eventBus.emit("plugin:destroyed",{name:e})}catch(s){this.logger.error(`Plugin destroy failed: ${e}`,{error:s}),t.state="registered"}}getPlugin(e){const t=this.plugins.get(e);return t?t.plugin:null}getReadyPlugin(e){const t=this.plugins.get(e);return"ready"===t?.state?t.plugin:null}hasPlugin(e){return this.plugins.has(e)}getPluginState(e){return this.plugins.get(e)?.state??null}getPluginIds(){return Array.from(this.plugins.keys())}getReadyPlugins(){return Array.from(this.plugins.values()).filter(e=>"ready"===e.state).map(e=>e.plugin)}getPluginsByType(e){return Array.from(this.plugins.values()).filter(t=>t.plugin.type===e).map(e=>e.plugin)}selectProvider(e){const t=this.getPluginsByType("provider");for(const s of t){const t=s.canPlay;if("function"==typeof t&&t(e))return s}return null}resolveDependencyOrder(){const e=new Set,t=new Set,s=[],i=(r,n=[])=>{if(e.has(r))return;if(t.has(r)){const e=[...n,r].join(" -> ");throw new Error(`Circular dependency detected: ${e}`)}const a=this.plugins.get(r);if(a){t.add(r);for(const e of a.plugin.dependencies||[])this.plugins.has(e)&&i(e,[...n,r]);t.delete(r),e.add(r),s.push(r)}};for(const r of this.plugins.keys())i(r);return s}validatePlugin(e){if(!e.id||"string"!=typeof e.id)throw new Error("Plugin must have a valid id");if(!e.name||"string"!=typeof e.name)throw new Error(`Plugin "${e.id}" must have a valid name`);if(!e.version||"string"!=typeof e.version)throw new Error(`Plugin "${e.id}" must have a valid version`);if(!e.type||"string"!=typeof e.type)throw new Error(`Plugin "${e.id}" must have a valid type`);if("function"!=typeof e.init)throw new Error(`Plugin "${e.id}" must have an init() method`);if("function"!=typeof e.destroy)throw new Error(`Plugin "${e.id}" must have a destroy() method`)}}class g{constructor(e){if(this._currentProvider=null,this.destroyed=!1,this.seekingWhilePlaying=!1,this.seekResumeTimeout=null,"string"==typeof e.container){const t=document.querySelector(e.container);if(!(t&&t instanceof HTMLElement))throw new Error(`ScarlettPlayer: container not found: ${e.container}`);this.container=t}else{if(!(e.container instanceof HTMLElement))throw new Error("ScarlettPlayer requires a valid HTMLElement container or CSS selector");this.container=e.container}if(this.initialSrc=e.src,this.eventBus=new a,this.stateManager=new r({autoplay:e.autoplay??!1,loop:e.loop??!1,volume:e.volume??1,muted:e.muted??!1,poster:e.poster??""}),this.logger=new h({level:e.logLevel??"warn",scope:"ScarlettPlayer"}),this.errorHandler=new c(this.eventBus,this.logger),this.pluginManager=new f(this.eventBus,this.stateManager,this.logger,{container:this.container}),e.plugins)for(const t of e.plugins)this.pluginManager.register(t);this.logger.info("ScarlettPlayer initialized",{autoplay:e.autoplay,plugins:e.plugins?.length??0}),this.eventBus.emit("player:ready",void 0)}async init(){this.checkDestroyed();for(const[e,t]of this.pluginManager.plugins)"provider"!==t.plugin.type&&"registered"===t.state&&await this.pluginManager.initPlugin(e);return this.initialSrc&&await this.load(this.initialSrc),Promise.resolve()}async load(e){this.checkDestroyed();try{if(this.logger.info("Loading source",{source:e}),this.stateManager.update({playing:!1,paused:!0,ended:!1,buffering:!0,currentTime:0,duration:0,bufferedAmount:0,playbackState:"loading"}),this._currentProvider){const e=this._currentProvider.id;this.logger.info("Destroying previous provider",{provider:e}),await this.pluginManager.destroyPlugin(e),this._currentProvider=null}const t=this.pluginManager.selectProvider(e);if(!t)return void this.errorHandler.throw(d.PROVIDER_NOT_FOUND,`No provider found for source: ${e}`,{fatal:!0,context:{source:e}});this._currentProvider=t,this.logger.info("Provider selected",{provider:t.id}),await this.pluginManager.initPlugin(t.id),this.stateManager.set("source",{src:e,type:this.detectMimeType(e)}),"function"==typeof t.loadSource&&await t.loadSource(e),this.stateManager.getValue("autoplay")&&await this.play()}catch(t){this.errorHandler.handle(t,{operation:"load",source:e})}}async play(){this.checkDestroyed();try{this.logger.debug("Play requested"),this.eventBus.emit("playback:play",void 0)}catch(e){this.errorHandler.handle(e,{operation:"play"})}}pause(){this.checkDestroyed();try{this.logger.debug("Pause requested"),this.seekingWhilePlaying=!1,null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:pause",void 0)}catch(e){this.errorHandler.handle(e,{operation:"pause"})}}seek(e){this.checkDestroyed();try{this.logger.debug("Seek requested",{time:e});this.stateManager.getValue("playing")&&(this.seekingWhilePlaying=!0),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("playback:seeking",{time:e}),this.stateManager.set("currentTime",e),this.seekingWhilePlaying&&(this.seekResumeTimeout=setTimeout(()=>{this.seekingWhilePlaying&&this.stateManager.getValue("playing")&&(this.logger.debug("Resuming playback after seek"),this.seekingWhilePlaying=!1,this.eventBus.emit("playback:play",void 0)),this.seekResumeTimeout=null},300))}catch(t){this.errorHandler.handle(t,{operation:"seek",time:e})}}setVolume(e){this.checkDestroyed();const t=Math.max(0,Math.min(1,e));this.stateManager.set("volume",t),this.eventBus.emit("volume:change",{volume:t,muted:this.stateManager.getValue("muted")})}setMuted(e){this.checkDestroyed(),this.stateManager.set("muted",e),this.eventBus.emit("volume:mute",{muted:e})}setPlaybackRate(e){this.checkDestroyed(),this.stateManager.set("playbackRate",e),this.eventBus.emit("playback:ratechange",{rate:e})}setAutoplay(e){this.checkDestroyed(),this.stateManager.set("autoplay",e),this.logger.debug("Autoplay set",{autoplay:e})}on(e,t){return this.checkDestroyed(),this.eventBus.on(e,t)}once(e,t){return this.checkDestroyed(),this.eventBus.once(e,t)}getPlugin(e){return this.checkDestroyed(),this.pluginManager.getPlugin(e)}registerPlugin(e){this.checkDestroyed(),this.pluginManager.register(e)}getState(){return this.checkDestroyed(),this.stateManager.snapshot()}getQualities(){if(this.checkDestroyed(),!this._currentProvider)return[];const e=this._currentProvider;return"function"==typeof e.getLevels?e.getLevels():[]}setQuality(e){if(this.checkDestroyed(),!this._currentProvider)return void this.logger.warn("No provider available for quality change");const t=this._currentProvider;"function"==typeof t.setLevel&&(t.setLevel(e),this.eventBus.emit("quality:change",{quality:-1===e?"auto":`level-${e}`,auto:-1===e}))}getCurrentQuality(){if(this.checkDestroyed(),!this._currentProvider)return-1;const e=this._currentProvider;return"function"==typeof e.getCurrentLevel?e.getCurrentLevel():-1}async requestFullscreen(){this.checkDestroyed();try{this.container.requestFullscreen?await this.container.requestFullscreen():this.container.webkitRequestFullscreen&&await this.container.webkitRequestFullscreen(),this.stateManager.set("fullscreen",!0),this.eventBus.emit("fullscreen:change",{fullscreen:!0})}catch(e){this.logger.error("Fullscreen request failed",{error:e})}}async exitFullscreen(){this.checkDestroyed();try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen&&await document.webkitExitFullscreen(),this.stateManager.set("fullscreen",!1),this.eventBus.emit("fullscreen:change",{fullscreen:!1})}catch(e){this.logger.error("Exit fullscreen failed",{error:e})}}async toggleFullscreen(){this.fullscreen?await this.exitFullscreen():await this.requestFullscreen()}requestAirPlay(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.showPicker?e.showPicker():this.logger.warn("AirPlay plugin not available")}async requestChromecast(){this.checkDestroyed();const e=this.pluginManager.getPlugin("chromecast");e&&"function"==typeof e.requestSession?await e.requestSession():this.logger.warn("Chromecast plugin not available")}stopCasting(){this.checkDestroyed();const e=this.pluginManager.getPlugin("airplay");e&&"function"==typeof e.stop&&e.stop();const t=this.pluginManager.getPlugin("chromecast");t&&"function"==typeof t.stopSession&&t.stopSession()}seekToLive(){this.checkDestroyed();if(!this.stateManager.getValue("live"))return void this.logger.warn("Not a live stream");if(this._currentProvider){const e=this._currentProvider;if("function"==typeof e.getLiveInfo){const t=e.getLiveInfo();if(void 0!==t?.liveSyncPosition)return void this.seek(t.liveSyncPosition)}}const e=this.stateManager.getValue("duration");e>0&&this.seek(e)}destroy(){this.destroyed||(this.logger.info("Destroying player"),null!==this.seekResumeTimeout&&(clearTimeout(this.seekResumeTimeout),this.seekResumeTimeout=null),this.eventBus.emit("player:destroy",void 0),this.pluginManager.destroyAll(),this.eventBus.destroy(),this.stateManager.destroy(),this.destroyed=!0,this.logger.info("Player destroyed"))}get playing(){return this.stateManager.getValue("playing")}get paused(){return this.stateManager.getValue("paused")}get currentTime(){return this.stateManager.getValue("currentTime")}get duration(){return this.stateManager.getValue("duration")}get volume(){return this.stateManager.getValue("volume")}get muted(){return this.stateManager.getValue("muted")}get playbackRate(){return this.stateManager.getValue("playbackRate")}get bufferedAmount(){return this.stateManager.getValue("bufferedAmount")}get currentProvider(){return this._currentProvider}get fullscreen(){return this.stateManager.getValue("fullscreen")}get live(){return this.stateManager.getValue("live")}get autoplay(){return this.stateManager.getValue("autoplay")}checkDestroyed(){if(this.destroyed)throw new Error("Cannot call methods on destroyed player")}detectMimeType(e){const t=e.split(".").pop()?.toLowerCase();switch(t){case"m3u8":return"application/x-mpegURL";case"mpd":return"application/dash+xml";case"mp4":default:return"video/mp4";case"webm":return"video/webm";case"ogg":return"video/ogg"}}}function m(e){if(e.name)return e.name;if(e.height){const t={2160:"4K",1440:"1440p",1080:"1080p",720:"720p",480:"480p",360:"360p",240:"240p",144:"144p"},s=Object.keys(t).map(Number).sort((t,s)=>Math.abs(t-e.height)-Math.abs(s-e.height))[0];return Math.abs(s-e.height)<=20?t[s]:`${e.height}p`}return e.bitrate?function(e){if(e>=1e6)return`${(e/1e6).toFixed(1)} Mbps`;if(e>=1e3)return`${Math.round(e/1e3)} Kbps`;return`${e} bps`}(e.bitrate):"Unknown"}var p="networkError",v="mediaError",y="muxError";function E(e){switch(e){case p:return"network";case v:return"media";case y:return"mux";default:return"other"}}function T(e,t,s){const i=[],r=(t,s)=>{e.on(t,s),i.push({event:t,handler:s})};return r("hlsManifestParsed",(i,r)=>{t.logger.debug("HLS manifest parsed",{levels:r.levels.length});const n=r.levels.map((t,s)=>({id:`level-${s}`,label:m(t),width:t.width,height:t.height,bitrate:t.bitrate,active:s===e.currentLevel}));t.setState("qualities",n),t.emit("quality:levels",{levels:n.map(e=>({id:e.id,label:e.label}))}),s.onManifestParsed?.(r.levels)}),r("hlsLevelSwitched",(i,r)=>{const n=e.levels[r.level],a=s.getIsAutoQuality?.()??e.autoLevelEnabled;if(t.logger.debug("HLS level switched",{level:r.level,height:n?.height,auto:a}),n){const e=a?`Auto (${m(n)})`:m(n);t.setState("currentQuality",{id:a?"auto":`level-${r.level}`,label:e,width:n.width,height:n.height,bitrate:n.bitrate,active:!0})}t.emit("quality:change",{quality:n?m(n):"auto",auto:a}),s.onLevelSwitched?.(r.level)}),r("hlsFragBuffered",()=>{t.setState("buffering",!1),s.onBufferUpdate?.()}),r("hlsFragLoading",()=>{t.setState("buffering",!0)}),r("hlsLevelLoaded",(e,i)=>{void 0!==i.details?.live&&(t.setState("live",i.details.live),s.onLiveUpdate?.())}),r("hlsError",(e,i)=>{const r=function(e){return{type:E(e.type),details:e.details||"Unknown error",fatal:e.fatal||!1,url:e.url,reason:e.reason,response:e.response}}(i);t.logger.warn("HLS error",{error:r}),s.onError?.(r)}),()=>{for(const{event:t,handler:s}of i)e.off(t,s);i.length=0}}function S(e,t){const s=[],i=(t,i)=>{e.addEventListener(t,i),s.push({event:t,handler:i})};i("playing",()=>{t.setState("playing",!0),t.setState("paused",!1),t.setState("playbackState","playing")}),i("pause",()=>{t.setState("playing",!1),t.setState("paused",!0),t.setState("playbackState","paused")}),i("ended",()=>{t.setState("playing",!1),t.setState("ended",!0),t.setState("playbackState","ended"),t.emit("playback:ended",void 0)}),i("timeupdate",()=>{t.setState("currentTime",e.currentTime),t.emit("playback:timeupdate",{currentTime:e.currentTime})}),i("durationchange",()=>{t.setState("duration",e.duration||0),t.emit("media:loadedmetadata",{duration:e.duration||0})}),i("waiting",()=>{t.setState("waiting",!0),t.setState("buffering",!0),t.emit("media:waiting",void 0)}),i("canplay",()=>{t.setState("waiting",!1),t.setState("playbackState","ready"),t.emit("media:canplay",void 0)}),i("canplaythrough",()=>{t.setState("buffering",!1),t.emit("media:canplaythrough",void 0)}),i("progress",()=>{if(e.buffered.length>0){const s=e.buffered.end(e.buffered.length-1),i=e.duration>0?s/e.duration:0;t.setState("bufferedAmount",i),t.setState("buffered",e.buffered),t.emit("media:progress",{buffered:i})}}),i("seeking",()=>{t.setState("seeking",!0)}),i("seeked",()=>{t.setState("seeking",!1),t.emit("playback:seeked",{time:e.currentTime})}),i("volumechange",()=>{t.setState("volume",e.volume),t.setState("muted",e.muted),t.emit("volume:change",{volume:e.volume,muted:e.muted})}),i("ratechange",()=>{t.setState("playbackRate",e.playbackRate),t.emit("playback:ratechange",{rate:e.playbackRate})}),i("loadedmetadata",()=>{t.setState("duration",e.duration),t.setState("mediaType",e.videoWidth>0?"video":"audio")}),i("error",()=>{const s=e.error;s&&(t.logger.error("Video element error",{code:s.code,message:s.message}),t.emit("media:error",{error:new Error(s.message||"Video playback error")}))}),i("enterpictureinpicture",()=>{t.setState("pip",!0),t.logger.debug("PiP: entered (standard)")}),i("leavepictureinpicture",()=>{t.setState("pip",!1),t.logger.debug("PiP: exited (standard)"),e.paused&&!t.getState("playing")||e.play().catch(()=>{})});const r=e;return"webkitPresentationMode"in e&&i("webkitpresentationmodechanged",()=>{const s=r.webkitPresentationMode,i="picture-in-picture"===s;t.setState("pip",i),t.logger.debug(`PiP: mode changed to ${s} (webkit)`),"inline"===s&&e.paused&&e.play().catch(()=>{})}),()=>{for(const{event:t,handler:i}of s)e.removeEventListener(t,i);s.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 I={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 k(e){const t={...I,...e};let s=null,i=null,r=null,n=!1,a=null,o=null,l=null,h=!0,d=0,c=0,u=null,f=0,g=0;const p=()=>{if(r)return r;const e=s?.container.querySelector("video");if(e)return r=e,r;r=document.createElement("video"),r.style.cssText="width:100%;height:100%;display:block;object-fit:contain;background:#000",r.preload="metadata",r.controls=!1,r.playsInline=!0;const t=s?.getState("poster");return t&&(r.poster=t),s?.container.appendChild(r),r},v=()=>{o?.(),o=null,l?.(),l=null,u&&(clearTimeout(u),u=null),i&&(i.destroy(),i=null),a=null,n=!1,h=!0,d=0,c=0,f=0,g=0},y=e=>{const s=t.retryDelayMs??1e3,i=t.retryBackoffFactor??2;return s*Math.pow(i,e)},E=(e,t)=>{const i=t?`HLS error: ${e.details} (max retries exceeded)`:`HLS error: ${e.details}`;s?.logger.error(i,{type:e.type,details:e.details}),s?.setState("playbackState","error"),s?.setState("buffering",!1),s?.emit("error",{code:"MEDIA_ERROR",message:i,fatal:!0,timestamp:Date.now()})},k=e=>{if(!L||!i)return;const r=Date.now();if(r-g>5e3?(f=1,g=r):f++,f>=10)return s?.logger.error(`Too many errors (${f} in 5000ms), giving up`),E(e,!0),o?.(),o=null,i.destroy(),void(i=null);if(e.fatal)switch(s?.logger.error("Fatal HLS error",{type:e.type,details:e.details}),e.type){case"network":{const r=t.maxNetworkRetries??3;if(d>=r)return s?.logger.error(`Network error recovery failed after ${d} attempts`),void E(e,!0);d++;const n=y(d-1);s?.logger.info(`Attempting network error recovery (attempt ${d}/${r}) in ${n}ms`),s?.emit("error:network",{error:new Error(e.details)}),u&&clearTimeout(u),u=setTimeout(()=>{i&&i.startLoad()},n);break}case"media":{const r=t.maxMediaRetries??2;if(c>=r)return s?.logger.error(`Media error recovery failed after ${c} attempts`),void E(e,!0);c++;const n=y(c-1);s?.logger.info(`Attempting media error recovery (attempt ${c}/${r}) in ${n}ms`),s?.emit("error:media",{error:new Error(e.details)}),u&&clearTimeout(u),u=setTimeout(()=>{i&&i.recoverMediaError()},n);break}default:E(e,!1)}},D=async e=>{const t=p();return n=!0,s&&(l=S(t,s)),new Promise((i,r)=>{const n=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a),s?.setState("source",{src:e,type:"application/x-mpegURL"}),s?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),i()},a=()=>{t.removeEventListener("loadedmetadata",n),t.removeEventListener("error",a);const e=t.error;r(new Error(e?.message||"Failed to load HLS source"))};t.addEventListener("loadedmetadata",n),t.addEventListener("error",a),t.src=e,t.load()})},P=async e=>{await async function(){return L||b||(b=(async()=>{try{const e=await Promise.resolve().then(()=>mh);if(!(L=e.default).isSupported())throw new Error("hls.js is not supported in this browser");return L}catch(e){throw b=null,new Error(`Failed to load hls.js: ${e instanceof Error?e.message:"Unknown error"}`)}})())}();const r=p();return n=!1,i=function(e){if(!L)throw new Error("hls.js is not loaded. Call loadHlsJs() first.");return new L(e)}({debug:t.debug,autoStartLoad:t.autoStartLoad,startPosition:t.startPosition,startLevel:-1,lowLatencyMode:t.lowLatencyMode,maxBufferLength:t.maxBufferLength,maxMaxBufferLength:t.maxMaxBufferLength,backBufferLength:t.backBufferLength,enableWorker:t.enableWorker,fragLoadingMaxRetry:1,manifestLoadingMaxRetry:1,levelLoadingMaxRetry:1,fragLoadingRetryDelay:500,manifestLoadingRetryDelay:500,levelLoadingRetryDelay:500}),s&&(l=S(r,s)),new Promise((t,n)=>{if(!i||!s)return void n(new Error("HLS not initialized"));let a=!1;o=T(i,s,{onManifestParsed:()=>{a||(a=!0,s?.setState("source",{src:e,type:"application/x-mpegURL"}),s?.emit("media:loaded",{src:e,type:"application/x-mpegURL"}),t())},onLevelSwitched:()=>{},onError:e=>{k(e),e.fatal&&!a&&"network"!==e.type&&"media"!==e.type&&(a=!0,n(new Error(e.details)))},getIsAutoQuality:()=>h}),i.attachMedia(r),i.loadSource(e)})};return{id:"hls-provider",name:"HLS Provider",version:"1.0.0",type:"provider",description:"HLS playback provider using hls.js",canPlay(e){if(!A()&&!R())return!1;const t=e.toLowerCase();return!!t.split("?")[0].split("#")[0].endsWith(".m3u8")||(!!t.includes("application/x-mpegurl")||!!t.includes("application/vnd.apple.mpegurl"))},async init(e){s=e,s.logger.info("HLS plugin initialized");const t=s.on("playback:play",async()=>{if(r)try{await r.play()}catch(e){s?.logger.error("Play failed",e)}}),a=s.on("playback:pause",()=>{r?.pause()}),o=s.on("playback:seeking",({time:e})=>{if(!r)return;const t=Math.max(0,Math.min(e,r.duration||0));r.currentTime=t}),l=s.on("volume:change",({volume:e})=>{r&&(r.volume=e)}),d=s.on("volume:mute",({muted:e})=>{r&&(r.muted=e)}),c=s.on("playback:ratechange",({rate:e})=>{r&&(r.playbackRate=e)}),u=s.on("quality:select",({quality:e,auto:t})=>{if(i&&!n)if(t||"auto"===e)h=!0,i.currentLevel=-1,s?.logger.debug("Quality: auto selection enabled"),s?.setState("currentQuality",{id:"auto",label:"Auto",width:0,height:0,bitrate:0,active:!0});else{h=!1;const t=parseInt(e.replace("level-",""),10);!isNaN(t)&&t>=0&&t<i.levels.length&&(i.nextLevel=t,s?.logger.debug(`Quality: queued switch to level ${t}`))}else s?.logger.warn("Quality selection not available")});s.onDestroy(()=>{t(),a(),o(),l(),d(),c(),u()})},async destroy(){s?.logger.info("HLS plugin destroying"),v(),r?.parentNode&&r.parentNode.removeChild(r),r=null,s=null},async loadSource(e){if(!s)throw new Error("Plugin not initialized");if(s.logger.info("Loading HLS source",{src:e}),v(),a=e,s.setState("playbackState","loading"),s.setState("buffering",!0),R())s.logger.info("Using hls.js for HLS playback"),await P(e);else{if(!A())throw new Error("HLS playback not supported in this browser");s.logger.info("Using native HLS playback (hls.js not supported)"),await D(e)}s.setState("playbackState","ready"),s.setState("buffering",!1)},getCurrentLevel:()=>n||!i?-1:i.currentLevel,setLevel(e){!n&&i?i.currentLevel=e:s?.logger.warn("Quality selection not available in native HLS mode")},getLevels(){return n||!i?[]:(e=i.levels,i.currentLevel,e.map((e,t)=>({index:t,width:e.width||0,height:e.height||0,bitrate:e.bitrate||0,label:m(e),codec:e.codecSet})));var e},getHlsInstance:()=>i,isNativeHLS:()=>n,getLiveInfo(){if(n||!i)return null;return s?.getState("live")||!1?{isLive:!0,latency:i.latency||0,targetLatency:i.targetLatency||3,drift:i.drift||0}:null},async switchToNative(){if(n)return void s?.logger.debug("Already using native HLS");if(!A())return void s?.logger.warn("Native HLS not supported in this browser");if(!a)return void s?.logger.warn("No source loaded");s?.logger.info("Switching to native HLS for AirPlay");const e=s?.getState("playing")||!1,t=r?.currentTime||0,i=a;if(v(),await D(i),r&&t>0&&(r.currentTime=t),e&&r)try{await r.play()}catch(o){s?.logger.debug("Could not auto-resume after switch")}s?.logger.info("Switched to native HLS")},async switchToHlsJs(){if(!n)return void s?.logger.debug("Already using hls.js");if(!R())return void s?.logger.warn("hls.js not supported in this browser");if(!a)return void s?.logger.warn("No source loaded");s?.logger.info("Switching back to hls.js");const e=s?.getState("playing")||!1,t=r?.currentTime||0,i=a;if(v(),await P(i),r&&t>0&&(r.currentTime=t),e&&r)try{await r.play()}catch(o){s?.logger.debug("Could not auto-resume after switch")}s?.logger.info("Switched to hls.js")}}}var D={play:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',pause:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/></svg>',replay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>',volumeHigh:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',volumeLow:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',volumeMute:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/></svg>',fullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>',exitFullscreen:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/></svg>',pip:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z"/></svg>',settings:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>',chromecast:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',chromecastConnected:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',airplay:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 22h12l-6-6-6 6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>',spinner:'<svg viewBox="0 0 24 24" fill="currentColor" class="sp-spin"><path d="M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8z"/></svg>'};function P(e,t,s){const i=document.createElement(e);if(t)for(const[r,n]of Object.entries(t))"className"===r?i.className=n:i.setAttribute(r,n);return i}function w(e,t,s){const i=P("button",{className:`sp-control ${e}`,"aria-label":t,type:"button"});return i.innerHTML=s,i}function _(e){return e.querySelector("video")}function C(e){if(!isFinite(e)||isNaN(e))return"0:00";const t=Math.abs(e),s=Math.floor(t/3600),i=Math.floor(t%3600/60),r=Math.floor(t%60),n=e<0?"-":"";return s>0?`${n}${s}:${x(i)}:${x(r)}`:`${n}${i}:${x(r)}`}function x(e){return e<10?`0${e}`:`${e}`}function M(e){return e<=0?"LIVE":`-${C(e)}`}var O=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=w("sp-play","Play",D.play),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){const e=this.api.getState("playing");let t,s;this.api.getState("ended")?(t=D.replay,s="Replay"):e?(t=D.pause,s="Pause"):(t=D.play,s="Play"),this.el.innerHTML=t,this.el.setAttribute("aria-label",s)}toggle(){const e=_(this.api.container);if(!e)return;const t=this.api.getState("ended"),s=this.api.getState("playing");t?(e.currentTime=0,e.play().catch(()=>{})):s?e.pause():e.play().catch(()=>{})}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},F=class{constructor(e){this.isDragging=!1,this.lastSeekTime=0,this.seekThrottleMs=100,this.wasPlayingBeforeDrag=!1,this.onMouseDown=e=>{e.preventDefault();const t=_(this.api.container);this.wasPlayingBeforeDrag=!!t&&!t.paused,this.isDragging=!0,this.el.classList.add("sp-progress--dragging"),this.lastSeekTime=0,this.seek(e.clientX,!0)},this.onDocMouseMove=e=>{this.isDragging&&(this.seek(e.clientX),this.updateVisualPosition(e.clientX))},this.onMouseUp=e=>{if(this.isDragging&&(this.seek(e.clientX,!0),this.isDragging=!1,this.el.classList.remove("sp-progress--dragging"),this.wasPlayingBeforeDrag)){const e=_(this.api.container);if(e&&e.paused){const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t)}}},this.onMouseMove=e=>{this.updateTooltip(e.clientX)},this.onMouseLeave=()=>{this.isDragging||(this.tooltip.style.opacity="0")},this.onKeyDown=e=>{const t=_(this.api.container);if(!t)return;const s=this.api.getState("duration")||0;switch(e.key){case"ArrowLeft":e.preventDefault(),t.currentTime=Math.max(0,t.currentTime-5);break;case"ArrowRight":e.preventDefault(),t.currentTime=Math.min(s,t.currentTime+5);break;case"Home":e.preventDefault(),t.currentTime=0;break;case"End":e.preventDefault(),t.currentTime=s}},this.api=e,this.wrapper=P("div",{className:"sp-progress-wrapper"}),this.el=P("div",{className:"sp-progress"});const t=P("div",{className:"sp-progress__track"});this.buffered=P("div",{className:"sp-progress__buffered"}),this.filled=P("div",{className:"sp-progress__filled"}),this.handle=P("div",{className:"sp-progress__handle"}),this.tooltip=P("div",{className:"sp-progress__tooltip"}),this.tooltip.textContent="0:00",t.appendChild(this.buffered),t.appendChild(this.filled),t.appendChild(this.handle),this.el.appendChild(t),this.el.appendChild(this.tooltip),this.wrapper.appendChild(this.el),this.el.setAttribute("role","slider"),this.el.setAttribute("aria-label","Seek"),this.el.setAttribute("aria-valuemin","0"),this.el.setAttribute("tabindex","0"),this.wrapper.addEventListener("mousedown",this.onMouseDown),this.wrapper.addEventListener("mousemove",this.onMouseMove),this.wrapper.addEventListener("mouseleave",this.onMouseLeave),this.el.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.wrapper}show(){this.wrapper.classList.add("sp-progress-wrapper--visible")}hide(){this.wrapper.classList.remove("sp-progress-wrapper--visible")}update(){const e=this.api.getState("currentTime")||0,t=this.api.getState("duration")||0,s=this.api.getState("buffered");if(t>0){const i=e/t*100;if(this.filled.style.width=`${i}%`,this.handle.style.left=`${i}%`,s&&s.length>0){const e=s.end(s.length-1)/t*100;this.buffered.style.width=`${e}%`}this.el.setAttribute("aria-valuemax",String(Math.floor(t))),this.el.setAttribute("aria-valuenow",String(Math.floor(e))),this.el.setAttribute("aria-valuetext",C(e))}}getTimeFromPosition(e){const t=this.el.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*(this.api.getState("duration")||0)}updateTooltip(e){const t=this.el.getBoundingClientRect(),s=Math.max(0,Math.min(1,(e-t.left)/t.width)),i=this.getTimeFromPosition(e);this.tooltip.textContent=C(i),this.tooltip.style.left=100*s+"%"}updateVisualPosition(e){const t=this.el.getBoundingClientRect(),s=Math.max(0,Math.min(1,(e-t.left)/t.width));this.filled.style.width=100*s+"%",this.handle.style.left=100*s+"%"}seek(e,t=!1){const s=_(this.api.container);if(!s)return;const i=Date.now();if(!t&&this.isDragging&&i-this.lastSeekTime<this.seekThrottleMs)return;this.lastSeekTime=i;const r=this.getTimeFromPosition(e);s.currentTime=r}destroy(){this.wrapper.removeEventListener("mousedown",this.onMouseDown),this.wrapper.removeEventListener("mousemove",this.onMouseMove),this.wrapper.removeEventListener("mouseleave",this.onMouseLeave),document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.wrapper.remove()}},N=class{constructor(e){this.api=e,this.el=P("div",{className:"sp-time"}),this.el.setAttribute("aria-live","off")}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("currentTime")||0,s=this.api.getState("duration")||0;if(e){const e=this.api.getState("seekableRange");if(e){const s=e.end-t;this.el.textContent=M(s)}else this.el.textContent=M(0)}else this.el.textContent=`${C(t)} / ${C(s)}`}destroy(){this.el.remove()}},B=class{constructor(e){this.isDragging=!1,this.onMouseDown=e=>{e.preventDefault(),this.isDragging=!0,this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onDocMouseMove=e=>{this.isDragging&&this.setVolume(this.getVolumeFromPosition(e.clientX))},this.onMouseUp=()=>{this.isDragging=!1},this.onKeyDown=e=>{const t=_(this.api.container);if(!t)return;switch(e.key){case"ArrowUp":case"ArrowRight":e.preventDefault(),this.setVolume(t.volume+.1);break;case"ArrowDown":case"ArrowLeft":e.preventDefault(),this.setVolume(t.volume-.1)}},this.api=e,this.el=P("div",{className:"sp-volume"}),this.btn=P("button",{className:"sp-control sp-volume__btn","aria-label":"Mute",type:"button"}),this.btn.innerHTML=D.volumeHigh,this.btn.onclick=()=>this.toggleMute();const t=P("div",{className:"sp-volume__slider-wrap"});this.slider=P("div",{className:"sp-volume__slider"}),this.slider.setAttribute("role","slider"),this.slider.setAttribute("aria-label","Volume"),this.slider.setAttribute("aria-valuemin","0"),this.slider.setAttribute("aria-valuemax","100"),this.slider.setAttribute("tabindex","0"),this.level=P("div",{className:"sp-volume__level"}),this.slider.appendChild(this.level),t.appendChild(this.slider),this.el.appendChild(this.btn),this.el.appendChild(t),this.slider.addEventListener("mousedown",this.onMouseDown),this.slider.addEventListener("keydown",this.onKeyDown),document.addEventListener("mousemove",this.onDocMouseMove),document.addEventListener("mouseup",this.onMouseUp)}render(){return this.el}update(){const e=this.api.getState("volume")??1,t=this.api.getState("muted")??!1;let s,i;t||0===e?(s=D.volumeMute,i="Unmute"):e<.5?(s=D.volumeLow,i="Mute"):(s=D.volumeHigh,i="Mute"),this.btn.innerHTML=s,this.btn.setAttribute("aria-label",i);const r=t?0:e;this.level.style.width=100*r+"%",this.slider.setAttribute("aria-valuenow",String(Math.round(100*r)))}toggleMute(){const e=_(this.api.container);e&&(e.muted=!e.muted)}setVolume(e){const t=_(this.api.container);if(!t)return;const s=Math.max(0,Math.min(1,e));t.volume=s,s>0&&t.muted&&(t.muted=!1)}getVolumeFromPosition(e){const t=this.slider.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))}destroy(){document.removeEventListener("mousemove",this.onDocMouseMove),document.removeEventListener("mouseup",this.onMouseUp),this.el.remove()}},U=class{constructor(e){this.api=e,this.el=P("div",{className:"sp-live"}),this.el.innerHTML='<div class="sp-live__dot"></div><span>LIVE</span>',this.el.setAttribute("role","button"),this.el.setAttribute("aria-label","Seek to live"),this.el.setAttribute("tabindex","0"),this.el.onclick=()=>this.seekToLive(),this.el.onkeydown=e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.seekToLive())}}render(){return this.el}update(){const e=this.api.getState("live"),t=this.api.getState("liveEdge");this.el.style.display=e?"":"none",t?this.el.classList.remove("sp-live--behind"):this.el.classList.add("sp-live--behind")}seekToLive(){const e=_(this.api.container);if(!e)return;const t=this.api.getState("seekableRange");t&&(e.currentTime=t.end)}destroy(){this.el.remove()}},$=class{constructor(e){this.isOpen=!1,this.lastQualitiesJson="",this.api=e,this.el=P("div",{className:"sp-quality"}),this.btn=w("sp-quality__btn","Quality",D.settings),this.btnLabel=P("span",{className:"sp-quality__label"}),this.btnLabel.textContent="Auto",this.btn.appendChild(this.btnLabel),this.btn.addEventListener("click",e=>{e.stopPropagation(),this.toggle()}),this.menu=P("div",{className:"sp-quality-menu"}),this.menu.setAttribute("role","menu"),this.menu.addEventListener("click",e=>{e.stopPropagation()}),this.el.appendChild(this.btn),this.el.appendChild(this.menu),this.closeHandler=e=>{this.el.contains(e.target)||this.close()},document.addEventListener("click",this.closeHandler)}render(){return this.el}update(){const e=this.api.getState("qualities")||[],t=this.api.getState("currentQuality");this.el.style.display=e.length>0?"":"none",this.btnLabel.textContent=t?.label||"Auto";const s=JSON.stringify(e.map(e=>e.id)),i=t?.id||"auto";s!==this.lastQualitiesJson&&(this.lastQualitiesJson=s,this.rebuildMenu(e)),this.updateActiveStates(i)}rebuildMenu(e){this.menu.innerHTML="";const t=this.createMenuItem("Auto","auto");this.menu.appendChild(t);const s=[...e].sort((e,t)=>t.height-e.height);for(const i of s){if("auto"===i.id)continue;const e=this.createMenuItem(i.label,i.id);this.menu.appendChild(e)}}updateActiveStates(e){this.menu.querySelectorAll(".sp-quality-menu__item").forEach(t=>{const s=t.getAttribute("data-quality-id")===e;t.classList.toggle("sp-quality-menu__item--active",s)})}createMenuItem(e,t){const s=P("div",{className:"sp-quality-menu__item"});s.setAttribute("role","menuitem"),s.setAttribute("data-quality-id",t);const i=P("span",{className:"sp-quality-menu__label"});return i.textContent=e,s.appendChild(i),s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.selectQuality(t)}),s}selectQuality(e){this.api.emit("quality:select",{quality:e,auto:"auto"===e}),this.close()}toggle(){this.isOpen?this.close():this.open()}open(){this.isOpen=!0,this.menu.classList.add("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","true")}close(){this.isOpen=!1,this.menu.classList.remove("sp-quality-menu--open"),this.btn.setAttribute("aria-expanded","false")}destroy(){document.removeEventListener("click",this.closeHandler),this.el.remove()}};var G=class{constructor(e,t){this.api=e,this.type=t,this.supported="chromecast"===t?function(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent;return/Chrome/.test(e)&&!/Edge|Edg/.test(e)}():"undefined"!=typeof HTMLVideoElement&&"function"==typeof HTMLVideoElement.prototype.webkitShowPlaybackTargetPicker;const s="chromecast"===t?D.chromecast:D.airplay,i="chromecast"===t?"Cast":"AirPlay";this.el=w(`sp-cast sp-cast--${t}`,i,s),this.el.addEventListener("click",()=>this.handleClick()),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(this.supported)if("chromecast"===this.type){const e=this.api.getState("chromecastAvailable"),t=this.api.getState("chromecastActive");this.el.style.display="",this.el.disabled=!e&&!t,this.el.classList.toggle("sp-cast--active",!!t),this.el.classList.toggle("sp-cast--unavailable",!e&&!t),t?(this.el.innerHTML=D.chromecastConnected,this.el.setAttribute("aria-label","Stop casting")):(this.el.innerHTML=D.chromecast,this.el.setAttribute("aria-label",e?"Cast":"No Cast devices found"))}else{const e=this.api.getState("airplayActive");this.el.style.display="",this.el.disabled=!1,this.el.classList.toggle("sp-cast--active",!!e),this.el.classList.remove("sp-cast--unavailable"),this.el.setAttribute("aria-label",e?"Stop AirPlay":"AirPlay")}else this.el.style.display="none"}handleClick(){"chromecast"===this.type?this.handleChromecast():this.handleAirPlay()}handleChromecast(){const e=this.api.getPlugin("chromecast");e&&(e.isConnected()?e.endSession():e.requestSession().catch(()=>{}))}async handleAirPlay(){const e=this.api.getPlugin("airplay");if(e)await e.showPicker();else{const e=_(this.api.container);e?.webkitShowPlaybackTargetPicker?.()}}destroy(){this.el.remove()}},K=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e;const t=document.createElement("video");this.supported="pictureInPictureEnabled"in document||"webkitSetPresentationMode"in t,this.el=w("sp-pip","Picture-in-Picture",D.pip),this.el.addEventListener("click",this.clickHandler),this.supported||(this.el.style.display="none")}render(){return this.el}update(){if(!this.supported)return;const e=this.api.getState("pip");this.el.setAttribute("aria-label",e?"Exit Picture-in-Picture":"Picture-in-Picture"),this.el.classList.toggle("sp-pip--active",!!e)}async toggle(){const e=_(this.api.container);if(e)try{document.pictureInPictureElement===e||"picture-in-picture"===e.webkitPresentationMode?(document.pictureInPictureElement?await document.exitPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("inline"),this.api.logger.debug("PiP: exited")):(e.requestPictureInPicture?await e.requestPictureInPicture():e.webkitSetPresentationMode&&e.webkitSetPresentationMode("picture-in-picture"),this.api.logger.debug("PiP: entered"))}catch(t){this.api.logger.warn("PiP: failed",{error:t.message})}else this.api.logger.warn("PiP: video element not found")}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},H=class{constructor(e){this.clickHandler=()=>{this.toggle()},this.api=e,this.el=w("sp-fullscreen","Fullscreen",D.fullscreen),this.el.addEventListener("click",this.clickHandler)}render(){return this.el}update(){this.api.getState("fullscreen")?(this.el.innerHTML=D.exitFullscreen,this.el.setAttribute("aria-label","Exit fullscreen")):(this.el.innerHTML=D.fullscreen,this.el.setAttribute("aria-label","Fullscreen"))}async toggle(){const e=this.api.container,t=_(e);try{document.fullscreenElement?await document.exitFullscreen():e.requestFullscreen?await e.requestFullscreen():t?.webkitEnterFullscreen&&t.webkitEnterFullscreen()}catch{}}destroy(){this.el.removeEventListener("click",this.clickHandler),this.el.remove()}},V=class{constructor(){this.el=P("div",{className:"sp-spacer"})}render(){return this.el}update(){}destroy(){this.el.remove()}},Y=["play","volume","time","live-indicator","spacer","quality","chromecast","airplay","pip","fullscreen"];function q(e,...t){for(const s of t){const t=e.getAttribute(s);if(null!==t)return t}return null}function j(e){const t={},s=q(e,"data-src","src","href");s&&(t.src=s);const i=q(e,"data-autoplay","autoplay");null!==i&&(t.autoplay="false"!==i);const r=q(e,"data-muted","muted");null!==r&&(t.muted="false"!==r);const n=q(e,"data-controls","controls");null!==n&&(t.controls="false"!==n);const a=q(e,"data-keyboard","keyboard");null!==a&&(t.keyboard="false"!==a);const o=q(e,"data-loop","loop");null!==o&&(t.loop="false"!==o);const l=q(e,"data-poster","poster");l&&(t.poster=l);const h=q(e,"data-brand-color","data-color","color");h&&(t.brandColor=h);const d=e.getAttribute("data-primary-color");d&&(t.primaryColor=d);const c=e.getAttribute("data-background-color");c&&(t.backgroundColor=c);const u=e.getAttribute("data-width");u&&(t.width=u);const f=e.getAttribute("data-height");f&&(t.height=f);const g=e.getAttribute("data-aspect-ratio");g&&(t.aspectRatio=g);const m=e.getAttribute("data-class");m&&(t.className=m);const p=e.getAttribute("data-hide-delay");if(p){const e=parseInt(p,10);isNaN(e)||(t.hideDelay=e)}const v=e.getAttribute("data-playback-rate");if(v){const e=parseFloat(v);isNaN(e)||(t.playbackRate=e)}const y=e.getAttribute("data-start-time");if(y){const e=parseFloat(y);isNaN(e)||(t.startTime=e)}return t}function W(e){const t=e.split(":").map(Number),s=t[0],i=t[1];return 2===t.length&&void 0!==s&&void 0!==i&&!isNaN(s)&&!isNaN(i)&&s>0?i/s*100:56.25}function z(e,t){t.className&&e.classList.add(...t.className.split(" ")),t.width&&(e.style.width=t.width),t.height?e.style.height=t.height:t.aspectRatio&&(e.style.position="relative",e.style.paddingBottom=`${W(t.aspectRatio)}%`,e.style.height="0")}async function X(e,t){if(!t.src)return console.error("[Scarlett Player] No source URL provided"),null;try{z(e,t);const s={};t.brandColor&&(s.accentColor=t.brandColor),t.primaryColor&&(s.primaryColor=t.primaryColor),t.backgroundColor&&(s.backgroundColor=t.backgroundColor);const i={};Object.keys(s).length>0&&(i.theme=s),void 0!==t.hideDelay&&(i.hideDelay=t.hideDelay);const r=[k()];!1!==t.controls&&r.push(function(e={}){let t,s=null,i=null,r=null,n=null,a=null,o=[],l=null,h=null,d=!0;const c=e.controls||Y,u=e.hideDelay??3e3,f=e=>{switch(e){case"play":return new O(t);case"volume":return new B(t);case"progress":default:return null;case"time":return new N(t);case"live-indicator":return new U(t);case"quality":return new $(t);case"chromecast":return new G(t,"chromecast");case"airplay":return new G(t,"airplay");case"pip":return new K(t);case"fullscreen":return new H(t);case"spacer":return new V}},g=()=>{o.forEach(e=>e.update()),r?.update();const e=t?.getState("waiting"),s=t?.getState("seeking"),i=t?.getState("playbackState"),a="loading"===i,l=e||s&&!t?.getState("paused")||a;n?.classList.toggle("sp-buffering--visible",!!l)},m=()=>{d||(d=!0,s?.classList.add("sp-controls--visible"),s?.classList.remove("sp-controls--hidden"),i?.classList.add("sp-gradient--visible"),r?.show(),t?.setState("controlsVisible",!0)),v()},p=()=>{const e=t?.getState("paused");e||(d=!1,s?.classList.remove("sp-controls--visible"),s?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),r?.hide(),t?.setState("controlsVisible",!1))},v=()=>{l&&clearTimeout(l),l=setTimeout(p,u)},y=()=>{m()},E=()=>{p()},T=e=>{if(!t.container.contains(document.activeElement))return;const s=t.container.querySelector("video");if(s)switch(e.key){case" ":case"k":e.preventDefault(),s.paused?s.play():s.pause();break;case"m":e.preventDefault(),s.muted=!s.muted;break;case"f":e.preventDefault(),document.fullscreenElement?document.exitFullscreen():t.container.requestFullscreen?.();break;case"ArrowLeft":e.preventDefault(),s.currentTime=Math.max(0,s.currentTime-5),m();break;case"ArrowRight":e.preventDefault(),s.currentTime=Math.min(s.duration||0,s.currentTime+5),m();break;case"ArrowUp":e.preventDefault(),s.volume=Math.min(1,s.volume+.1),m();break;case"ArrowDown":e.preventDefault(),s.volume=Math.max(0,s.volume-.1),m()}};return{id:"ui-controls",name:"UI Controls",type:"ui",version:"1.0.0",async init(l){t=l,a=document.createElement("style"),a.textContent="\n/* ============================================\n Container & Base\n ============================================ */\n.sp-container {\n position: relative;\n width: 100%;\n height: 100%;\n background: #000;\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n}\n\n.sp-container video {\n width: 100%;\n height: 100%;\n display: block;\n object-fit: contain;\n}\n\n.sp-container:focus {\n outline: none;\n}\n\n/* ============================================\n Gradient Overlay\n ============================================ */\n.sp-gradient {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 160px;\n background: linear-gradient(\n to top,\n rgba(0, 0, 0, 0.8) 0%,\n rgba(0, 0, 0, 0.4) 50%,\n transparent 100%\n );\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.25s ease;\n z-index: 5;\n}\n\n.sp-gradient--visible {\n opacity: 1;\n}\n\n/* ============================================\n Controls Container\n ============================================ */\n.sp-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n align-items: center;\n padding: 0 12px 12px;\n gap: 4px;\n opacity: 0;\n transform: translateY(4px);\n transition: opacity 0.25s ease, transform 0.25s ease;\n z-index: 10;\n}\n\n.sp-controls--visible {\n opacity: 1;\n transform: translateY(0);\n}\n\n.sp-controls--hidden {\n opacity: 0;\n transform: translateY(4px);\n pointer-events: none;\n}\n\n/* ============================================\n Progress Bar (Above Controls)\n ============================================ */\n.sp-progress-wrapper {\n position: absolute;\n bottom: 48px;\n left: 12px;\n right: 12px;\n height: 20px;\n display: flex;\n align-items: center;\n cursor: pointer;\n z-index: 10;\n opacity: 0;\n transition: opacity 0.25s ease;\n}\n\n.sp-progress-wrapper--visible {\n opacity: 1;\n}\n\n.sp-progress {\n position: relative;\n width: 100%;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n transition: height 0.15s ease;\n}\n\n.sp-progress-wrapper:hover .sp-progress,\n.sp-progress--dragging {\n height: 5px;\n}\n\n.sp-progress__track {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n border-radius: inherit;\n overflow: hidden;\n}\n\n.sp-progress__buffered {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: rgba(255, 255, 255, 0.4);\n border-radius: inherit;\n transition: width 0.1s linear;\n}\n\n.sp-progress__filled {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: var(--sp-accent, #e50914);\n border-radius: inherit;\n}\n\n.sp-progress__handle {\n position: absolute;\n top: 50%;\n width: 14px;\n height: 14px;\n background: var(--sp-accent, #e50914);\n border-radius: 50%;\n transform: translate(-50%, -50%) scale(0);\n transition: transform 0.15s ease;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__handle,\n.sp-progress--dragging .sp-progress__handle {\n transform: translate(-50%, -50%) scale(1);\n}\n\n/* Progress Tooltip */\n.sp-progress__tooltip {\n position: absolute;\n bottom: calc(100% + 8px);\n padding: 6px 10px;\n background: rgba(20, 20, 20, 0.95);\n color: #fff;\n font-size: 12px;\n font-weight: 500;\n font-variant-numeric: tabular-nums;\n border-radius: 4px;\n white-space: nowrap;\n transform: translateX(-50%);\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.15s ease;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n}\n\n.sp-progress-wrapper:hover .sp-progress__tooltip {\n opacity: 1;\n}\n\n/* ============================================\n Control Buttons\n ============================================ */\n.sp-control {\n background: none;\n border: none;\n color: rgba(255, 255, 255, 0.9);\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: color 0.15s ease, transform 0.15s ease, background 0.15s ease;\n flex-shrink: 0;\n}\n\n.sp-control:hover {\n color: #fff;\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-control:active {\n transform: scale(0.92);\n}\n\n.sp-control:focus-visible {\n outline: 2px solid var(--sp-accent, #e50914);\n outline-offset: 2px;\n}\n\n.sp-control:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n transform: none;\n}\n\n.sp-control:disabled:hover {\n background: none;\n}\n\n.sp-control svg {\n width: 24px;\n height: 24px;\n fill: currentColor;\n display: block;\n}\n\n.sp-control--small svg {\n width: 20px;\n height: 20px;\n}\n\n/* ============================================\n Spacer\n ============================================ */\n.sp-spacer {\n flex: 1;\n min-width: 0;\n}\n\n/* ============================================\n Time Display\n ============================================ */\n.sp-time {\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n color: rgba(255, 255, 255, 0.9);\n white-space: nowrap;\n padding: 0 4px;\n letter-spacing: 0.02em;\n}\n\n/* ============================================\n Volume Control\n ============================================ */\n.sp-volume {\n display: flex;\n align-items: center;\n position: relative;\n}\n\n.sp-volume__slider-wrap {\n width: 0;\n overflow: hidden;\n transition: width 0.2s ease;\n}\n\n.sp-volume:hover .sp-volume__slider-wrap,\n.sp-volume:focus-within .sp-volume__slider-wrap {\n width: 64px;\n}\n\n.sp-volume__slider {\n width: 64px;\n height: 3px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 1.5px;\n cursor: pointer;\n position: relative;\n margin: 0 8px 0 4px;\n}\n\n.sp-volume__level {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: #fff;\n border-radius: inherit;\n transition: width 0.1s ease;\n}\n\n/* ============================================\n Live Indicator\n ============================================ */\n.sp-live {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 11px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--sp-accent, #e50914);\n cursor: pointer;\n padding: 6px 10px;\n border-radius: 4px;\n transition: background 0.15s ease, opacity 0.15s ease;\n}\n\n.sp-live:hover {\n background: rgba(255, 255, 255, 0.1);\n}\n\n.sp-live__dot {\n width: 8px;\n height: 8px;\n background: currentColor;\n border-radius: 50%;\n animation: sp-pulse 2s ease-in-out infinite;\n}\n\n.sp-live--behind {\n opacity: 0.6;\n}\n\n.sp-live--behind .sp-live__dot {\n animation: none;\n}\n\n@keyframes sp-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.4; }\n}\n\n/* ============================================\n Quality / Settings Menu\n ============================================ */\n.sp-quality {\n position: relative;\n}\n\n.sp-quality__btn {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.sp-quality__label {\n font-size: 12px;\n font-weight: 500;\n opacity: 0.9;\n}\n\n.sp-quality-menu {\n position: absolute;\n bottom: calc(100% + 8px);\n right: 0;\n background: rgba(20, 20, 20, 0.95);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border-radius: 8px;\n padding: 8px 0;\n min-width: 150px;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);\n opacity: 0;\n visibility: hidden;\n transform: translateY(8px);\n transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s;\n z-index: 20;\n}\n\n.sp-quality-menu--open {\n opacity: 1;\n visibility: visible;\n transform: translateY(0);\n}\n\n.sp-quality-menu__item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 16px;\n font-size: 13px;\n color: rgba(255, 255, 255, 0.8);\n cursor: pointer;\n transition: background 0.1s ease, color 0.1s ease;\n}\n\n.sp-quality-menu__item:hover {\n background: rgba(255, 255, 255, 0.1);\n color: #fff;\n}\n\n.sp-quality-menu__item--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-quality-menu__check {\n width: 16px;\n height: 16px;\n fill: currentColor;\n margin-left: 8px;\n opacity: 0;\n}\n\n.sp-quality-menu__item--active .sp-quality-menu__check {\n opacity: 1;\n}\n\n/* ============================================\n Cast Button States\n ============================================ */\n.sp-cast--active {\n color: var(--sp-accent, #e50914);\n}\n\n.sp-cast--unavailable {\n opacity: 0.4;\n}\n\n/* ============================================\n Buffering Indicator\n ============================================ */\n.sp-buffering {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 15;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.2s ease;\n}\n\n.sp-buffering--visible {\n opacity: 1;\n}\n\n.sp-buffering svg {\n width: 48px;\n height: 48px;\n fill: rgba(255, 255, 255, 0.9);\n filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));\n}\n\n@keyframes sp-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n}\n\n.sp-spin {\n animation: sp-spin 0.8s linear infinite;\n}\n\n/* ============================================\n Reduced Motion\n ============================================ */\n@media (prefers-reduced-motion: reduce) {\n .sp-gradient,\n .sp-controls,\n .sp-progress-wrapper,\n .sp-progress,\n .sp-progress__handle,\n .sp-progress__tooltip,\n .sp-control,\n .sp-volume__slider-wrap,\n .sp-quality-menu,\n .sp-buffering {\n transition: none;\n }\n\n .sp-live__dot,\n .sp-spin {\n animation: none;\n }\n}\n\n/* ============================================\n CSS Custom Properties (Theming)\n ============================================ */\n:root {\n --sp-accent: #e50914;\n --sp-color: #fff;\n --sp-bg: rgba(0, 0, 0, 0.8);\n --sp-control-height: 48px;\n --sp-icon-size: 24px;\n}\n",document.head.appendChild(a),e.theme&&this.setTheme(e.theme);const d=t.container;if(d){"static"===getComputedStyle(d).position&&(d.style.position="relative"),i=document.createElement("div"),i.className="sp-gradient sp-gradient--visible",d.appendChild(i),n=document.createElement("div"),n.className="sp-buffering",n.innerHTML=D.spinner,n.setAttribute("aria-hidden","true"),d.appendChild(n),r=new F(t),d.appendChild(r.render()),r.show(),s=document.createElement("div"),s.className="sp-controls sp-controls--visible",s.setAttribute("role","toolbar"),s.setAttribute("aria-label","Video controls");for(const e of c){const t=f(e);t&&(o.push(t),s.appendChild(t.render()))}d.appendChild(s),d.addEventListener("mousemove",y),d.addEventListener("mouseenter",y),d.addEventListener("mouseleave",E),d.addEventListener("touchstart",y,{passive:!0}),d.addEventListener("click",y),document.addEventListener("keydown",T),h=t.subscribeToState(g),document.addEventListener("fullscreenchange",g),g(),d.hasAttribute("tabindex")||d.setAttribute("tabindex","0"),t.logger.debug("UI controls plugin initialized")}else t.logger.error("UI plugin: container not found")},async destroy(){l&&(clearTimeout(l),l=null),h?.(),h=null,t?.container&&(t.container.removeEventListener("mousemove",y),t.container.removeEventListener("mouseenter",y),t.container.removeEventListener("mouseleave",E),t.container.removeEventListener("touchstart",y),t.container.removeEventListener("click",y)),document.removeEventListener("keydown",T),document.removeEventListener("fullscreenchange",g),o.forEach(e=>e.destroy()),o=[],r?.destroy(),r=null,s?.remove(),s=null,i?.remove(),i=null,n?.remove(),n=null,a?.remove(),a=null,t?.logger.debug("UI controls plugin destroyed")},show(){m()},hide(){d=!1,s?.classList.remove("sp-controls--visible"),s?.classList.add("sp-controls--hidden"),i?.classList.remove("sp-gradient--visible"),r?.hide(),t?.setState("controlsVisible",!1)},setTheme(e){const s=t?.container||document.documentElement;e.primaryColor&&s.style.setProperty("--sp-color",e.primaryColor),e.accentColor&&s.style.setProperty("--sp-accent",e.accentColor),e.backgroundColor&&s.style.setProperty("--sp-bg",e.backgroundColor),e.controlBarHeight&&s.style.setProperty("--sp-control-height",`${e.controlBarHeight}px`),e.iconSize&&s.style.setProperty("--sp-icon-size",`${e.iconSize}px`)},getControlBar:()=>s}}(i));const n=await async function(e){const t=new g(e);return await t.init(),t}({container:e,src:t.src,autoplay:t.autoplay||!1,muted:t.muted||!1,poster:t.poster,loop:t.loop||!1,plugins:r}),a=e.querySelector("video");return a&&(t.playbackRate&&(a.playbackRate=t.playbackRate),t.startTime&&(a.currentTime=t.startTime)),n}catch(s){return console.error("[Scarlett Player] Failed to create player:",s),null}}async function Q(e){if(e.hasAttribute("data-scarlett-initialized"))return null;const t=j(e);e.setAttribute("data-scarlett-initialized","true");const s=await X(e,t);return s||e.removeAttribute("data-scarlett-initialized"),s}const J=["[data-scarlett-player]","[data-sp]","[data-video-player]",".scarlett-player"];async function Z(){const e=J.join(", "),t=document.querySelectorAll(e),s=Array.from(t).map(e=>Q(e));await Promise.all(s),t.length>0&&console.log(`[Scarlett Player] Initialized ${t.length} player(s)`)}async function ee(e){let t=null;if("string"==typeof e.container){if(t=document.querySelector(e.container),!t)return console.error(`[Scarlett Player] Container not found: ${e.container}`),null}else t=e.container;return X(t,{...e})}const te={create:ee,initAll:Z,version:"0.1.2"};"undefined"!=typeof window&&(window.ScarlettPlayer=te),"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Z()}):Z());const se=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ie=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=re},re=Number.MAX_SAFE_INTEGER||9007199254740991;let ne=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ae=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),oe=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var le="manifest",he="level",de="audioTrack",ce="subtitleTrack",ue={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class fe{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ge{constructor(e,t,s,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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fe(e),this.fast_=new fe(t),this.defaultTTFB_=i,this.ttfb_=new fe(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new fe(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new fe(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new fe(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function me(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function pe(){return pe=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},pe.apply(null,arguments)}function ve(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function ye(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(s),!0).forEach(function(t){me(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ve(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}class Ee{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Te,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Te=function(){},Se={trace:Te,debug:Te,log:Te,warn:Te,info:Te,error:Te};function Le(){return pe({},Se)}function be(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Te}(e,s)}const Ae=Le();const Re=Ae;function Ie(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ke(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(e=>-1===i.indexOf(e))}function De(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let i,r,n,a="",o=0;for(;o<s;){if(i=e[o++],0===i&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function Pe(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function we(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function _e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ce,xe={exports:{}};var Me,Oe,Fe,Ne,Be,Ue=(Ce||(Ce=1,Me=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Oe=/^(?=([^\/?#]*))\1([^]*)$/,Fe=/(?:\/|^)\.(?=\/)/g,Ne=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,xe.exports=Be={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var i=Be.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=Be.normalizePath(i.path),Be.buildURLFromParts(i)}var r=Be.parseURL(t);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=Be.normalizePath(r.path),Be.buildURLFromParts(r)):t;var n=Be.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Oe.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=Be.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?Be.normalizePath(r.path):r.path),Be.buildURLFromParts(o)},parseURL:function(e){var t=Me.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(Fe,"");e.length!==(e=e.replace(Ne,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),xe.exports);class $e{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 Ge="audio",Ke="video",He="audiovideo";class Ve{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const s=We(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[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={[Ge]:null,[Ke]:null,[He]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new $e),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ue.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ge]=null,e[Ke]=null,e[He]=null}}function Ye(e){return"initSegment"!==e.sn}class qe extends Ve{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(se(e)&&se(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=se(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){se(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Ye(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class je extends Ve{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function We(e,t){const s=Object.getPrototypeOf(e);if(s){const e=Object.getOwnPropertyDescriptor(s,t);return e||We(s,t)}}const ze=Math.pow(2,32)-1,Xe=[].push,Qe={video:1,audio:2,id3:3,text:4};function Je(e){return String.fromCharCode.apply(null,e)}function Ze(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function et(e,t){const s=st(e,t);return s<0?4294967296+s:s}function tt(e,t){let s=et(e,t);return s*=Math.pow(2,32),s+=et(e,t+4),s}function st(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function it(e,t){const s=[];if(!t.length)return s;const i=e.byteLength;for(let r=0;r<i;){const n=et(e,r),a=n>1?r+n:i;if(Je(e.subarray(r+4,r+8))===t[0])if(1===t.length)s.push(e.subarray(r+8,a));else{const i=it(e.subarray(r+8,a),t.slice(1));i.length&&Xe.apply(s,i)}r=a}return s}function rt(e){const t=[],s=e[0];let i=8;const r=et(e,i);i+=4;let n=0,a=0;0===s?(n=et(e,i),a=et(e,i+4),i+=8):(n=tt(e,i),a=tt(e,i+8),i+=16),i+=2;let o=e.length+a;const l=Ze(e,i);i+=2;for(let h=0;h<l;h++){let s=i;const n=et(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return Re.warn("SIDX has hierarchical references (not supported)"),null;const l=et(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function nt(e){const t=[],s=it(e,["moov","trak"]);for(let i=0;i<s.length;i++){const e=s[i],r=it(e,["tkhd"])[0];if(r){let s=r[0];const i=et(r,0===s?12:20),n=it(e,["mdia","mdhd"])[0];if(n){s=n[0];const r=et(n,0===s?12:20),a=it(e,["mdia","hdlr"])[0];if(a){const s=Je(a.subarray(8,12)),n={soun:Ge,vide:Ke}[s],o=at(it(e,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=ye({timescale:r,id:i},o)):t[i]={timescale:r,type:s,stsd:o}}}}}return it(e,["moov","mvex","trex"]).forEach(e=>{const s=et(e,4),i=t[s];i&&(i.default={duration:et(e,12),flags:et(e,20)})}),t}function at(e){const t=e.subarray(8),s=t.subarray(86),i=Je(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=it(t,[i])[0];it(e.subarray("enca"===i?28:78),["sinf"]).forEach(e=>{const t=it(e,["schm"])[0];if(t){const s=Je(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=it(e,["frma"])[0];t&&(n=Je(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=it(s,["avcC"])[0];e&&e.length>3&&(n+="."+ht(e[1])+ht(e[2])+ht(e[3]),r=ot("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=it(t,[i])[0],s=it(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=lt(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=lt(s,e);const i=s[e++];if(64!==i)break;if(n+="."+ht(i),e+=12,5!==s[e++])break;e=lt(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=it(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=et(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}r=ot("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ot(n,s)||n;break;case"vp09":{const e=it(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+dt(t)+"."+dt(s)+"."+dt(i)}break}case"av01":{const e=it(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,v=0;n+="."+t+"."+dt(i)+a+"."+dt(h)+"."+d+"."+c+u+f+"."+dt(g)+"."+dt(m)+"."+dt(p)+"."+v,r=ot("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function ot(e,t){const s=it(t,["dvvC"]),i=s.length?s[0]:it(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+dt(t)+"."+dt(s)}}function lt(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function ht(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function dt(e){return(e<10?"0":"")+e}function ct(e,t){it(e,["moov","trak"]).forEach(e=>{const s=it(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=it(i,["enca"]);const n=r.length>0;n||(r=it(i,["encv"])),r.forEach(e=>{it(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const s=ut(e);s&&t(s,n)})})})}function ut(e){const t=it(e,["schm"])[0];if(t){const s=Je(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=it(e,["schi","tenc"])[0];if(t)return t}}}function ft(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function gt(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return it(i,["moof"]).map(o=>{const l=o.byteOffset-8;it(o,["traf"]).map(o=>{const h=it(o,["tfdt"]).map(e=>{const t=e[0];let s=et(e,4);return 1===t&&(s*=Math.pow(2,32),s+=et(e,8)),s/r})[0];return void 0!==h&&(e=h),it(o,["tfhd"]).map(h=>{const d=et(h,4),c=16777215&et(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=et(h,p),p+=4),f&&(g=et(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=mt(t.codec)),it(o,["trun"]).map(n=>{const o=n[0],h=16777215&et(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=et(n,4);let b=8;d&&(c=et(n,b),b+=4),f&&(b+=4);let A=c+l;for(let l=0;l<L;l++){if(m?(p=et(n,b),b+=4):p=u,v?(y=et(n,b),b+=4):y=g,E&&(b+=4),T&&(S=0===o?et(n,b):st(n,b),b+=4),t.type===Ke){let t=0;for(;t<y;){const n=et(i,A);if(A+=4,pt(a,i[A])){vt(i.subarray(A,A+n),a?2:1,e+S/r,s)}A+=n,t+=n+4}}e+=p/r}}))})})}),s}function mt(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function pt(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function vt(e,t,s,i){const r=yt(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){Re.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=Ze(r,t);if(t+=2,49===e){const e=et(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let s=0;s<n;s++)l[s]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:De(l),userDataBytes:l})}}}function yt(e){const t=e.byteLength,s=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return e;const r=t-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=e[a];return n}function Et(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(e,...t){const s=t.length;let i=8,r=s;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,s)}function Tt(e){const t=e.getUint32(0),s=e.byteOffset,i=e.byteLength;if(i<t)return{offset:s,size:i};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:t};const n=e.buffer,a=Pe(new Uint8Array(n,s+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=e.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,s+32+16*e,16));h=32+16*r}if(!h)return{offset:s,size:t};const d=e.getUint32(h);return t-32<d?{offset:s,size:t}:(l=new Uint8Array(n,s+h+4,d),{version:r,systemId:a,kids:o,data:l,offset:s,size:t})}const St=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Lt={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 bt(e,t){const s=Lt[t];return!!s&&!!s[e.slice(0,4)]}function At(e,t,s=!0){return!e.split(",").some(e=>!Rt(e,t,s))}function Rt(e,t,s=!0){var i;const r=Ie(s);return null!=(i=null==r?void 0:r.isTypeSupported(It(e,t)))&&i}function It(e,t){return`${t}/mp4;codecs=${e}`}function kt(e){if(e){const t=e.substring(0,4);return Lt.video[t]}return 2}function Dt(e){const t=St();return e.split(",").reduce((e,s)=>{const i=t&&mt(s)?9:Lt.video[s];return i?(2*i+e)/(e?3:2):(Lt.audio[s]+e)/(e?2:1)},0)}const Pt={};const wt=/flac|opus|mp4a\.40\.34/i;function _t(e,t=!0){return e.replace(wt,e=>function(e,t=!0){if(Pt[e])return Pt[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(Rt(s[r],"audio",t))return Pt[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=Ie(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function Ct(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(xt(e,"audio")||xt(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function xt(e,t){return bt(e,t)&&Rt(e,t)}function Mt(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function Ot(e){const t=Ie(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ft(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Nt={supported:!1,smooth:!1,powerEfficient:!1},Bt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ut(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Nt],error:e}}function $t(e,t,s,i,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,s)=>{if(s){const i=t.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(t=>{e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(u){return!0}return void 0!==a&&(a.split(",").some(e=>mt(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(r,8e6))||!!c&&se(d)&&Object.keys(c).some(e=>parseInt(e)>d)}function Gt(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(Bt);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Ht(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map(e=>{const t={contentType:It(Mt(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Ht(e);if(r&&e.audioGroups)return e.audioGroups.reduce((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:It(t,"audio"),bitrate:s?Kt(t,n):n};i&&(r.channels=""+i),e.push(r)})}return e},e):e},[]);return[]}(e,t,o>0),h=l.length;for(let d=o||1*h||1;d--;){const e={type:"media-source"};if(o&&(e.video=a[d%o]),h){e.audio=l[d%h];const t=e.audio.bitrate;e.video&&t&&(e.video.bitrate-=t)}n.push(e)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>mt(e))&&St())return Promise.resolve(Ut(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:s,video:i}=e;if(i){t+=`${Ft(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){t+=`${i?"_":""}${Ft(s.contentType)}_c${s.channels}`}return t}(e);return i[t]||(i[t]=s.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Kt(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Ht(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const Vt=["NONE","TYPE-0","TYPE-1",null];const Yt=["SDR","PQ","HLG"];var qt={No:"",Yes:"YES",v2:"v2"};function jt(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?qt.v2:qt.Yes:qt.No}class Wt{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class zt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Xt(this._audioGroups,e)}hasSubtitleGroup(e){return Xt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Xt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Qt(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||Yt.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Jt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}})(t));function Zt(e,t){Re.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function es(e){return e.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ts(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function ss(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let i=0;i<t.length;i++){if(is(e,t[i],s))return i}return-1}function is(e,t,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const s=e.split(","),i=t.split(",");return s.length===i.length&&!s.some(e=>-1===i.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===s||s(e,t))}function rs(e,t){const{audioCodec:s,channels:i}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function ns(e,t,s){for(let i=t;i>-1;i--)if(s(e[i]))return i;for(let i=t+1;i<e.length;i++)if(s(e[i]))return i;return-1}function as(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}class os extends Ee{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!e||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(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=r.levels,A=b[u],R=Math.max(l.loaded,Math.round(h*(s.bitrate||A.averageBitrate)/8));let I=S?d-T:d;I<1&&S&&(I=Math.min(d,8*l.loaded/L));const k=S?1e3*l.loaded/I:0,D=v/1e3,P=k?(R-l.loaded)/k:8*R/L+D;if(P<=E)return;const w=k?8*k:L,_=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),C=this.hls.config.abrBandWidthUpFactor;let x,M=Number.POSITIVE_INFINITY;for(x=u-1;x>c;x--){const e=b[x].maxBitrate,t=!b[x].details||_;if(M=this.getTimeToLoadFrag(D,w,h*e,t),M<Math.min(E,h+D))break}if(M>=P)return;if(M>10*h)return;S?this.bwEstimator.sample(d-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(d);const O=b[x].maxBitrate;this.getBwEstimate()*C>O&&this.resetEstimator(O);const F=this.findBestLevel(O,c,x,0,E,1,1);F>-1&&(x=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${P.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: ${se(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${x} @ ${0|O} bps`),r.nextLoadLevel=r.nextAutoLevel=x,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===x&&x>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${x>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,x>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,x,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||P>2*M?N():this.timer=self.setInterval(N,1e3*M),r.trigger(oe.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ge(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ae.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;se(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===ue.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(oe.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ue.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===h;let T,S="SDR",L=(null==v?void 0:v.frameRate)||0;const{audioPreference:b,videoPreference:A}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=es(g));let I=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce((e,s,i)=>{if(!s.codecSet)return e;const r=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]}))}),e},{})}(f,R,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Qt(t,r);for(let b=n.length;b--;){const t=e[n[b]];d||(d=t.channels[2]>0),u=Math.min(u,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),E.filter(e=>t.videoRanges[e]>0).length>0&&(c=!0)}u=se(u)?u:0,f=se(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=se(g)?g:s,s=Math.max(g,s),c||(t=void 0);const L=n.length>1;return{codecSet:n.reduce((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?E.filter(e=>r.videoRanges[e]>0):[],L){if(r.minBitrate>s)return Zt(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return Zt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Zt(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return Zt(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return Zt(i,"no renditions with stereo sound found"),t;if(r.minHeight>T)return Zt(i,`min resolution of ${r.minHeight} > maximum of ${T}`),t;if(r.minFramerate>S)return Zt(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),t;if(!v.some(e=>r.videoRanges[e]>0))return Zt(i,`no variants with VIDEO-RANGE of ${Jt(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Zt(i,`video codec preference "${l}" not found`),t;if(r.maxScore<p)return Zt(i,`max score of ${r.maxScore} < selected max of ${p}`),t}return t&&(Dt(i)>=Dt(t)||r.fragmentError>e[t].fragmentError)?t:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(i,S,e,b,A),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;I=h,T=n,S=d?a[a.length-1]:a[0],L=o,e=Math.max(e,l),this.log(`picked start tier ${Jt(r)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let _=s;_>=t;_--){var w;const t=f[_],o=_>d;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&$t(t,R,S,L,e,b)?(t.supportedPromise=Gt(t,R,s,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,i=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${Jt(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${Jt(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${Jt(e)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=Bt}if((T&&t.codecSet!==T||S&&t.videoRange!==S||o&&L>t.frameRate||!o&&L>0&&L<t.frameRate||null!=(w=t.supportedResult)&&null!=(w=w.decodingInfoResults)&&w.some(e=>!1===e.smooth))&&(!E||_!==I)){P.push(_);continue}const c=t.details,g=(u?null==c?void 0:c.partTarget:null==c?void 0:c.averagetargetduration)||k;let v;v=o?a*e:n*e;const A=k&&i>=2*k&&0===r?t.averageBitrate:t.maxBitrate,C=this.getTimeToLoadFrag(D,v,A*g,void 0===c);if(v>=A&&(_===h||0===t.loadError&&0===t.fragmentError)&&(C<=D||!se(C)||y&&!this.bitrateTestDelay||C<l)){const e=this.forcedAutoLevel;return _===m||-1!==e&&e===m||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${d}->${_} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-A)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=_),_}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const ls=function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function hs(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===ds(s,i,n)||function(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=ls(t,ds.bind(null,s,i));return!a||a===e&&n?n:a}function ds(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function cs(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function us(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),ls(i,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0)),n||null}return null}function fs(e){switch(e.details){case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_TIMEOUT:case ae.LEVEL_LOAD_TIMEOUT:case ae.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function gs(e){return e.details.startsWith("key")}function ms(e){return gs(e)&&!!e.frag&&!e.frag.decryptdata}function ps(e,t){const s=fs(t);return e.default[(s?"timeout":"error")+"Retry"]}function vs(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function ys(e){return ye(ye({},e),{errorRetry:null,timeoutRetry:null})}function Es(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return Ts(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function Ts(e){return 0===e&&!1===navigator.onLine}var Ss={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ls={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class bs extends Ee{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.ERROR,this.onError,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.ERROR,this.onError,this),e.off(oe.ERROR,this.onErrorOut,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===ue.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i){return this.hls.allAudioTracks.filter(e=>i.indexOf(e.groupId)>=0).some(e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ae.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=As());case ae.FRAG_GAP:case ae.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Ss.SendAlternateToPenaltyBox);case ae.LEVEL_EMPTY_ERROR:case ae.LEVEL_PARSING_ERROR:{var n;const e=t.parent===ue.MAIN?t.level:i.loadLevel;t.details===ae.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case ae.AUDIO_TRACK_LOAD_ERROR:case ae.AUDIO_TRACK_LOAD_TIMEOUT:case ae.SUBTITLE_LOAD_ERROR:case ae.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===de&&e.hasAudioGroup(r.groupId)||r.type===ce&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ss.SendAlternateToPenaltyBox,void(t.errorAction.flags=Ls.MoveAllAlternatesMatchingHost)}return;case ae.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingHDCP});case ae.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ae.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ae.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingKey});case ae.BUFFER_ADD_CODEC_ERROR:case ae.REMUX_ALLOC_ERROR:case ae.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:i.loadLevel);return;case ae.INTERNAL_EXCEPTION:case ae.BUFFER_APPENDING_ERROR:case ae.BUFFER_FULL_ERROR:case ae.LEVEL_SWITCH_ERROR:case ae.BUFFER_STALLED_ERROR:case ae.BUFFER_SEEK_OVER_HOLE:case ae.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=As())}t.type===ne.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=As())}getPlaylistRetryOrSwitchAction(e,t){const s=ps(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Es(s,i,fs(e),e.response))return{action:Ss.RetryRequest,flags:Ls.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=ps(gs(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(i&&(e.details!==ae.FRAG_GAP&&i.fragmentError++,!ms(e))){if(Es(a,o,fs(e),e.response))return{action:Ss.RetryRequest,flags:Ls.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,t===ae.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===ue.AUDIO&&t===ae.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:e})=>i.audioCodec!==e),m="video"===e.sourceBufferName&&(t===ae.BUFFER_ADD_CODEC_ERROR||t===ae.BUFFER_APPEND_ERROR)&&h.some(({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(t===ae.FRAG_GAP&&f===ue.MAIN&&e.frag){const t=h[r].details;if(t){const s=hs(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===de&&s.hasAudioGroup(v)||p===ce&&s.hasSubtitleGroup(v))continue;if(f===ue.AUDIO&&null!=(a=i.audioGroups)&&a.some(e=>s.hasAudioGroup(e))||f===ue.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(e=>s.hasSubtitleGroup(e))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Ss.SendAlternateToPenaltyBox,flags:Ls.None,nextAutoLevel:l}}return{action:Ss.SendAlternateToPenaltyBox,flags:Ls.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case Ss.DoNothing:break;case Ss.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ae.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ls.None:this.switchLevel(e,r);break;case Ls.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=Vt[Vt.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ls.MoveAllAlternatesMatchingKey:{const t=e.decryptdata;if(t){const i=this.hls.levels,r=i.length;for(let s=r;s--;){var n,a;if(this.variantHasKey(i[s],t))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${Pe(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s)}const o=e.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==ue.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ae.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=Ft(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}}function As(e){const t={action:Ss.DoNothing,flags:Ls.None};return e&&(t.resolved=!0),t}var Rs="NOT_LOADED",Is="APPENDING",ks="PARTIAL",Ds="OK";class Ps{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const t=s[i];if(!t)break;if(t.start<=e&&e<=t.end&&t.loaded)return t}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,i=_s(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(i=>{const a=s.elementaryStreams[i];if(!a)return;const o=t[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,e.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),ws(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Cs(s,t=>t.fragment.sn>=e))}fragBuffered(e,t){const s=_s(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const e=i.start(h)-this.bufferPadding,t=i.end(h)+this.bufferPadding;if(l>=e&&o<=t){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(n<t&&a>e){const e=Math.max(n,i.start(h)),t=Math.min(a,i.end(h));t>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:t}))}else if(a<=e)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&ws(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ws(t))}getState(e){const t=_s(e),s=this.fragments[t];return s?s.buffered?ws(s)?ks:Ds:Is:Rs}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=_s(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(i){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_s(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=_s(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=Cs(s,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function ws(e){var t,s,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial)}function _s(e){return`${e.type}_${e.level}_${e.sn}`}function Cs(e,t){return e.filter(e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s})}var xs=0,Ms=1;class Os{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case xs:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ms:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Fs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(4*i);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),v=new Int32Array(p.length);let y,E,T,S,L,b,A,R,I,k,D,P,w,_;const C=this.networkToHostOrderSwap;for(;t<p.length;){for(I=C(p[t]),k=C(p[t+1]),D=C(p[t+2]),P=C(p[t+3]),L=I^r[0],b=P^r[1],A=D^r[2],R=k^r[3],w=4,_=1;_<i;_++)y=o[L>>>24]^l[b>>16&255]^h[A>>8&255]^d[255&R]^r[w],E=o[b>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&L]^r[w+1],T=o[A>>>24]^l[R>>16&255]^h[L>>8&255]^d[255&b]^r[w+2],S=o[R>>>24]^l[L>>16&255]^h[b>>8&255]^d[255&A]^r[w+3],L=y,b=E,A=T,R=S,w+=4;y=n[L>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^r[w],E=n[b>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&L]^r[w+1],T=n[A>>>24]<<24^n[R>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^r[w+2],S=n[R>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[w+3],v[t]=C(y^u),v[t+1]=C(S^f),v[t+2]=C(T^g),v[t+3]=C(E^m),u=I,f=k,g=D,m=P,t+=4}return v.buffer}}class Ns{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case xs:return"AES-CBC";case Ms:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class Bs{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(s){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==xs||16!==t.byteLength)return Re.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=ft(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Fs),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Ns(this.subtle,t,i)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Os(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)}).catch(r=>(Re.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Re.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Us=Math.pow(2,17);class $s{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(Ks(e));e.gap=!1}const l=this.loader=r?new r(i):new n(i),h=Gs(e);e.loader=l;const d=ys(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Us};e.stats=l.stats;const u={onSuccess:(t,s,i,r)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,i,r,n)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ye({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:t}))}};t&&(u.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(h,c,u)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Ks(e,t));const l=this.loader=r?new r(i):new n(i),h=Gs(e,t);e.loader=l;const d=ys(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Us};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ye({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new Hs({type:ne.NETWORK_ERROR,details:ae.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Gs(e,t=null){const s=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(se(r)&&se(n)){var a;let t=r,s=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(s=n+(16-e%16)),0!==r&&(i.resetIV=!0,t=r-16)}i.rangeStart=t,i.rangeEnd=s}var o;return i}function Ks(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:ne.MEDIA_ERROR,details:ae.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Hs(i)}class Hs extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Vs extends Ee{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ys{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}const qs={length:0,start:()=>0,end:()=>0};class js{static isBuffered(e,t){if(e){const s=js.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=js.getBuffered(e);return js.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=js.bufferedRanges(e);if(i.length)return js.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const n=r.length;if(n){const t=r[n-1].end;e[h].start-t<s?e[h].end>t&&(r[n-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n,a=0,o=t,l=t;for(let h=0;h<r.length;h++){const e=r[h].start,d=r[h].end;if(-1===i&&t>=e&&t<=d&&(i=h),t+s>=e&&t<d)o=e,l=d,a=l-t;else if(t+s<e){n=e;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||qs}catch(t){return Re.log("failed to get media.buffered",t),qs}}}const Ws=/\{\$([a-zA-Z0-9-_]+)\}/g;function zs(e){return Ws.test(e)}function Xs(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(Ws,t=>{const i=t.substring(2,t.length-1),r=null==s?void 0:s[i];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),t):r})}return t}function Qs(e,t,s){let i,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=e.get(i)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=t.NAME,r=t.VALUE;i in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Js(e,t,s){const i=t.IMPORT;if(s&&i in s){let t=e.variableList;t||(e.variableList=t={}),t[i]=s[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const Zs=/^(\d+)x(\d+)$/,ei=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ti{constructor(e,t){"string"==typeof e&&(e=ti.parseAttrList(e,t)),pe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Zs.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(ei.lastIndex=0;null!==(s=ei.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=Xs(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Re.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function si(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ii(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class ri{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){Re.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=pe(new ti({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);se(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Re.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(se(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&se(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 ni{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&se(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ai(e,t){return e.length===t.length&&!e.some((e,s)=>e!==t[s])}function oi(e,t){return!e&&!t||!(!e||!t)&&ai(e,t)}function li(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function hi(e){switch(e){case"AES-128":case"AES-256":return xs;case"AES-256-CTR":return Ms;default:throw new Error(`invalid full segment method ${e}`)}}function di(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ci(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function ui(e){const t=function(e,t,s){const i=e[t];e[t]=e[s],e[s]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function fi(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),i=e[e.length-1].split(",");if(2===i.length){const t="base64"===i[0],r=i[1];t?(e.splice(-1,1),s=di(r)):s=function(e){const t=ci(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}(r)}}return s}const gi="undefined"!=typeof self?self:void 0;var mi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},pi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function vi(e){switch(e){case pi.FAIRPLAY:return mi.FAIRPLAY;case pi.PLAYREADY:return mi.PLAYREADY;case pi.WIDEVINE:return mi.WIDEVINE;case pi.CLEARKEY:return mi.CLEARKEY}}function yi(e){switch(e){case mi.FAIRPLAY:return pi.FAIRPLAY;case mi.PLAYREADY:return pi.PLAYREADY;case mi.WIDEVINE:return pi.WIDEVINE;case mi.CLEARKEY:return pi.CLEARKEY}}function Ei(e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?[mi.FAIRPLAY,mi.WIDEVINE,mi.PLAYREADY,mi.CLEARKEY].filter(e=>!!t[e]):[];return!i[mi.WIDEVINE]&&s&&i.push(mi.WIDEVINE),i}const Ti=null!=gi&&null!=(Si=gi.navigator)&&Si.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Si;function Li(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(t)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=di(e).subarray(0,16);return ui(t),t}}return null}let bi={};class Ai{static clearKeyUriToKeyIdMap(){bi={}}static setKeyIdForUri(e,t){bi[e]=t}static addKeyIdForUri(e){const t=Object.keys(bi).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),bi[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!li(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(we(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ai(e.keyFormatVersions,this.keyFormatVersions)&&oi(e.iv,this.iv)&&oi(e.keyId,this.keyId)}isSupported(){if(this.method){if(li(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case pi.FAIRPLAY:case pi.WIDEVINE:case pi.PLAYREADY:case pi.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(li(this.method)){let t=this.iv;t||("number"!=typeof e&&(Re.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(e));return new Ai(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=bi[this.uri];if(e&&!ai(this.keyId,e)&&Ai.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=fi(this.uri);if(s)switch(this.keyFormat){case pi.WIDEVINE:if(this.pssh=s,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let i=0;for(;i+32<s;){const s=Tt(new DataView(e,i));t.push(s),i+=s.size}}return t}(s.buffer);if(e.length){var i;const t=e[0];this.keyId=null!=(i=t.kids)&&i.length?t.kids[0]:null}}this.keyId||(this.keyId=Ri(t));break;case pi.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Et(e,0,s),this.keyId=Li(s);break}default:{let e=s.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[pi.WIDEVINE];if(t)return t.keyId;return null}(t),e||(e=Ri(t),e||(e=bi[this.uri])),e&&(this.keyId=e,Ai.setKeyIdForUri(this.uri,e))}return this}}function Ri(e){const t=null==e?void 0:e[pi.PLAYREADY];if(t){const e=fi(t.uri);if(e)return Li(e)}return null}const Ii=/#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,ki=/#EXT-X-MEDIA:(.*)/g,Di=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),wi=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 _i{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Ue.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Di.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:zs(e)},i=[];if(Ii.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=Ii.exec(e));)if(r[1]){var n;const e=new ti(r[1],s),a=Xs(s,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:_i.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Fi(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Fi(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const e=r[3],i=r[4];switch(e){case"SESSION-DATA":{const e=new ti(i,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=Mi(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):Re.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":Qs(s,new ti(i,s),t);break;case"CONTENT-STEERING":{const e=new ti(i,s);s.contentSteering={uri:_i.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Oi(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(ki.lastIndex=0;null!==(i=ki.exec(e));){const e=new ti(i[1],s),n=e.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?_i.resolve(e.URI,t):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=_i.findGroup(s,f.groupId)||s[0];Ni(f,e,"audioCodec"),Ni(f,e,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new ni(t),h=l.fragments,d=[];let c,u,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,L=new qe(i,o),b=-1,A=!1,R=null;if(Pi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=zs(e),"#EXTM3U"!==(null==(a=Pi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Pi.exec(e));){A&&(A=!1,L=new qe(i,o),L.playlistOffset=y,L.setStart(y),L.sn=p,L.cc=E,T&&(L.bitrate=T),L.level=s,m&&(L.initSegment=m,m.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(L.setByteRange(R),R=null)));const e=c[1];if(e){L.duration=parseFloat(e);const t=(" "+c[2]).slice(1);L.title=t||null,L.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(se(L.duration)){L.playlistOffset=y,L.setStart(y),f&&$i(L,f,l),L.sn=p,L.level=s,L.cc=E,h.push(L);const e=(" "+c[3]).slice(1);L.relurl=Xs(l,e),Bi(L,S,d),S=L,y+=L.duration,p++,v=0,A=!0}}else{if(c=c[0].match(wi),!c){Re.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":S?L.setByteRange(r,S):L.setByteRange(r);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=r,L.tagList.push(["PROGRAM-DATE-TIME",r]),-1===b&&(b=h.length);break;case"PLAYLIST-TYPE":l.type&&Gi(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Gi(l,e,c):h.length>0&&Ki(l,e,c),p=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&Gi(l,e,c);const t=new ti(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(se(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);p+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Gi(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Gi(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Gi(l,e,c),l.live=!1;break;case"#":(r||a)&&L.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([e]);break;case"BITRATE":L.tagList.push([e,r]),T=1e3*parseInt(r),se(T)?L.bitrate=T:T=0;break;case"DATERANGE":{const e=new ti(r,l),t=new ri(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Re.warn(`Ignoring invalid DATERANGE tag: "${r}"`),L.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new ti(r,l);"IMPORT"in e?Js(l,e,n):Qs(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Gi(l,e,c):h.length>0&&Ki(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=Mi(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=pe({},f)),f[e.keyFormat]=e)}else Re.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Oi(r);break;case"MAP":{const e=new ti(r,l);if(L.duration){const t=new qe(i,o);Ui(t,e,s,f),m=t,L.initSegment=m,m.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime)}else{const t=L.byteRangeEndOffset;if(t){const e=L.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;Ui(L,e,s,f),m=L,A=!0}m.cc=E;break}case"SERVER-CONTROL":g&&Gi(l,e,c),g=new ti(r),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&&Gi(l,e,c);const t=new ti(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new ti(r,l),n=new je(i,L,o,s,t);e.push(n),L.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new ti(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new ti(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Re.warn(`line parsed but not handled: ${c}`)}}}S&&!S.relurl?(h.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(Bi(L,S,d),L.cc=E,l.fragmentHint=L,f&&$i(L,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const I=h.length,k=h[0],D=h[I-1];if(y+=l.skippedSegments*l.targetduration,y>0&&I&&D){l.averagetargetduration=y/I;const e=D.sn;l.endSN="initSegment"!==e?e:0,l.live||(D.endList=!0),b>0&&(!function(e,t){let s=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,b),k&&d.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&k&&Ci(d,l),l.endCC=E,l}}function Ci(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=xi(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function xi(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(t>=o||0===i){var a;if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length){for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function Mi(e,t,s){var i,r;const n=new ti(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Re.error(`Invalid IV: ${n.IV}`);const c=o?_i.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ai(a,c,d,u,l,n.KEYID)}function Oi(e){const t=new ti(e).decimalFloatingPoint("TIME-OFFSET");return se(t)?t:null}function Fi(e,t){let s=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const i=s.filter(t=>bt(t,e));i.length&&(t[`${e}Codec`]=i.map(e=>e.split("/")[0]).join(","),s=s.filter(e=>-1===i.indexOf(e)))}),t.unknownCodecs=s}function Ni(e,t,s){const i=t[s];i&&(e[s]=i)}function Bi(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ui(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function $i(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||i.push(e)}function Gi(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Ki(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function Hi(e,t){const s=t.startPTS;if(se(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Vi(e,t,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let o=s,l=i;const h=t.startPTS,d=t.endPTS;if(se(h)){const c=Math.abs(h-s);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):se(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(s,h),s=Math.min(s,h),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(i,d),i=Math.max(i,d),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=r,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,m=e.fragments;for(m[g]=t,f=g;f>0;f--)Hi(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Hi(m[f],m[f+1]);return e.fragmentHint&&Hi(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function Yi(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let d=r.length-1;d>=0;d--){const e=r[d].initSegment;if(e){i=e;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){const i=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=t.fragments[h]=r),r&&n){s(r,n,h,o);const i=r.relurl,a=n.relurl;if(i&&er(i,a))return void(t.playlistParsingError=qi(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=qi(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,(e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}se(e.startPTS)&&se(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=pe({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(e=>{const t=n[e],r=new ri(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Jt(i[e].attr)}"`)}),n}(e.dateRanges,t,s));const i=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&Bi(o[e],o[e-1],i);Ci(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=Xi(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?Vi(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):ji(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function qi(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function ji(e,t,s=!0){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Wi(t,a)}function Wi(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function zi(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function Xi(e,t,s){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t?i:t<e.startSN&&s&&s.sn===t?s:null)}function Qi(e,t,s){return e?Ji(e.partList,t,s):null}function Ji(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Zi(e){e.forEach((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function er(e,t){return!(e===t||!t)&&tr(e)!==tr(t)}function tr(e){return e.replace(/\?[^?]*$/,"")}function sr(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function ir(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function rr(e,t){const s=t.fragments;for(let i=0,r=s.length;i<r;i++)ir(s[i],e);t.fragmentHint&&ir(t.fragmentHint,e),t.alignedSliding=!0}function nr(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const s=Math.min(t.endCC,e.endCC),i=sr(t.fragments,s),r=sr(e.fragments,s);if(!i||!r)return;Re.log(`Aligning playlist at start of dicontinuity sequence ${s}`);rr(i.start-r.start,e)}function ar(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=sr(i,a),n=sr(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=sr(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;rr((l-o)/1e3-(n.start-r.start),e)}function or(e,t,s){lr(e,t,s),e.addEventListener(t,s)}function lr(e,t,s){e.removeEventListener(t,s)}const hr=function(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t},dr="STOPPED",cr="IDLE",ur="KEY_LOADING",fr="FRAG_LOADING",gr="FRAG_LOADING_WAITING_RETRY",mr="WAITING_TRACK",pr="PARSING",vr="PARSED",yr="ENDED",Er="ERROR",Tr="WAITING_INIT_PTS",Sr="WAITING_LEVEL";class Lr extends Vs{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=dr,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=js.bufferInfo(i||s,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${se(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===yr)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(o||r<a.start||i>a.end){const e=n>r;(n<i||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===cr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new $s(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Bs(e.config)}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===dr)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=dr}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=js.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return js.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;or(s,"seeking",this.onMediaSeeking),or(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===dr&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),lr(i,"seeking",this.onMediaSeeking),lr(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=dr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===fr||!this.fragCurrent&&t===pr)&&(this.fragmentTracker.removeFragment(s),this.state=cr):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(oe.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Is){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ks&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(oe.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&li(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,hi(r.method)).catch(e=>{throw t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e}).then(i=>{const r=self.performance.now();return t.trigger(oe.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==dr&&(this.state=cr),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(s.message),!e||e.mediaKeys?!1:(this.hls.trigger(oe.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?hr(js.getBuffered(s)):"(detached)"})`),Ye(e)){var i;if(e.type!==ue.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=cr)}const t=null==(i=this.levels)?void 0:i[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=cr}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),a=new Ys(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ur,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(oe.KEY_LOADED,e),this.state===ur&&(this.state=cr),e}),this.hls.trigger(oe.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Ye(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&Ye(e)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,s);if(o>-1){const l=r[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=fr,h=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,i)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,i).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(Ye(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),se(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=fr;const h=this.config.progressive&&e.type!==ue.SUBTITLE;let d;return d=h&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,i)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,h?i:void 0),a]).then(([e])=>(!h&&i&&i(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(oe.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then(i=>{o[t.index]=i;const n=i.part;this.hls.trigger(oe.FRAG_LOADED,i);const a=Qi(s.details,e.sn,t.index+1)||Ji(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ae.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ne.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(oe.ERROR,t)}else this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==pr)return void(this.fragCurrent||this.state===dr||this.state===Er||(this.state=cr));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===ue.SUBTITLE)return!1;if(t>=r.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Qi(o,r,n):null,h=l?l.fragment:Xi(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==pr)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=ft(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(oe.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!js.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=js.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!se(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=js.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return js.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=ue.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(s[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ds||s===ks&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(br(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(br(this.config)&&e.type!==ue.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let t=r.length;t--;){const s=r[t].interstitial;if(s.appendInPlace&&e.start>=s.startTime&&e.end<=s.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!se(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(cs(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=us(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=hs(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Ds||t===ks&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Ds?t:null}}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&se(r);if(n||!a&&!r){!function(e,t){e&&(nr(t,e),t.alignedSliding||ar(t,e),t.alignedSliding||t.skippedSegments||ji(e,t,!1))}(s,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&se(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ye(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===gr)||(this.state=cr)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===ae.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a)return void(this.state=Er);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===Ss.RetryRequest,f=c&&!a.resolved&&l===Ls.MoveAllAlternatesMatchingHost,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&Ye(i)&&!i.endList&&g&&!ms(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var m;const s=Ts(null==(m=t.response)?void 0:m.code),r=vs(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=gr,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===Ss.RemoveAlternatePermanently||(a.resolved=!0)}else this.state=o===Ss.SendAlternateToPenaltyBox?Sr:Er;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ts(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=cr)}reduceLengthAndFlushBuffer(e){if(this.state===pr||this.state===vr){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===ue.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dr&&(this.state=cr)}afterBufferFlushed(e,t,s){if(!e)return;const i=js.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===yr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dr&&(this.state=cr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i?0:Vi(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(oe.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var n;const t=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||t&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=vr,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(oe.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ue.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN).toFixed(3)}-${(null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function br(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Ar{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let r=0;r<e.length;r++){const t=e[r];s.set(t,i),i+=t.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Rr,Ir={exports:{}};var kr=(Rr||(Rr=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(Ir)),Ir.exports),Dr=_e(kr);const Pr="1.6.15",wr={};function _r(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Cr(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function xr(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function Mr(e,t){const s=t;let i=0;for(;Cr(e,t);){i+=10;i+=xr(e,t+6),_r(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(s,s+i)}function Or(e,t){return 255===e[t]&&240==(246&e[t+1])}function Fr(e,t){return 1&e[t+1]?7:9}function Nr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Br(e,t){return t+1<e.length&&Or(e,t)}function Ur(e,t){if(Br(e,t)){const s=Fr(e,t);if(t+s>=e.length)return!1;const i=Nr(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||Br(e,r)}return!1}function $r(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const c=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return Re.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(t,s,i,r);if(!n)return;pe(e,n)}}function Gr(e){return 9216e4/e}function Kr(e,t,s,i,r){const n=i+r*Gr(e.samplerate),a=function(e,t){const s=Fr(e,t);if(t+s<=e.length){const i=Nr(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Hr(e,t){return Cr(e,t)&&xr(e,t+6)+10<=e.length-t}function Vr(e,t=0,s=1/0){return function(e,t,s,i){const r=(n=e,n instanceof ArrayBuffer?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(u=e,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,h=(o+t)/a,d=Math.floor(Math.max(0,Math.min(h,l))),c=Math.floor(Math.min(d+Math.max(s,0),l));var u;return new i(r,d,c-d)}(e,t,s,Uint8Array)}function Yr(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=De(Vr(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=De(Vr(e.data,3+s,n));let o;var l;return o="--\x3e"===i?De(Vr(e.data,4+s+n)):(l=e.data.subarray(4+s+n))instanceof ArrayBuffer?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}function qr(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=De(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=De(e.data.subarray(t),!0);t+=s.length+1;const i=De(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=De(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Yr(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=De(e.data.subarray(t),!0);t+=s.length+1;const i=De(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=De(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function jr(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=xr(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}function Wr(e){let t=0;const s=[];for(;Cr(e,t);){const i=xr(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+i;for(;t+10<r;){const i=jr(e.subarray(t)),r=qr(i);r&&s.push(r),t+=i.size+10}_r(e,t)&&(t+=10)}return s}function zr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Xr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function Qr(e){const t=Wr(e);for(let s=0;s<t.length;s++){const e=t[s];if(zr(e))return Xr(e)}}let Jr=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Zr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class en{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=ft(this.cachedData,e),this.cachedData=null);let s,i=Mr(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?Qr(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&se(o))&&(this.basePTS=tn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Jr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else Hr(e,r)?(i=Mr(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Jr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=ft(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:Zr(),id3Track:a,textTrack:Zr()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Zr(),id3Track:this._id3Track,textTrack:Zr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const tn=(e,t,s)=>{if(se(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let sn=null;const rn=[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],nn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],an=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],on=[0,1,1,4];function ln(e,t,s,i,r){if(s+24>t.length)return;const n=hn(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function hn(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*rn[14*(3===s?3-i:3===i?3:4)+r-1],h=nn[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=an[s][i],u=on[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===sn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sn=e?parseInt(e[1]):0}return!!sn&&sn<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function dn(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function cn(e,t){return t+1<e.length&&dn(e,t)}function un(e,t){if(t+1<e.length&&dn(e,t)){const s=4,i=hn(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||cn(e,n)}return!1}const fn=(e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s};class gn extends en{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=mn(e,t,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}static probe(e){if(!e)return!1;const t=Mr(e,0);if(!t)return!1;const s=t.length;return 11===e[s]&&119===e[s+1]&&void 0!==Qr(t)&&fn(e,s)<16}}function mn(e,t,s,i,r){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const h=t[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(t[s+6]<<8|t[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}const pn=/\/emsg[-/]ID3/i;function vn(e,t){return se(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class yn{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Bs(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xs)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=yt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}}class En{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,d=1);d<i;)if(o=t[d++],r)if(1!==r)if(o)if(1===o){if(l=d-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=ft(s.data,t.subarray(0,l)),s.state=0))}d<i?(h=this.getNALuType(t,d),c=d,u=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,i),type:u,state:r};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=ft(s.data,t))}return e.naluState=r,a}}class Tn{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&Re.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Sn extends En{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 1:{let t=!1;n=!0;const r=i.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,vt(i.data,1,s.pts,t.samples);break;case 7:{var d,c;n=!0,o=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(d=e.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Tn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new Tn(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const E=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let L=[1,1];if(u()&&u()){switch(h()){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=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:L}}}class Ln extends En{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,vt(i.data,2,s.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=pe(e.params,this.readVPS(i.data)),this.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],i.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(i.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const s in t.params)e.params[s]=t.params[s]}this.pushParameterSet(e.sps,i.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(i.data);for(const s in t)e.params[s]=t[s]}this.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Tn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Tn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[];for(let Y=0;Y<s;Y++)v.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let Y=s;Y<8;Y++)t.readBits(2);for(let Y=0;Y<s;Y++)v[Y]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[Y]&&t.readUByte();t.readUEG();const E=t.readUEG();3==E&&t.skipBits(1);const T=t.readUEG(),S=t.readUEG(),L=t.readBoolean();let b=0,A=0,R=0,I=0;L&&(b+=t.readUEG(),A+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());const k=t.readUEG(),D=t.readUEG(),P=t.readUEG();for(let Y=t.readBoolean()?0:s;Y<=s;Y++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++){if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const w=t.readUEG();let _=0;for(let Y=0;Y<w;Y++){let e=!1;if(0!==Y&&(e=t.readBoolean()),e){Y===w&&t.readUEG(),t.readBoolean(),t.readUEG();let e=0;for(let s=0;s<=_;s++){const s=t.readBoolean();let i=!1;s||(i=t.readBoolean()),(s||i)&&e++}_=e}else{const e=t.readUEG(),s=t.readUEG();_=e+s;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let i=0;i<s;i++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let B=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(x=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),B=t.readBoolean(),B&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),i=t.readBoolean();let r=!1;(e||i)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){O=t.readBoolean();let s=!1;O||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(i)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let U=T,$=S;if(L){let e=1,t=1;1===E?e=t=2:2==E&&(e=2),U=T-e*A-e*b,$=S-t*I-t*R}const G=i?["A","B","C"][i]:"",K=a<<24|o<<16|l<<8|h;let H=0;for(let Y=0;Y<32;Y++)H=(H|(K>>Y&1)<<31-Y)>>>0;let V=H.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:U,height:$,pixelRatio:[x,M]}}readPPS(e){const t=new Tn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),i=t.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const bn=188;class An{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=An.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-bn)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=bn){if(71!==e[o]||t-o!==bn&&71!==e[o+bn]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-bn)+1)),r||(r=0===Rn(e,o)),r&&a>1&&(0===n&&a>2||o+bn>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=An.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=An.createTrack("audio",i),this._id3Track=An.createTrack("id3"),this._txtTrack=An.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=ft(this.remainderData,e)).length,this.remainderData=null),y<bn&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,An.syncOffset(e));y-=(y-E)%bn,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let L=E;L<y;L+=bn)if(71===e[L]){const t=!!(64&e[L+1]),i=Rn(e,L);let y;if((48&e[L+3])>>4>1){if(y=L+5+e[L+4],y===L+bn)continue}else y=L+4;switch(i){case h:t&&(d&&(r=wn(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(y,L+bn)),d.size+=L+bn-y);break;case c:if(t){if(f&&(r=wn(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(y,L+bn)),f.size+=L+bn-y);break;case u:t&&(g&&(r=wn(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(y,L+bn)),g.size+=L+bn-y);break;case 0:t&&(y+=e[y]+1),v=this._pmtId=In(e,y);break;case v:{t&&(y+=e[y]+1);const i=kn(e,y,this.typeSupported,s,this.observer,this.logger);h=i.videoPid,h>0&&(n.pid=h,n.segmentCodec=i.segmentVideoCodec),c=i.audioPid,c>0&&(a.pid=c,a.segmentCodec=i.segmentAudioCodec),u=i.id3Pid,u>0&&(o.pid=u),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&&Dn(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=wn(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=wn(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=wn(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new yn(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new Sn:"hevc"===e&&(this.videoParser=new Ln))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,r=i.sample.unit.byteLength;if(-1===t)o=ft(i.sample.unit,o);else{const n=r-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Br(o,r);r++);if(r!==s){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Dn(this.observer,new Error(e),t,this.logger),!t)return}if($r(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Gr(e.samplerate);a=i.sample.pts+t}}let l,h=0;for(;r<n;){if(l=Kr(e,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!Br(o,r);r++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(cn(s,n)){const t=ln(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=mn(e,s,o,i,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=pe({},t,{type:this._videoTrack?Jr.emsg:Jr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Rn(e,t){return((31&e[t+1])<<8)+e[t+2]}function In(e,t){return(31&e[t+10])<<8|e[t+11]}function kn(e,t,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Rn(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Pn("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){Pn("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.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){Pn("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let i=t+5,r=l;for(;r>2;){if(106===e[i])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[i+1]+2;i+=t,r-=t}}break;case 194:case 135:return Dn(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Dn(e,t,s,i){i.warn(`parsing error: ${t.message}`),e.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function Pn(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function wn(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ft(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class _n{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Cn=Math.pow(2,32)-1;class xn{static init(){let e;for(e in xn.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:[]},xn.types)xn.types.hasOwnProperty(e)&&(xn.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);xn.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);xn.STTS=xn.STSC=xn.STCO=r,xn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),xn.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]);xn.FTYP=xn.box(xn.types.ftyp,n,o,n,a),xn.DINF=xn.box(xn.types.dinf,xn.box(xn.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return xn.box(xn.types.hdlr,xn.HDLR_TYPES[e])}static mdat(e){return xn.box(xn.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Cn+1)),i=Math.floor(t%(Cn+1));return xn.box(xn.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return xn.box(xn.types.mdia,xn.mdhd(e.timescale||0,e.duration||0),xn.hdlr(e.type),xn.minf(e))}static mfhd(e){return xn.box(xn.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?xn.box(xn.types.minf,xn.box(xn.types.smhd,xn.SMHD),xn.DINF,xn.stbl(e)):xn.box(xn.types.minf,xn.box(xn.types.vmhd,xn.VMHD),xn.DINF,xn.stbl(e))}static moof(e,t,s){return xn.box(xn.types.moof,xn.mfhd(e),xn.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=xn.trak(e[t]);return xn.box.apply(null,[xn.types.moov,xn.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(xn.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=xn.trex(e[t]);return xn.box.apply(null,[xn.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Cn+1)),i=Math.floor(t%(Cn+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,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 xn.box(xn.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return xn.box(xn.types.sdtp,s)}static stbl(e){return xn.box(xn.types.stbl,xn.stsd(e),xn.box(xn.types.stts,xn.STTS),xn.box(xn.types.stsc,xn.STSC),xn.box(xn.types.stsz,xn.STSZ),xn.box(xn.types.stco,xn.STCO))}static avc1(e){let t,s,i,r=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=xn.box(xn.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return xn.box(xn.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,xn.box(xn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xn.box(xn.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return xn.box(xn.types.mp4a,xn.audioStsd(e),xn.box(xn.types.esds,xn.esds(e)))}static mp3(e){return xn.box(xn.types[".mp3"],xn.audioStsd(e))}static ac3(e){return xn.box(xn.types["ac-3"],xn.audioStsd(e),xn.box(xn.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return xn.box(xn.types.stsd,xn.STSD,xn.mp4a(e));if("ac3"===t&&e.config)return xn.box(xn.types.stsd,xn.STSD,xn.ac3(e));if("mp3"===t&&"mp3"===e.codec)return xn.box(xn.types.stsd,xn.STSD,xn.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return xn.box(xn.types.stsd,xn.STSD,xn.avc1(e));if("hevc"===t&&e.vps)return xn.box(xn.types.stsd,xn.STSD,xn.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Cn+1)),a=Math.floor(s%(Cn+1));return xn.box(xn.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const s=xn.sdtp(e),i=e.id,r=Math.floor(t/(Cn+1)),n=Math.floor(t%(Cn+1));return xn.box(xn.types.traf,xn.box(xn.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),xn.box(xn.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),xn.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,xn.box(xn.types.trak,xn.tkhd(e),xn.mdia(e))}static trex(e){const t=e.id;return xn.box(xn.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return xn.box(xn.types.trun,n)}static initSegment(e){xn.types||xn.init();const t=xn.moov(e);return ft(xn.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let r=i.length;for(let u=0;u<s.length;u+=1){r+=3;for(let e=0;e<s[u].length;e+=1)r+=2+s[u][e].length}const n=new Uint8Array(r);n.set(i,0),r=i.length;const a=s.length-1;for(let u=0;u<s.length;u+=1){n.set(new Uint8Array([32+u|(u===a?128:0),0,s[u].length]),r),r+=3;for(let e=0;e<s[u].length;e+=1)n.set(new Uint8Array([s[u][e].length>>8,255&s[u][e].length]),r),r+=2,n.set(s[u][e],r),r+=s[u][e].length}const o=xn.box(xn.types.hvcC,n),l=e.width,h=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return xn.box(xn.types.hvc1,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,l>>8&255,255&l,h>>8&255,255&h,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]),o,xn.box(xn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xn.box(xn.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}xn.types=void 0,xn.HDLR_TYPES=void 0,xn.STTS=void 0,xn.STSC=void 0,xn.STCO=void 0,xn.STSZ=void 0,xn.VMHD=void 0,xn.SMHD=void 0,xn.STSD=void 0,xn.FTYP=void 0,xn.DINF=void 0;function Mn(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}function On(e,t=!1){return Mn(e,1e3,1/9e4,t)}function Fn(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}let Nn,Bn=null,Un=null;function $n(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Gn extends Ee{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===Bn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bn=e?parseInt(e[1]):0}if(null===Un){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Un=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Fn(t):t} > ${e?Fn(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=Kn(r,s),n=r-e),n>0?e:r},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.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 e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(L=e.pixelRatio)?void 0:L[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(A=e.pixelRatio)?void 0:A[1]))||!e&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.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 s=this.getVideoStartPts(t.samples),i=(Kn(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||T||o===ue.AUDIO?m:void 0),T){const i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,m,s,i)}}else T&&(l=this.remuxVideo(t,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Hn(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Vn(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Kn(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(h=d=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):xn.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:h=d=this.computeInitPts(r[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:xn.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Kn(n[0].dts,e),i=this.computeInitPts(t,c,s,"video"),r=this.computeInitPts(e,c,s,"video");d=Math.min(d,i),h=Math.min(h,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${h/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/c} (${h}/${c}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:c,trackId:g},this._initDTS={baseTime:d,timescale:c,trackId:g}):h=c=void 0,{tracks:o,initPTS:h,timescale:c,trackId:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let d,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const e=h+t*r,i=n[0].pts-Kn(n[0].dts,n[0].pts);Bn&&null!==u&&Math.abs(e-i-(u+h))<15e3?s=!0:u=e-i-h}const y=u+h;for(let O=0;O<o;O++){const e=n[O];e.pts=Kn(e.pts,y),e.dts=Kn(e.dts,y),e.dts<n[O>0?O-1:O].dts&&(v=!0)}v&&n.sort(function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i}),d=n[0].dts,c=n[n.length-1].dts;const E=c-d,T=E?Math.round(E/(o-1)):g||e.inputTimeScale/30;if(s){const s=d-y,i=s>T,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${On(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${On(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||y>=n[0].pts||Bn)){d=y;const e=n[0].pts-s;if(i)n[0].dts=d,n[0].pts=e;else{let t=!0;for(let i=0;i<n.length&&!(n[i].dts>e&&t);i++){const e=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;t=s<=n[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${On(e,!0)}/${On(d,!0)}, delta: ${On(s,!0)} ms`)}}d=Math.max(0,d);let S=0,L=0,b=d;for(let O=0;O<o;O++){const e=n[O],t=e.units,s=t.length;let i=0;for(let r=0;r<s;r++)i+=t[r].data.length;L+=i,S+=s,e.length=i,e.dts<b?(e.dts=b,b+=T/4|0||1):b=e.dts,m=Math.min(e.pts,m),p=Math.max(e.pts,p)}c=n[o-1].dts;const A=L+4*S+8;let R;try{R=new Uint8Array(A)}catch(M){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:A,reason:`fail allocating video mdat ${A}`})}const I=new DataView(R.buffer);I.setUint32(0,A),R.set(xn.types.mdat,4);let k=!1,D=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,w=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let O=0;O<o;O++){const e=n[O],t=e.units;let s,l=0;for(let i=0,r=t.length;i<r;i++){const e=t[i],s=e.data,r=e.data.byteLength;I.setUint32(f,r),f+=4,R.set(s,f),f+=r,l+=4+r}if(O<o-1)g=n[O+1].dts-e.dts,s=n[O+1].pts-e.pts;else{const t=this.config,a=O>0?e.dts-n[O-1].dts:T;if(s=O>0?e.pts-n[O-1].pts:T,t.stretchShortVideoTrack&&null!==this.nextAudioTs){const s=Math.floor(t.maxBufferHole*r),n=(i?m+i*r:this.nextAudioTs+h)-e.pts;n>s?(g=n-a,g<0?g=a:k=!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 d=Math.round(e.pts-e.dts);D=Math.min(D,g),w=Math.max(w,g),P=Math.min(P,s),_=Math.max(_,s),a.push($n(e.key,g,l,d))}if(a.length)if(Bn){if(Bn<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Un&&_-P<w-D&&T/w<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,s=a.length;t<s;t++){const i=e+a[t].duration,r=e+a[t].cts;if(t<s-1){const e=i+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:T;a[t].cts=0,e=i}}g=k||!g?T:g;const C=c+g;this.nextVideoTs=u=C-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const x={data1:xn.moof(e.sequenceNumber++,d,pe(e,{samples:a})),data2:R,startPTS:(m-h)/r,endPTS:(p+g-h)/r,startDTS:(d-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,x}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=d?0:8,m=this.nextAudioTs||-1;const p=h.baseTime*n/h.timescale,v=p+t*n;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(v-(m+p))<9e3||Math.abs(Kn(f[0].pts,v)-(m+p))<20*l),f.forEach(function(e){e.pts=Kn(e.pts,v)}),!s||m<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:i&&!u?Math.max(0,v-p):f[0].pts-p}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=m+p;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(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>=t*l&&h<1e4&&u){let t=Math.round(o/l);for(i=a-t*l;i<0&&t&&l;)t--,i+=l;0===s&&(this.nextAudioTs=m=i-p),this.warn(`Injecting ${t} audio frames @ ${((i-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=_n.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(s,0,{unit:t,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,T=null,S=0,L=f.length;for(;L--;)S+=f[L].unit.byteLength;for(let w=0,_=f.length;w<_;w++){const t=f[w],i=t.unit;let r=t.pts;if(null!==T){c[w-1].duration=Math.round((r-T)/a)}else{if(s&&"aac"===e.segmentCodec&&(r=m+p),E=r,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(P){return void this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MUX_ERROR,details:ae.REMUX_ALLOC_ERROR,fatal:!1,error:P,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(y.buffer).setUint32(0,S),y.set(xn.types.mdat,4)}}y.set(i,g);const n=i.byteLength;g+=n,c.push($n(!0,o,n,0)),T=r}const b=c.length;if(!b)return;const A=c[c.length-1];m=T-p,this.nextAudioTs=m+a*A.duration;const R=d?new Uint8Array(0):xn.moof(e.sequenceNumber++,E/a,pe({},e,{samples:c}));e.samples=[];const I=(E-p)/n,k=this.nextAudioTs/n,D={data1:R,data2:y,startPTS:I,endPTS:k,startDTS:I,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,D}}function Kn(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function Hn(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let o=0;o<r;o++){const r=e.samples[o];r.pts=Kn(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=Kn(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Vn(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=Kn(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function Yn(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function qn(e,t,s){const i=e.codec;if(i&&i.length>4)return i;if(t===Ge){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return _t(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{Nn=self.performance.now.bind(self.performance)}catch(ph){Nn=Date.now}const jn=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Zr("video",1),n=this.audioTrack=Zr("audio",1),a=this.txtTrack=Zr("text",1);if(this.id3Track=Zr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=nt(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=Qe.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=et(e,s);if(i>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=ft(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=it(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(s);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=gt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=gt(e,t),{videoTrack:t,audioTrack:Zr(),id3Track:i,textTrack:Zr()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=it(e.samples,["emsg"]);i&&i.forEach(e=>{const i=function(e){const t=e[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==Je(e.subarray(h,h+1));)s+=Je(e.subarray(h,h+1)),h+=1;for(s+=Je(e.subarray(h,h+1)),h+=1;"\0"!==Je(e.subarray(h,h+1));)i+=Je(e.subarray(h,h+1)),h+=1;i+=Je(e.subarray(h,h+1)),h+=1,r=et(e,12),n=et(e,16),o=et(e,20),l=et(e,24),h=28}else if(1===t){h+=4,r=et(e,h),h+=4;const t=et(e,h);h+=4;const n=et(e,h);for(h+=4,a=2**32*t+n,ie(a)||(a=Number.MAX_SAFE_INTEGER,Re.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=et(e,h),h+=4,l=et(e,h),h+=4;"\0"!==Je(e.subarray(h,h+1));)s+=Je(e.subarray(h,h+1)),h+=1;for(s+=Je(e.subarray(h,h+1)),h+=1;"\0"!==Je(e.subarray(h,h+1));)i+=Je(e.subarray(h,h+1)),h+=1;i+=Je(e.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(pn.test(i.schemeIdUri)){const e=vn(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Jr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=vn(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:Jr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends Ee{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=nt(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&ct(e,(e,t)=>{const i=e.subarray(8,24);i.some(e=>0!==e)||(Re.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Pe(i)} -> ${Pe(s)}`),e.set(s,8))})}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(s=qn(r,Ge,this)),n&&(i=qn(n,Ke,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};se(h)||(h=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return d;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,s){const i={},r=it(e,["moof","traf"]);for(let n=0;n<r.length;n++){const e=r[n],a=it(e,["tfhd"])[0],o=et(a,4),l=t[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=i[o],d=it(e,["tfdt"])[0];if(d){const e=d[0];let t=et(d,4);1===e&&(t===ze?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=ze+1,t+=et(d,8))),se(t)&&(!se(h.start)||t<h.start)&&(h.start=t)}const c=l.default,u=et(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=et(a,2&u?12:8));const g=it(e,["trun"]);let m=h.start||0,p=0,v=f;for(let t=0;t<g.length;t++){const e=g[t],s=et(e,4),i=h.sampleCount;h.sampleCount+=s;const r=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],d=8&e[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&e[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=i),c+=4,a?(v=et(e,c),c+=4):v=f,o&&(c+=4),d&&(c+=4),m+=v,p+=v,u--);u--;)a?(v=et(e,c),c+=4):v=f,o&&(c+=4),l&&(1&e[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=m),c+=4),d&&(c+=4),m+=v,p+=v;!p&&f&&(p+=f*s)}h.duration+=p}if(!Object.keys(i).some(e=>i[e].duration)){let t=1/0,s=0;const r=it(e,["sidx"]);for(let e=0;e<r.length;e++){const i=rt(r[e]);if(null!=i&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);const e=i.references.reduce((e,t)=>e+t.info.duration||0,0);s=Math.max(s,e+i.earliestPresentationTime/i.timescale)}}s&&se(s)&&Object.keys(i).forEach(e=>{i[e].duration||(i[e].duration=s*i[e].timescale-i[e].start)})}return i}(c,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Yn(p,1/0),y=Yn(m,1/0),E=Yn(p,0,!0),T=Yn(m,0,!0);let S=r,L=0;const b=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),A=b?m:p;if(A){const e=A.timescale,t=A.start-r*e,s=b?f.audio.id:f.video.id;S=A.start/e,L=b?T-y:E-v,!n&&l||!function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>r}(l,S,r,L)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${t}/${e}) trackId: ${s}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=S,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const R=S-l.baseTime/l.timescale,I=R+L;L>0?this.lastEndTime=I:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!f.audio,D=!!f.video;let P="";k&&(P+="audio"),D&&(P+="video");const w={data1:c,startPTS:R,startDTS:R,endPTS:I,endDTS:I,type:P,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=k&&!D?w:void 0,d.video=D?w:void 0;const _=null==p?void 0:p.sampleCount;if(_){const e=p.keyFrameIndex,t=-1!==e;w.nb=_,w.dropped=0===e||this.isVideoContiguous?0:t?e:_,w.independent=t,w.firstKeyFrame=e,t&&p.keyFrameStart&&(w.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${_} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return d.initSegment=u,d.id3=Hn(s,r,l,l),i.samples.length&&(d.text=Vn(i,r,l)),d}}},{demux:An,remux:Gn},{demux:class extends en{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Mr(e,0);let i=(null==s?void 0:s.length)||0;if(un(e,i))return!1;for(let r=e.length;i<r;i++)if(Ur(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Or(e,t)&&Nr(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){$r(e,this.observer,t,s,e.manifestCodec);const i=Kr(e,t,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:Gn},{demux:class extends en{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Mr(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==Qr(t)&&fn(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(un(e,s))return Re.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return dn(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return ln(e,t,s,this.basePTS,this.frameIndex)}},remux:Gn}];jn.splice(2,0,{demux:gn,remux:Gn});class Wn{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Nn();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(e,t){let s=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t);return s}(n,t);if(E&&li(E.method)){const e=this.getDecrypter(),t=hi(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,t).then(e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t}),this.decryptionPromise;{let i=e.softwareDecrypt(n,E.key.buffer,E.iv.buffer,t);if(s.part>-1){const t=e.flush();i=t?t.buffer:t}if(!i)return r.executeEnd=Nn(),zn(s);n=new Uint8Array(i)}}const T=this.needsProbing(h,d);if(T){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(oe.ERROR,oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Nn(),zn(s)}(h||d||f||T)&&this.resetInitSegment(y,g,m,v,t),(h||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,s);this.asyncResult=Xn(S);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=Nn(),S}flush(e){const t=e.transmuxing;t.executeStart=Nn();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Nn();const s=[zn(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return Xn(h)?(this.asyncResult=!0,h.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===ue.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Nn()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,i),a.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let d=0,c=jn.length;d<c;d++){var n;if(null!=(n=jn[d].demux)&&n.probe(e,this.logger)){r=jn[d];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(s,t,i,this.logger)),a&&a instanceof h||(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Bs(this.config)),e}}const zn=e=>({remuxResult:{},chunkMeta:e});function Xn(e){return"then"in e&&e.then instanceof Function}class Qn{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Jn{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Zn=0;class ea{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Zn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===oe.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Dr,this.observer.on(oe.FRAG_DECRYPTED,n),this.observer.on(oe.ERROR,n);const a=Ot(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=wr[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return wr[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=wr[Pr];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return wr[Pr]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Jt(r)})}catch(ph){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,ph),this.terminateWorker(),this.error=null,this.transmuxer=new Wn(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Wn(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Zn++;const t=this.hls.config,s=Ot(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Jt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=wr[e||Pr];if(t&&1===t.clientCount--){const{worker:s,objectURL:i}=t;delete wr[e||Pr],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.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===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!T&&L||(n.stats.parsing.start=b);const A=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),R=new Jn(v,L,o,y,g,A);if(!L||v||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===ue.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 e=new Qn(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,R);Xn(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);Xn(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class ta extends Lr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",ue.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(oe.BUFFER_RESET,this.onBufferReset,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(oe.BUFFER_RESET,this.onBufferReset,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){if(s===ue.MAIN){const e=t.cc,s=this.fragCurrent;if(this.initPTS[e]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===Tr){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==e)&&this.syncWithAnchor(t,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==e?(s.abortRequests(),this.syncWithAnchor(t,s)):this.state===cr&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(t&&(null==i?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=us(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===cr&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=dr);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=cr):this.state=mr,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case cr:this.doTickIdle();break;case mr:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Tr}break}case gr:this.checkRetryDate();break;case Tr:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=fr;const e={frag:t,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=cr}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=mr,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ge,ue.AUDIO));const h=this.getFwdBufferInfo(l,ue.AUDIO);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(oe.BUFFER_EOS,{type:"audio"}),void(this.state=yr);const d=h.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:h.end;if(this.switchingTrack&&i){const e=g;o.PTSKnown&&e<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(d>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,h,ue.MAIN,c)),!p)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Ye(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ds&&(this.mainFragLoading=v=null),v&&Ye(v))){if(p.start>v.end){const e=this.fragmentTracker.getFragAtPos(m,ue.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new zt(e))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==dr&&(this.setInterval(100),this.state=cr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(oe.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=t;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dr&&(this.state=mr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||null!=(s=h.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(h.details)d=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(nr(r,l),r.alignedSliding||ar(r,l),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(oe.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==mr||this.waitForCdnTuneIn(r)||(this.state=cr),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new ea(this.hls,ue.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=i?i.index:-1,n=-1!==t,a=new Ys(s.level,s.sn,s.stats.chunkCount,r.byteLength,t,n);c.push(r,f,d,"",s,i,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ar,complete:!1};e.push(new Uint8Array(r)),this.state!==dr&&(this.state=Tr)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ue.MAIN&&Ye(t.frag)&&(this.mainFragLoading=t,this.state===cr&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type===ue.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Ye(s)){this.fragPrevious=s;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(oe.AUDIO_TRACK_SWITCHED,ye({},e)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==ue.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var s;if(t.fatal)this.state=Er;else switch(t.details){case ae.FRAG_GAP:case ae.FRAG_PARSING_ERROR:case ae.FRAG_DECRYPT_ERROR:case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ue.AUDIO,t);break;case ae.AUDIO_TRACK_LOAD_ERROR:case ae.AUDIO_TRACK_LOAD_TIMEOUT:case ae.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==mr||(null==(s=t.context)?void 0:s.type)!==de||(this.state=cr);break;case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ae.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ae.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Ke&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ke){this.flushing=!1,this.bufferFlushed=!0,this.state===yr&&(this.state=cr);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,ue.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=pr,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,e,n),i.trigger(oe.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Ge]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Ge,e,t,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=pe({id:s,frag:o,details:d},f);i.trigger(oe.FRAG_PARSING_METADATA,e)}if(u){const e=pe({id:s,frag:o,details:d},u);i.trigger(oe.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,s,i){if(this.state!==pr)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=ue.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(oe.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(oe.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||i===Rs||i===ks)if(Ye(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Tr;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&ar(t.details,s)}else super.loadFragment(e,t,s);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;is({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},e,rs)||(as(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(oe.AUDIO_TRACK_SWITCHED,ye({},e))}}class sa extends Ee{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let n=-1;for(let s=0;s<i.length;s++){const a=i[s];let o;try{o=new self.URL(a.URI,t.url).href}catch(r){this.warn(`Could not construct new URL for Rendition Report: ${r}`),o=a.URI||""}if(o===e){n=s;break}o===e.substring(0,o.length)&&(n=s)}if(-1!==n){const e=i[n],r=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&jt(s);return new Wt(r,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const e=Math.max(o||0,0);i.appliedTimelineOffset=e,i.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(i.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){Yi(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void s.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=zi(i,1e3*(i.edge-d));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=e?0:l):(f=r,g=e?l+1:i.maxPartIndex):f=a+1;const d=i.age,c=d+i.ageHeader;let m=Math.min(c-i.partTarget,1.5*i.targetduration);if(m>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${i.age}`),m=0;else{const e=Math.floor(m/i.targetduration);if(f+=e,void 0!==g){g+=Math.round(m%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${m} skip sn ${e} to part ${g}`)}i.tuneInGoal=m}if(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g),e||!h)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,i){let r=jt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=qt.No),new Wt(s,i,r)}checkRetry(e){const t=e.details,s=fs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Ss.RetryRequest||!i.resolved&&r===Ss.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=vs(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}function ia(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!ra(e[s].attrs,t[s].attrs))return!1;return!0}function ra(e,t,s){const i=e["STABLE-RENDITION-ID"];return i&&!s?i===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>e[s]!==t[s])}function na(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class aa extends sa{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(oe.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!s||-1!==s.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const s=ss(t,e,rs);if(s>-1)r=e[s];else{const e=ss(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(oe.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==de||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&is(e,i,rs))return i;const r=ss(e,this.tracksInGroup,rs);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(i){let i=t.loadLevel;-1===i&&(i=t.firstAutoLevel);const r=function(e,t,s,i,r){const n=t[i],a=t.reduce((e,t,s)=>{const i=t.uri;return(e[i]||(e[i]=[])).push(s),e},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ns(t,i,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const i=t.audioGroups,n=s.filter(e=>!i||-1!==i.indexOf(e.groupId));return ss(e,n,r)>-1});return d>-1?d:ns(t,i,t=>{const i=t.audioGroups,n=s.filter(e=>!i||-1!==i.indexOf(e.groupId));return ss(e,n,r)>-1})}(e,t.levels,s,i,rs);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=ss(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(oe.AUDIO_TRACK_SWITCHING,ye({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||is(e,i,rs)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(is({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],rs))return e}for(let l=0;l<t.length;l++){const s=t[l];if(ra(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const s=t[l];if(ra(e.attrs,s.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&as(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(oe.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class oa{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(i){var s;if(r.onError(i),null===this.queues||null===this.tracks)return;const t=null==(s=this.tracks[e])?void 0:s.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const la=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ha="HlsJsTrackRemovedError";class da extends Error{constructor(e){super(e),this.name=ha}}class ca extends Ee{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(oe.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=Ie(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.BUFFER_RESET,this.onBufferReset,this),e.on(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.BUFFER_EOS,this.onBufferEos,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.FRAG_PARSED,this.onFragParsed,this),e.on(oe.FRAG_CHANGED,this.onFragChanged,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.BUFFER_RESET,this.onBufferReset,this),e.off(oe.BUFFER_APPENDING,this.onBufferAppending,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.BUFFER_EOS,this.onBufferEos,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.FRAG_PARSED,this.onFragParsed,this),e.off(oe.FRAG_CHANGED,this.onFragChanged,this),e.off(oe.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?pe(s,i.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(s[t]=pe({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Ie(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&n instanceof t,ua(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(r){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&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: ${Jt(s,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${Jt(i,(e,t)=>"initSegment"===e?void 0:t)}}`),!ke(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(oe.MEDIA_DETACHING,{}),this.onMediaAttaching(oe.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=js.getBuffered(e);i.detectEvictedFragments(t,s,r,null,!0)}const n=fa(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(ph){this.warn(`onMediaDetaching: ${ph.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&ua(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(oe.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(ph){this.warn(`onBufferReset ${e}`,ph)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fa(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new oa(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!i[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=Ct(m,p),y=null==v?void 0:v.replace(la,"$1");let E=Ct(o,l);const T=null==(r=E)?void 0:r.replace(la,"$1");E&&v&&y!==T&&("audio"===e.slice(0,5)&&(E=_t(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(e,h,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,ue.MAIN))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>i||null!=t&&t.buffer&&js.isBuffered(t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,ue.MAIN))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();d.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=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||js.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!js.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const T=(o||a).start,S={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,T,.1,r,c,u):void 0!==h&&se(h)&&this.updateTimestampOffset(t,h,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);const t={};this.sourceBuffers.forEach(([e,s])=>{e&&(t[e]=js.getBuffered(s))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(oe.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:ne.MEDIA_ERROR,parent:a.type,details:ae.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},i=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)s.details=ae.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=As(!0);else if(e.name===ha&&0===this.sourceBufferCount)s.errorAction=As(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger(oe.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===ue.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[He]?r.push("audiovideo"):(n[Ge]&&r.push("audio"),n[Ke]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.hls.trigger(oe.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type})},r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(oe.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ae.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;se(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(se(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=i.frontBufferFlushThreshold;if(se(o)&&o>0){const e=Math.max(i.maxBufferLength,o),t=Math.max(e,n),s=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([e,t])=>{if(t){const r=js.getBuffered(t);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger(oe.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(oe.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([t,i])=>{if(i){const r=js.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return se(r)?{duration:r}:null;const n=this.media.duration;return i>(se(s.duration)?s.duration:0)&&i>n||!se(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==e&&(se(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Jt(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(oe.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const e=this.getTrackCodec(o,a),n=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${Jt(o)}`);try{const e=s.addSourceBuffer(n),i=fa(a),r=[a,e];t[i]=r,o.buffer=e}catch(r){var i;return this.error(`error while trying to add sourceBuffer: ${r.message}`),this.shiftAndExecuteNext(a),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[a],void this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:r,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&At(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)bt(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=Ct(i,e.levelCodec);return r?"audio"===t.slice(0,5)?_t(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger(oe.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=se(i.duration)?i.duration:1/0,l=se(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),a.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new da(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(e=>{s.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}function ua(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function fa(e){return"audio"===e?1:0}class ga{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(oe.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&se(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((t,s)=>this.isLevelAllowed(t)&&s<=e);return this.clientRect=null,ga.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;const i=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let r=e.length-1;const n=Math.max(t,s);for(let a=0;a<e.length;a+=1){const t=e[a];if((t.width>=n||t.height>=n)&&i(t,e[a+1])){r=a;break}}return r}}const ma={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},pa={HLS:"h"};class va{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof va?e:new va(e))),this.value=e,this.params=t}}function ya(e,t,s,i){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}function Ea(e,t,s){return ya("serialize",e,t,s)}class Ta{constructor(e){this.description=e}}const Sa="Bare Item";function La(e){if(!1===ArrayBuffer.isView(e))throw Ea(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function ba(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Ea(e,"Integer");return e.toString()}function Aa(e,t){if(e<0)return-Aa(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}function Ra(e){const t=Aa(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ea(e,"Decimal");const s=t.toString();return s.includes(".")?s:`${s}.0`}const Ia=/[\x00-\x1f\x7f]+/;function ka(e){const t=(s=e).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Ea(t,"Token");return t}function Da(e){switch(typeof e){case"number":if(!se(e))throw Ea(e,Sa);return Number.isInteger(e)?ba(e):Ra(e);case"string":return function(e){if(Ia.test(e))throw Ea(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return ka(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Ea(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${ba(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return La(e);if(e instanceof Ta)return ka(e);default:throw Ea(e,Sa)}}function Pa(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Ea(e,"Key");return e}function wa(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${Pa(e)}`:`;${Pa(e)}=${Da(t)}`).join("")}function _a(e){return e instanceof va?`${Da(e.value)}${wa(e.params)}`:Da(e)}function Ca(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Ea(e,"Dict");const s=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(s).map(([e,t])=>{t instanceof va==!1&&(t=new va(t));let s=Pa(e);var i;return!0===t.value?s+=wa(t.params):(s+="=",Array.isArray(t.value)?s+=`(${(i=t).value.map(_a).join(" ")})${wa(i.params)}`:s+=_a(t)),s}).join(`,${i}`)}function xa(e,t){return Ca(e,t)}const Ma="CMCD-Object",Oa="CMCD-Request",Fa="CMCD-Session",Na="CMCD-Status",Ba={br:Ma,ab:Ma,d:Ma,ot:Ma,tb:Ma,tpb:Ma,lb:Ma,tab:Ma,lab:Ma,url:Ma,pb:Oa,bl:Oa,tbl:Oa,dl:Oa,ltc:Oa,mtp:Oa,nor:Oa,nrr:Oa,rc:Oa,sn:Oa,sta:Oa,su:Oa,ttfb:Oa,ttfbb:Oa,ttlb:Oa,cmsdd:Oa,cmsds:Oa,smrt:Oa,df:Oa,cs:Oa,ts:Oa,cid:Fa,pr:Fa,sf:Fa,sid:Fa,st:Fa,v:Fa,msd:Fa,bs:Na,bsd:Na,cdn:Na,rtp:Na,bg:Na,pt:Na,ec:Na,e:Na},Ua=Oa;function $a(e,t){const s={};if(!e)return s;const i=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var s;return null===(s=n[t])||void 0===s||s.forEach(s=>e[s]=t),e},{})):{};var n;return i.reduce((t,s)=>{var i;const n=Ba[s]||r[s]||Ua;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[s]=e[s],t},s)}const Ga="event";const Ka=e=>Math.round(e),Ha=(e,t)=>Array.isArray(e)?e.map(e=>Ha(e,t)):e instanceof va&&"string"==typeof e.value?new va(Ha(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const s=new URL(e),i=new URL(t);if(s.origin!==i.origin)return e;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),Va=e=>100*Ka(e/100),Ya={br:Ka,d:Ka,bl:Va,dl:Va,mtp:Va,nor:(e,t)=>{let s=e;return t.version>=2&&(e instanceof va&&"string"==typeof e.value?s=new va([e]):"string"==typeof e&&(s=[e])),Ha(s,t)},rtp:Va,tb:Ka},qa="request",ja="response",Wa=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],za=["e"],Xa=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Qa(e){return Xa.test(e)}const Ja=["d","dl","nor","ot","rtp","su"];const Za=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const eo=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function to(e){return eo.includes(e)||Qa(e)}const so={[ja]:function(e){return Wa.includes(e)||Ja.includes(e)||Za.includes(e)||Qa(e)},[Ga]:function(e){return Wa.includes(e)||za.includes(e)||Qa(e)},[qa]:function(e){return Wa.includes(e)||Ja.includes(e)||Qa(e)}};function io(e,t={}){const s={};if(null==e||"object"!=typeof e)return s;const i=t.version||e.v||1,r=t.reportingMode||qa,n=1===i?to:so[r];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ja||r===Ga;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const h=pe({},Ya,t.formatters),d={version:i,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let r=e[t];const n=h[t];if("function"==typeof n&&(r=n(r,d)),"v"===t){if(1===i)return;r=i}"pr"==t&&1===r||(l&&"ts"===t&&!se(r)&&(r=Date.now()),function(e){return"number"==typeof e?se(e):null!=e&&""!==e&&!1!==e}(r)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof r&&(r=new Ta(r)),s[t]=r))}),s}function ro(e,t,s){return pe(e,function(e,t={}){const s={};if(!e)return s;const i=$a(io(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce((e,[t,s])=>{const i=xa(s,{whitespace:!1});return i&&(e[t]=i),e},s)}(t,s))}function no(e,t={}){if(!e)return"";const s=function(e,t={}){return e?xa(io(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(s)}const ao=/CMCD=[^&#]+/;function oo(e,t,s){const i=function(e,t={}){return e?`CMCD=${no(e,t)}`:""}(t,s);if(!i)return e;if(ao.test(e))return e.replace(ao,i);const r=e.includes("?")?"&":"?";return`${e}${r}${i}`}class lo{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:ma.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=e=>{try{const{frag:t,part:s}=e,i=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(s||t).duration,ot:r};r!==ma.VIDEO&&r!==ma.AUDIO&&r!=ma.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHED,this.onMediaDetached,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHED,this.onMediaDetached,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=null==(s=t.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}createData(){var e;return{v:1,sf:pa.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){pe(t,this.createData());const s=t.ot===ma.INIT||t.ot===ma.VIDEO||t.ot===ma.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((e,s)=>(i.includes(s)&&(e[s]=t[s]),e),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),ro(e.headers,t,r)):e.url=oo(e.url,t,r)}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=i;for(let t=r.length-1;t>=0;t--){const i=r[t];if(i.index===s&&i.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?ma.TIMED_TEXT:"initSegment"===e.sn?ma.INIT:"audio"===t?ma.AUDIO:"main"===t?this.hls.audioTracks.length?ma.VIDEO:ma.MUXED:void 0}getTopBandwidth(e){let t,s=0;const i=this.hls;if(e===ma.AUDIO)t=i.audioTracks;else{const e=i.maxAutoLevel,s=e>-1?e+1:i.levels.length;t=i.levels.slice(0,s)}return t.forEach(e=>{e.bitrate>s&&(s=e.bitrate)}),s>0?s:NaN}getBufferLength(e){const t=this.media,s=e===ma.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!t)return NaN;return 1e3*js.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}}class ho extends Ee{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===Ss.SendAlternateToPenaltyBox&&s.flags===Ls.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),t.details!==ae.BUFFER_APPEND_ERROR||t.fatal?s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${Jt(i)} penalized: ${Jt(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(e=>{i-s[e]>3e5&&delete s[e]});for(let r=0;r<e.length;r++){const i=e[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Zi(t),this.hls.trigger(oe.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===de&&i[r].hasAudioGroup(e)||t===ce&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new ti(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=uo(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new zt({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let s=1;s<e.audioGroups.length;s++)h.addGroupId("audio",`${e.audioGroups[s]}_clone_${r}`);if(e.subtitleGroups)for(let s=1;s<e.subtitleGroups.length;s++)h.addGroupId("text",`${e.subtitleGroups[s]}_clone_${r}`);return h});t.push(...o),co(this.audioTracks,s,a,r),co(this.subtitleTracks,i,a,r)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(h){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(h){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:i.toString()};this.hls.trigger(oe.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}}function co(e,t,s,i){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=pe({},e);return n.details=void 0,n.attrs=new ti(n.attrs),n.url=n.attrs.URI=uo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n});e.push(...n)})}function uo(e,t,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class fo extends Ee{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=fo.CDMCleanupPromise?[fo.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,i=`"${e.type}" event: init data type: "${t}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ei(this.config));const t=e.map(yi).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{const n=vi(r);if("sinf"!==t||n!==mi.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=Je(new Uint8Array(s)),t=ut(di(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(c){return void this.warn(`${i} Failed to parse sinf: ${c}`)}const o=Pe(a),{keyIdToKeySessionPromise:l,mediaKeySessions:h}=this;let d=l[o];for(let e=0;e<h.length;e++){const i=h[e],r=i.decryptdata;if(!r.keyId)continue;const n=Pe(r.keyId);if(ai(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(d=l[n],!d)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(s),r.keyId=a,d=l[o]=d.then(()=>this.generateRequestWithPreferredKeySession(i,t,s,"encrypted-event-key-match")),d.catch(e=>this.handleError(e));break}}d||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(oe.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(oe.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(oe.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(oe.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=null==t?void 0:t[e];return i?i.licenseUrl:e===mi.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=null==t?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,i=t.map(e=>e.audioCodec).filter(s),r=t.map(e=>e.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,i,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):s(t instanceof po?t:new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===Ti&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=function(e,t,s,i){let r;switch(e){case mi.FAIRPLAY:r=["cenc","sinf"];break;case mi.WIDEVINE:case mi.PLAYREADY:r=["cenc"];break;case mi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,s,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,t,s,i)}(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Jt(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,i.then(t=>t?this.setMediaKeysServerCertificate(s,e,t):s)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Pe(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=go(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Pe(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>yi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const i=yi(e);i?t(i):s(new Error(`Unable to find format for key-system "${e}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Ei(this.config),s=e.map(vi).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=mo(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=go(t),i=this.bannedKeyIds[s];if(i||"internal-error"===this.getKeyStatus(t)){const s=vo(i||"internal-error",t);return this.handleError(s,e.frag),Promise.reject(s)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const i=this.getKeySystemForKeyPromise(t).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:t}))))).then(e=>{const s=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",s,"playlist-key")});return i.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[s]=i,i}return n.catch(s=>{if(s instanceof po){const i=ye({},s.data);"internal-error"===this.getKeyStatus(t)&&(i.decryptdata=t);const r=new po(i,s.message);this.handleError(r,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof po){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Pe(s.keyId||[])})`:""}`),this.hls.trigger(oe.ERROR,e.data)}else this.error(e.message),this.hls.trigger(oe.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=go(e),s=this.keyIdToKeySessionPromise[t];if(!s){const t=vi(e.keyFormat),s=t?[t]:Ei(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ei(this.config)),0===e.length)throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Jt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(s)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===s.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(n)try{const i=n.call(this.hls,t,s,e);if(!i)throw new Error("Invalid response from configured generateRequest filter");t=i.initDataType,s=i.initData?i.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const a=go(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${s.byteLength})`);const l=new Dr,h=e._onmessage=t=>{const s=e.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:i,message:r}=t;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(e,r).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===i?e.keySystem===mi.FAIRPLAY&&this.updateKeySession(e,ci("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${i}"`)},d=(e,t)=>{let s;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?s=vo(e,t.decryptdata):"expired"===e?s=new Error(`key expired (keyId: ${a})`):"released"===e?s=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),s&&(l.eventNames().length?l.emit("error",s):this.handleError(s))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const s=this.getKeyStatuses(e);if(!Object.keys(s).some(e=>"status-pending"!==s[e]))return;if("expired"===s[a])return this.log(`Expired key ${Jt(s)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let i=s[a];if(i)d(i,e);else{var r;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const s=this.getKeyStatus(e.decryptdata);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${s} from other session.`),d(s,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),i="internal-error",d(i,e)},t)),this.log(`No status for keyId ${a} (${Jt(s)}).`)}};or(e.mediaKeysSession,"message",h),or(e.mediaKeysSession,"keystatuseschange",c);const u=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>u).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if("string"==typeof i&&"object"==typeof s){const e=i;i=s,s=e}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===mi.PLAYREADY&&16===r.length){const e=Pe(r);t[e]=s,ui(r)}const n=Pe(r);"internal-error"===s&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{r(e.data)},onError:(t,s,r,o)=>{n(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:ye({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,r)=>{n(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(e=>{r(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let s=0,i=r.length;s<i;s++){var n,a;t=r[s];const i=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;i&&o&&e.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ci(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(s=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:s||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const s=this.config.licenseResponseCallback;if(s)try{t=s.call(this.hls,a,n,e)}catch(o){this.error(o)}i(t)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new po({type:ne.KEY_SYSTEM_ERROR,details:ae.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then(({xhr:t,licenseChallenge:s})=>{e.keySystem==mi.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,or(s,"encrypted",this.onMediaEncrypted),or(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(lr(e,"encrypted",this.onMediaEncrypted),lr(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ai.clearKeyUriToKeyIdMap();const r=i.length;fo.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((null==s||null==(e=s.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Pe((null==i?void 0:i.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(s)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function go(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Pe(e.keyId)}function mo(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}fo.CDMCleanupPromise=void 0;class po extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function vo(e,t){const s="output-restricted"===e,i=s?ae.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ae.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new po({type:ne.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}class yo{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(oe.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(oe.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Eo(e,t){let s;try{s=new Event("addtrack")}catch(ph){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function To(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(ph){Re.debug(`[texttrack-utils]: ${ph}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(i){Re.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}"disabled"===s&&(e.mode=s)}function So(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===s&&(e.mode=s)}function Lo(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function bo(e){const t=[];for(let s=0;s<e.length;s++){const i=e[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[s])}return t}class Ao extends sa{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=bo(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const s=this.findTrackForTextTrack(e);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(oe.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(oe.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;bo(s.textTracks).forEach(e=>{So(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!s||-1!==s.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const s=ss(t,e);if(s>-1)r=e[s];else{const e=ss(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(oe.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if((!s||r.default)&&(s||e)&&(!e||is(r,e)))return i}if(e){for(let s=0;s<t.length;s++){const i=t[s];if(ra(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(ra(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){if(na(t[s],e))return s}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==ce||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&is(e,s))return s;const i=ss(e,this.tracksInGroup);if(i>-1){const e=this.tracksInGroup[i];return this.setSubtitleTrack(i),e}if(s)return null;{const s=ss(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(oe.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=bo(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(e=>na(s,e))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==i&&(e.mode="disabled")}),i){const e=this.subtitleDisplay?"showing":"hidden";i.mode!==e&&(i.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!se(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(oe.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(oe.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}}function Ro(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}const Io=.025;let ko=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Do(e,t,s){return`${e.identifier}-${s+1}-${Ro(t)}`}class Po{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;if(e<=0||isNaN(s))return!1;if(0===s)return!0;return((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return wo(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-wo(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=se(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return wo(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Io))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?ko.Range:ko.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function wo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Io)?t.start:t.start+t.duration}function _o(e,t,s){const i=new self.URL(e,s);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",t),i}function Co(e,t){for(;null!=(s=e.assetList[++t])&&s.error;)var s;return t}function xo(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}class Mo{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(oe.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(oe.LEVEL_LOADED,n),r.once(oe.AUDIO_TRACK_LOADED,n),r.once(oe.SUBTITLE_TRACK_LOADED,n),r.on(oe.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(oe.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(oe.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let s=this.assetItem.uri;try{s=_o(s,e.config.primarySessionId||"").href}catch(t){}e.loadSource(s)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=js.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=js.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;null==(i=this.hls)||i.on(e,t)}once(e,t,s){var i;null==(i=this.hls)||i.once(e,t)}off(e,t,s){var i;null==(i=this.hls)||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xo(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Oo extends Ee{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const e=s[i].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if((null==(s=t[i].event)?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const e=s[r];if(!e.error){const s=e.timelineStart;if(t===s||t>s&&(t<s+(e.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,s=e[e.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),a=Object.keys(i),o=r?r.filter(e=>!a.includes(e.identifier)):[];n.length&&n.sort((e,t)=>{const s=e.cue.pre,i=e.cue.post,r=t.cue.pre,n=t.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=e.startTime,i=t.startTime;if(s!==i)return s-i}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||(null==r?void 0:r.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new Po(o,t),this.eventMap[a]=e,!1===s&&(e.appendInPlace=s)),i.push(e)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let i=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,h=t.cue.post,d=e[a-1]||null,c=t.appendInPlace,u=h?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===ko.Range?f:0,m=t.resumptionOffset,p=(null==d?void 0:d.startTime)===u,v=u+t.cumulativeDuration;let y=c?v+f:u+m;if(l||!h&&u<=0){const e=o;o+=g,t.timelineStart=v;const i=n;n+=f,s.push({event:t,start:v,end:y,playout:{start:i,end:n},integrated:{start:e,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,h=o;o+=r;const d=n;n+=r;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:d,end:n},integrated:{start:h,end:o}};s.push(c)}else r>0&&d&&(d.cumulativeDuration+=r,s[s.length-1].end=u)}h&&(y=v),t.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:t,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=t.resumeTime;i=h||E>r?r:E}),i<r){var a;const e=i,t=o,l=r-i;o+=l;const h=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:i,end:e+l,playout:{start:h,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;s.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,d=l?0:h?i:a.startTime;this.updateAssetDurations(a);if(n===d?a.cumulativeDuration=r:(r=0,n=d),!h&&a.snapOptions.in&&(a.resumeAnchor=hs(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=se(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;if(Math.abs(s-i)>Io)return this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;return!Object.keys(t).some(i=>{const r=t[i].details,n=r.edge;if(s>=n)return this.log(`"${e.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=hs(null,r.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Io+o||Math.abs(a.end-s)<Io+o)&&(this.log(`"${e.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error);s+=a.error?0:a.duration||0}e.duration=i&&!r?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Fo(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class No{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=_o(s,this.hls.sessionId,e.baseUrl)}catch(d){const t=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_ERROR,d,s);return void this.hls.trigger(oe.ERROR,t)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,s,i,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,ae.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(oe.ERROR,t)}e.assetListResponse=n,this.hls.trigger(oe.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,s,i,r)=>{const n=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,r,i);this.hls.trigger(oe.ERROR,n)},onTimeout:(t,s,i)=>{const r=this.assignAssetListError(e,ae.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,i);this.hls.trigger(oe.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(oe.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:ne.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Bo(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Uo(e,t){return`[${e}] Advancing timeline position to ${t}`}class $o extends Lr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",ue.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(oe.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(oe.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(oe.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=cr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(Ye(s)&&(this.fragPrevious=s),this.state=cr),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(0===s&&i!==Number.POSITIVE_INFINITY){const e=i-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}}),this.fragmentTracker.removeFragmentsInRange(s,e,ue.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===ue.SUBTITLE&&(t.details===ae.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dr&&(this.state=cr))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&ia(this.levels,t)?this.levels=t.map(e=>new zt(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new zt(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ue.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==dr&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Wi(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(ar(n,e),l=n.fragmentStart):t&&(l=t.start,Wi(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger(oe.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===cr)){hs(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&li(i.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,hi(i.method)).catch(e=>{throw r.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(s=>{const i=performance.now();r.trigger(oe.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:e,tdecrypt:i}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=cr})}}doTick(){if(this.media){if(this.state===cr){const{currentTrackId:e,levels:t}=this,s=null==t?void 0:t[e];if(!s||!t.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=js.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=i.maxFragLookUpTolerance,t=a>c-e?0:e;u=hs(f,h,Math.max(h[0].start,a),t),!u&&f&&f.start<h[0].start&&(u=h[0])}else u=h[d-1];if(u=this.filterReplacedPrimary(u,s.details),!u)return;const g=h[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===Rs&&(u=g),this.fragmentTracker.getState(u)===Rs){const e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,s,a)}}}else this.state=cr}loadFragment(e,t,s){Ye(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Go(this.tracksBuffered[this.currentTrackId]||[])}}class Go{constructor(e){this.buffered=void 0;const t=(t,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}const Ko={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ho=e=>String.fromCharCode(Ko[e]||e),Vo=15,Yo=100,qo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},jo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Wo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Xo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Qo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;Re.log(`${this.time} [${e}] ${s}`)}}}const Jo=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Zo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class el{constructor(){this.uchar=" ",this.penState=new Zo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class tl{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Zo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Yo;t++)this.chars.push(new el);this.logger=e}equals(e){for(let t=0;t<Yo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Yo;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Yo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Yo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Yo)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ho(e);this.pos>=Yo?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<Yo;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Yo;s++){const i=this.chars[s].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class sl{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Vo;t++)this.rows.push(new tl(e));this.logger=e}reset(){for(let e=0;e<Vo;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<Vo;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Vo;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Vo;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Jt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let t=0;t<Vo;t++)this.rows[t].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[e].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(s.rows[e+n])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,i=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[i].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Jt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Vo;r++){const s=this.rows[r].getTextString();s&&(i=r+1,e?t.push("Row "+i+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}}class il{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new sl(s),this.nonDisplayedMemory=new sl(s),this.lastOutputScreen=new sl(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+Jt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class rl{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new Qo;this.channels=[null,new il(e,t,i),new il(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const e=127&t[s],i=127&t[s+1];let r=!1,n=null;if(0===e&&0===i)continue;this.logger.log(3,()=>"["+Jo([t[s],t[s+1]])+"] -> ("+Jo([e,i])+")");const a=this.cmdHistory;if(e>=16&&e<=31){if(al(e,i,a)){nl(null,null,a),this.logger.log(3,()=>"Repeated command ("+Jo([e,i])+") is dropped");continue}nl(e,i,this.cmdHistory),r=this.parseCmd(e,i),r||(r=this.parseMidrow(e,i)),r||(r=this.parsePAC(e,i)),r||(r=this.parseBackgroundAttributes(e,i))}else nl(null,null,a);if(!r&&(n=this.parseChars(e,i),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Jo([e,i])+" orig: "+Jo([t[s],t[s+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,i=this.channels[s];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Jo([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const i=e<=23?1:2;s=t>=64&&t<=95?1===i?qo[e]:Wo[e]:1===i?jo[e]:zo[e];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,t)),this.currentChannel=i,!0)}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+Ho(e)+"' in channel "+s),i=[e]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Jo(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let s;const i={};16===e||24===e?(s=Math.floor((t-32)/2),i.background=Xo[s],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}nl(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function nl(e,t,s){s.a=e,s.b=t}function al(e,t,s){return s.a===e&&s.b===t}var ol=function(){if(null!=gi&&gi.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function i(e){return s(t,e)}function r(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=t,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const i=function(t){return s(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");L=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class ll{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function hl(e){function t(e,t,s,i){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(i||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}class dl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function cl(e,t,s,i){const r=i?e.split(i):[e];for(const n in r){if("string"!=typeof r[n])continue;const e=r[n].split(s);if(2!==e.length)continue;t(e[0],e[1])}}const ul=new ol(0,0,""),fl="middle"===ul.align?"middle":"center";function gl(e,t,s){const i=e;function r(){const t=hl(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const i=new dl;cl(e,function(e,t){let r;switch(e){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===t){i.set(e,s[r].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),i.integer(e,r[0]),i.percent(e,r[0])&&i.set("snapToLines",!1),i.alt(e,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",fl,"end"]);break;case"position":r=t.split(","),i.percent(e,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",fl,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",fl,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===ul.line&&(r=-1),t.line=r,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",fl);let n=i.get("position","auto");"auto"===n&&50===ul.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function ml(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class pl{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ll,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=ml(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const i=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),i}function i(e){cl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const i=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:e=s(),t.state){case"HEADER":/:/.test(e)?i(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new ol(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{gl(e,t.cue,t.regionList)}catch(r){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(r){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const vl=/\r\n|\n\r|\n|\r/g,yl=function(e,t,s=0){return e.slice(s,s+t.length)===t};function El(e,t,s){return Ro(e.toString())+Ro(t.toString())+Ro(s)}function Tl(e,t,s,i,r,n,a){const o=new pl,l=De(new Uint8Array(e)).trim().replace(vl,"\n").split("\n"),h=[],d=t?function(e,t=1){return Mn(e,9e4,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s}(s,i,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=e.endTime-e.startTime,u=Kn(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=El(e.startTime,e.endTime,m)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(h)},l.forEach(e=>{if(m){if(yl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach(e=>{yl(e,"LOCAL:")?u=e.slice(6):yl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(se(t)&&se(s)&&se(i)&&se(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*i,t+=36e5*r,t}(u)/1e3}catch(t){c=t}return}""===e&&(m=!1)}o.parse(e+"\n")}),o.flush()}const Sl="stpp.ttml.im1t",Ll=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,bl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Al={left:"start",center:"center",right:"end",start:"start",end:"end"};function Rl(e,t,s,i){const r=it(new Uint8Array(e),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>De(e)),a=function(e,t,s=1,i=!1){return Mn(e,t,1/s,i)}(t.baseTime,1,t.timescale);try{n.forEach(e=>s(function(e,t){const s=(new DOMParser).parseFromString(e,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),o=kl(Il(i,"styling","style")),l=kl(Il(i,"layout","region")),h=Il(i,"body","[begin]");return[].map.call(h,e=>{const s=Dl(e,a);if(!s||!e.hasAttribute("begin"))return null;const i=_l(e.getAttribute("begin"),n),r=_l(e.getAttribute("dur"),n);let h=_l(e.getAttribute("end"),n);if(null===i)throw wl(e);if(null===h){if(null===r)throw wl(e);h=i+r}const d=new ol(i-t,h-t,s);d.id=El(d.startTime,d.endTime,d.text);const c=function(e,t,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce((s,n)=>{const a=Pl(t,i,n)||Pl(e,i,n)||Pl(r,i,n);return a&&(s[n]=a),s},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=c;if(u){const e=Al[u];e&&(d.lineAlign=e),d.align=u}return pe(d,c),d}).filter(e=>null!==e)}(e,a)))}catch(o){i(o)}}function Il(e,t,s){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function kl(e){return e.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Dl(e,t){return[].slice.call(e.childNodes).reduce((e,s,i)=>{var r;return"br"===s.nodeName&&i?e+"\n":null!=(r=s.childNodes)&&r.length?Dl(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent},"")}function Pl(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function wl(e){return new Error(`Could not parse ttml timestamp ${e}`)}function _l(e,t){if(!e)return null;let s=hl(e);return null===s&&(Ll.test(e)?s=function(e,t){const s=Ll.exec(e),i=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/t.frameRate}(e,t):bl.test(e)&&(s=function(e,t){const s=bl.exec(e),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),s}class Cl{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class xl{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(oe.FRAG_LOADING,this.onFragLoading,this),e.on(oe.FRAG_LOADED,this.onFragLoaded,this),e.on(oe.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(oe.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(oe.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(oe.FRAG_LOADING,this.onFragLoading,this),e.off(oe.FRAG_LOADED,this.onFragLoaded,this),e.off(oe.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(oe.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(oe.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(oe.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Cl(this,"textTrack1"),t=new Cl(this,"textTrack2"),s=new Cl(this,"textTrack3"),i=new Cl(this,"textTrack4");this.cea608Parser1=new rl(1,e,t),this.cea608Parser2=new rl(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let a=r.length;a--;){const e=r[a],i=Fl(e[0],e[1],t,s);if(i>=0&&(e[0]=Math.min(e[0],t),e[1]=Math.max(e[1],s),n=!0,i/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,s,i)}else{const r=this.Cues.newCue(null,t,s,i);this.hls.trigger(oe.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;s===ue.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(oe.FRAG_LOADED,e):this.hls.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Ol(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)s[e]=a,So(s[e]),Eo(s[e],i);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,s[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(oe.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(e=>{So(i[e]),delete i[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)So(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(e=>e.textCodec===Sl);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ia(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const e=this.media,t=e?bo(e.textTracks):null;if(this.tracks.forEach((e,s)=>{let i;if(t){let s=null;for(let i=0;i<t.length;i++)if(t[i]&&Ol(t[i],e)){s=t[i],t[i]=null;break}s&&(i=s)}if(i)So(i);else{const t=Ml(e);i=this.createTextTrack(t,e.name,e.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(oe.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,i=this.captionsProperties[s];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ue.MAIN){var s,i;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(i=t.part)?void 0:i.index)?s:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===ue.SUBTITLE)if(i.byteLength){const e=s.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),e&&e.textCodec===Sl?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Rl(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),s.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{s.logger.log(`Failed to parse IMSC1: ${t}`),s.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(e);const o=this.hls;Tl(null!=(t=s.initSegment)&&t.data?ft(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,e=>{this._appendCues(e,s.level),o.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>s.cc||o.trigger(oe.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:t})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Rl(t,this.initPTS[e.cc],()=>{s.textCodec=Sl,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||"disabled"===s.mode)return;e.forEach(e=>To(s,e))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(oe.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===ue.SUBTITLE&&this.onFragLoaded(oe.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(s.type!==ue.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let r=0;r<i.length;r++){const e=i[r].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const t=this.extractCea608Data(e);this.cea608Parser1.addData(i[r].pts,t[0]),this.cea608Parser2.addData(i[r].pts,t[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach(i=>Lo(e[i],t,s))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==i){const{textTracks:e}=this;Object.keys(e).forEach(s=>Lo(e[s],t,i))}}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let i=2;for(let r=0;r<s;r++){const s=e[i++],r=127&e[i++],n=127&e[i++];if(0===r&&0===n)continue;if(!!(4&s)){const e=3&s;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}}function Ml(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ol(e,t){return!!e&&e.kind===Ml(t)&&na(t,e)}function Fl(e,t,s,i){return Math.min(t,i)-Math.max(e,s)}const Nl=/\s/,Bl={newCue(e,t,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)Nl.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const i=ml(h.trim()),f=El(t,s,i);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new d(t,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>To(e,t))),r}};function Ul(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const $l=/(\d+)-(\d+)\/(\d+)/;class Gl{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Kl,this.controller=new self.AbortController,this.stats=new $e}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(pe({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&se(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout);(Xn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Hl(t||"fetch, bad network response",e,s)}i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=$l.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(se(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&se(t.highWaterMark)?this.loadProgressively(s,i,e,t.highWaterMark,o):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()}).then(s=>{var r,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=s[a];l&&(i.loaded=i.total=l);const h={url:o.url,data:s,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!se(t.highWaterMark)&&d(i,e,s,o),null==(n=this.callbacks)||n.onSuccess(h,i,e,o)}).catch(t=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},e,t?t.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new Ar,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function Kl(e,t){return new self.Request(e.url,t)}class Hl extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Vl=/^age:\s*[\d.]+\s*$/im;class Yl{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new $e,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)}).catch(e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&se(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;if(Es(h,s.retry,!1,{url:e.url,data:void 0,code:i}))this.retry(h);else Re.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Es(e,this.stats.retry,!0))this.retry(e);else{var t;Re.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=vs(e,s.retry),s.retry++,Re.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Vl.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const ql=ye(ye({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Yl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:os,bufferController:ca,capLevelController:ga,errorController:bs,fpsController:yo,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:Ti,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Bl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:$o,subtitleTrackController:Ao,timelineController:xl,audioStreamController:ta,audioTrackController:aa,emeController:fo,cmcdController:lo,contentSteeringController:ho,interstitialsController:class extends Ee{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),s&&e<i.start||e>=i.end){var r;const t=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const t=i.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&e<a||e>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;if(!s)return;e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>Fo(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,d=null;i&&(h=this.updateItem(i,this.timelinePos),this.itemsMatch(i,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(d=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,d)?this.bufferingItem=d:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const s=e.assetItem.timelineStart,i=e.timelineOffset-s;if(i)try{e.timelineOffset=s}catch(t){Math.abs(i)>Io&&this.warn(`${t} ("${e.assetId}" ${e.timelineOffset}->${s})`)}}}),l||t){if(this.hls.trigger(oe.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(h,i),c&&d!==h&&this.trimInPlace(d,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new No(e),this.schedule=new Oo(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(oe.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(oe.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(oe.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(oe.MEDIA_ENDED,this.onMediaEnded,this),e.on(oe.ERROR,this.onError,this),e.on(oe.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(oe.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(oe.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(oe.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(oe.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(oe.MEDIA_ENDED,this.onMediaEnded,this),e.off(oe.ERROR,this.onError,this),e.off(oe.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){lr(e,"play",this.onPlay),lr(e,"pause",this.onPause),lr(e,"seeking",this.onSeeking),lr(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;or(s,"seeking",this.onSeeking),or(s,"timeupdate",this.onTimeupdate),or(s,"play",this.onPlay),or(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=t=>t?e.getAssetPlayer(t.identifier):t,i=(t,i,n,a,o)=>{if(t){let l=t[i].start;const h=t.event;if(h){if("playout"===i||h.timelineOccupancy!==ko.Point){const e=s(n);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?r():e[a])-t.start}return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var s,i;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,r),d=null==(a=e.schedule.items)?void 0:a[h],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){const n=s(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=t;if("primary"!==r){const e=t-d[r].start;s=d.start+e}const i=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(i)e.timelinePos=s,e.checkBuffer();else{const e=d.event.assetList,s=t-(d[r]||d).start;for(let t=e.length;t--;){const i=e[t];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=t;break}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=s)}}},o=()=>{const s=e.effectivePlayingItem;if(e.isInterstitial(s))return s;const i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=t(),r=e.bufferingItem;var n;return r&&r===s&&(i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),s=e.effectivePlayingItem;return s&&s===t?i(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(t){const s=o(),i=e.effectivePlayingItem;i&&i===s&&a(t+i.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const s=null==(t=o())?void 0:t.event.assetList;return s?s.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const s=null==(t=o())?void 0:t.event;return s&&e.effectivePlayingAsset?s.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,s)=>{var i;if(0!==t&&"primary"!==s&&null!=(i=e.schedule)&&i.length){var r;const i=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[i];if(n)return t+(n[s].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,s=null==t?void 0:t.event;if(s&&!s.restrictions.skip){const i=e.findItemIndex(t);if(s.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&s)&&this.findItemIndex(t)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);const r=null==(t=i)?void 0:t.currentTime;return void 0!==r&&se(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Jt(s)}`),this.detachedData=s}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),h=`${e}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Jt(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=d&&r?r:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(c===r&&u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.log(Uo("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const t=this.timelinePos=s>0?s:0,i=e.findItemIndexAtTime(t);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Co(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,s){const i=Co(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=t+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.log(Uo("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(i)}}}else{if(e.appendInPlace){const t=e.assetList[i];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const t=s.findEventIndex(i),n=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?Fo(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,h=this.playingAsset,d=null==h?void 0:h.identifier,c=d?this.getAssetPlayer(d):null;if(c&&d&&(!this.eventItemsMatch(n,r)||void 0!==t&&d!==s.assetList[t].identifier)){var o;const t=s.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${xo(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(oe.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:e,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(d,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Fo(n)}`),s.hasPlayed=!0,this.hls.trigger(oe.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:e}),s.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const s=this.findItemIndex(r);this.advanceSchedule(s,e,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const s=t.interstitial,i=n.findEventIndex(s.identifier);(i<e||i>e+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const t=Co(r,(s=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,s);s=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Fo(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(oe.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=r.assetList[s];if(!d)return void this.advanceAfterAssetEnded(r,e,s||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){const e=r.assetList.length;this.warn(`asset ${s+1}/${e} player destroyed ${r}`),h=this.createAssetPlayer(r,d,s),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,s,t,e,o),this.shouldPlay&&Bo(h.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&Bo(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Fo(e)}`),null==(i=this.detachedData)||!i.mediaSource){let s=this.timelinePos;(s<e.start||s>=e.end)&&(s=this.getPrimaryResumption(e,t),this.log(Uo("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,e)}if(!s)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Fo(e)}`),this.hls.trigger(oe.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(s<e.fragmentStart||s>e.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return js.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Uo("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(oe.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(oe.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=ye(ye({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=ye(ye({},this.altSelection),{},{audio:s}));const r=ye(ye({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=ye(ye({},this.altSelection),{},{subtitles:s}));const r=ye(ye({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=ts(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=ts(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const i=t[e];if(i.cue.post){var s;const e=this.schedule.findEventIndex(i.identifier),t=null==(s=this.schedule.items)?void 0:s[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(e&&i){return i[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,s)=>{e.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(t.identifier,null)});const s=e.end+.25,i=js.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${Fo(e)} (was ${Fo(t)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&(null==(t=this.schedule)||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=null==(t=this.schedule)?void 0:t.items;if(!s)return;const i=js.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(r),i=Math.min(s+1,t.length-1),n=t[i];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=i),this.isInterstitial(r)){const e=r.event;if(i-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const s=this.getAssetPlayer(e.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Fo(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,s)=>{const i=this.getAssetPlayer(e.identifier);i&&(s===t&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(oe.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=0===i&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(e,0,0,r,e.duration,s);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&i){for(let r=t;r<i;r++){const t=e.assetList[r],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,r)}const s=e.assetList[t];if(s){const e=this.getAssetPlayer(s.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(oe.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,i,r,n){const a={parentIdentifier:e.identifier,identifier:Do(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=pe({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const s=t.duration;s&&e<s&&(h=e)}}const d=t.identifier,c=ye(ye({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=pe({},u,{contentId:Ro(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const f=new Mo(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[s]=t;let g=!0;const m=i=>{if(i.live){var r;const t=new Error(`Interstitials MUST be VOD assets ${e}`),i={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(i,e,n,s,t.message)}const n=i.edge-i.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${d}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(oe.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(oe.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(oe.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(e,t)=>{const s=this.getAssetPlayer(d);if(s&&t.tracks){s.off(oe.BUFFER_CODECS,p),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};f.on(oe.BUFFER_CODECS,p);f.on(oe.BUFFERED_TO_END,()=>{var s;const i=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${i}`),!i||!this.schedule)return;const r=this.schedule.findEventIndex(e.identifier),n=null==(s=this.schedule.items)?void 0:s[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)});const v=t=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return f.once(oe.MEDIA_ENDED,v(s)),f.once(oe.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(oe.ERROR,(t,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(d);if(i.details===ae.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(i,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${i.error} ${e}`)}),f.on(oe.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${d}`),i={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(i,e,this.schedule.findEventIndex(e.identifier),s,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xo(t)}`),this.hls.trigger(oe.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){const e=this.playerQueue[s];this.log(`clear ${e} toSegment: ${t?Fo(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xo(a)}`),this.hls.trigger(oe.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=null==(s=this.schedule.items)?void 0:s[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const d=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(d&&!ke(d,e.tracks)){const t=new Error(`Asset ${xo(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),s={fatal:!0,type:ne.OTHER_ERROR,details:ae.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,a,i,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const s=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===ae.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?xo(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,d=pe({},e,{fatal:!1,errorAction:As(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(oe.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let g=i;g<t.assetList.length;g++)this.resetAssetPlayer(t.assetList[g].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===a?this.advanceAfterAssetEnded(t,s,i):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Fo(s)} error: ${e.error}`),-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);this.itemsMatch(s,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===i)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(r,t,h,o+h,s,e.URI),h+=s}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ae.ASSET_LIST_PARSING_ERROR:case ae.ASSET_LIST_LOAD_ERROR:case ae.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ae.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function jl(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(jl):Object.keys(e).reduce((t,s)=>(t[s]=jl(e[s]),t),{}):e}class Wl extends Vs{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;or(s,"playing",this.onMediaPlaying),or(s,"waiting",this.onMediaWaiting),or(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(lr(s,"playing",this.onMediaPlaying),lr(s,"waiting",this.onMediaWaiting),lr(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(oe.MEDIA_ENDED,{stalled:!1})));if(!js.getBuffered(n).length)return void(this.nudgeRetry=0);const d=js.bufferInfo(n,e,0),c=d.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=zl(this.hls.inFlightFragments,e),s=d.len>2,i=!c||t||c-e>2&&!u.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(d.len>0)&&!c)return;const t=Math.max(c,d.start||0)-e,s=!(null==f||!f.live)?2*f.targetduration:2,i=Ql(e,u);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.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(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(oe.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const T=js.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(T,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(oe.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=js.bufferedInfo(js.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=js.timeRangesToArray(i),r=js.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=js.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Ql(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=js.bufferInfo(this.media,e,0);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=Ql(s,n);if(h||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,ue.MAIN),r=s.getFragAtPos(i,ue.MAIN);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Jt(e)})`);this.warn(i.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=null==(t=this.hls)?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=js.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&i.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>r.maxBufferHole){let t=!1;if(0===n){const e=s.getAppendedFrag(0,ue.MAIN);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(zl(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=Ql(i,s);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,i.currentTime=t,null==e||!e.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),i={type:ne.MEDIA_ERROR,details:ae.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?i.part=e:i.frag=e),this.hls.trigger(oe.ERROR,i)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}}function zl(e,t){const s=Xl(e.main);if(s&&s.start<=t)return s;const i=Xl(e.audio);return i&&i.start<=t?i:null}function Xl(e){if(!e)return null;switch(e.state){case cr:case dr:case yr:case Er:return null}return e.frag}function Ql(e,t){return t.getAppendedFrag(e,ue.MAIN)||t.getPartialFragment(e)}function Jl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Zl(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,Jt(r?ye({type:r},i):i))}return n}const eh=(()=>{const e=Jl();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class th{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(oe.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(oe.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,!1===(null==(s=t.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&So(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return Eo(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Jl();if(n)for(let a=0;a<r.length;a++){const e=r[a].type;if(e===Jr.emsg&&!s||!i)continue;const t=Wr(r[a].data),o=r[a].pts;let l=o+r[a].duration;l>eh&&(l=eh);l-o<=0&&(l=o+.25);for(let s=0;s<t.length;s++){const i=t[s];if(!zr(i)){this.updateId3CueEnds(o,e);const t=Zl(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===t&&s.startTime<e&&s.endTime===eh&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===Jr.audioId3&&o:"video"===i?e=>e.type===Jr.emsg&&a:e=>e.type===Jr.audioId3&&o||e.type===Jr.emsg&&a,Lo(r,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Jl();if(s&&i&&!n){const{fragmentStart:t,fragmentEnd:i}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=i):a&&(r=this.assetCue=Zl(a,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(d).filter(e=>!h.includes(e));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach(e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(s){}}})}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&se(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=eh;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const e=h.reduce((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(s.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!si(l))continue;const h=o[l];if(h)!c||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=u):h.endTime=u;else if(a){let e=s.attr[l];ii(l)&&(e=we(e));const r=Zl(a,i,u,{key:l,data:e},Jr.dateRange);r&&(r.id=t,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}d[t]={cues:o,dateRange:s,durationKnown:c}}}}}class sh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(oe.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(oe.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(oe.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(oe.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ae.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class ih extends sa{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.on(oe.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this),e.off(oe.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=_t(h,s)||void 0),d&&(d=e.videoCodec=function(e){const t=e.split(",");for(let s=0;s<t.length;s++){const e=t[s].split(".");e.length>2&&"avc1"===e[0]&&(t[s]=`avc1.${parseInt(e[1]).toString(16)}${("000"+parseInt(e[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!d),l||(l=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=t,S=`${`${y||"."}-`}${e.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",t.AUDIO),r[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[S]=s,i.push(s)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,i.push(t)}}),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new zt(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=Ut(e,[])}return t}isAudioSupported(e){return At(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return At(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let a=[],o=[],l=e;const h=(null==(n=t.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&(!!(r=t)&&Yt.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${Jt(t.levels.map(e=>e.attrs.CODECS).filter((e,t,s)=>s.indexOf(e)===t))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger(oe.ERROR,{type:ne.MEDIA_ERROR,details:ae.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}}),void(h.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),rh(a)),t.subtitles&&(o=t.subtitles,rh(o));const d=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Yt.indexOf(e.videoRange)-Yt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=kt(e.videoCodec),i=kt(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=Dt(e.codecSet),i=Dt(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length))for(let v=0;v<d.length;v++)if(d[v].pathwayId===l[0].pathwayId){c=d[v];break}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===c){var u;this._firstLevel=v;const e=c.bitrate,t=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${e}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const s=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);s>t&&t===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=s)}break}const f=r&&!i,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:m&&!f&&a.some(e=>!!e.url)};h.end=performance.now(),this.hls.trigger(oe.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(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(oe.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===he&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===ue.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(oe.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Zi(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(oe.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(oe.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function rh(e){const t={};e.forEach(e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++})}function nh(){return self.SourceBuffer||self.WebKitSourceBuffer}function ah(){if(!Ie())return!1;const e=nh();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function oh(){if(!ah())return!1;const e=Ie();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(It(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(It(t,"audio"))))}class lh extends Lr{constructor(e,t,s){super(e,t,s,"stream-controller",ue.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!se(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,ue.MAIN,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.on(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(oe.BUFFER_CREATED,this.onBufferCreated,this),e.on(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(oe.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(oe.MANIFEST_PARSED,this.onManifestParsed,this),e.off(oe.LEVEL_LOADED,this.onLevelLoaded,this),e.off(oe.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(oe.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(oe.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(oe.BUFFER_CREATED,this.onBufferCreated,this),e.off(oe.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(oe.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=cr,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=dr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Sr:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=cr;break}if(this.hls.nextLoadLevel!==this.level){this.state=cr;break}break}case gr:this.checkRetryDate()}this.state===cr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(oe.BUFFER_EOS,e),void(this.state=yr)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===Sr||this.waitForLive(n))return this.level=r,this.state=Sr,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&Ye(u)&&this.fragmentTracker.getState(u)!==Ds){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Ge:Ke,t=(e===Ke?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,ue.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,ue.MAIN,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Rs||i===ks?Ye(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ue.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ur:case fr:case gr:case pr:case vr:this.state=cr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;or(s,"playing",this.onMediaPlaying),or(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(lr(s,"playing",this.onMediaPlaying),lr(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(oe.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const e=t.levels[r].audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=nh();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==cr)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Sr)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==fr&&this.state!==gr||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(oe.LEVEL_UPDATED,{details:a,level:n}),this.state===Sr){if(this.waitForCdnTuneIn(a))return;this.state=cr}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=js.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=js.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new ea(this.hls,ue.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new Ys(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const s=this.hls,i=0!==this.altAudio;if(as(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(oe.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(oe.AUDIO_TRACK_SWITCHED,t)}),void s.trigger(oe.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(oe.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=as(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const a in s){const e=s[a];if("main"===e.id){if(r=a,i=e,"video"===a){const e=s[a];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===ue.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===vr&&(this.state=cr));const e=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),Ye(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&js.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=Er;else switch(t.details){case ae.FRAG_GAP:case ae.FRAG_PARSING_ERROR:case ae.FRAG_DECRYPT_ERROR:case ae.FRAG_LOAD_ERROR:case ae.FRAG_LOAD_TIMEOUT:case ae.KEY_LOAD_ERROR:case ae.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ue.MAIN,t);break;case ae.LEVEL_LOAD_ERROR:case ae.LEVEL_LOAD_TIMEOUT:case ae.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Sr||(null==(s=t.context)?void 0:s.type)!==he||(this.state=cr);break;case ae.BUFFER_ADD_CODEC_ERROR:case ae.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ae.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ae.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=cr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ge||!this.altAudio){const e=(t===Ke?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,ue.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=js.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=cr,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(oe.FRAG_LOADED,e),i.bitrateTest=!1}).catch(t=>{this.state!==dr&&this.state!==Er&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=pr,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger(oe.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(se(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e},s.trigger(oe.INIT_PTS_FOUND,{frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Ge]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Ge,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(oe.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger(oe.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Ye(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==pr)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=Ct(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=ue.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=ue.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(oe.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(oe.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ue.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=cr}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(js.isBuffered(e,s)?t=this.getAppendedFrag(s):js.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger(oe.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger(oe.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return se(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(se(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?hs(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class hh extends Ee{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ae.KEY_LOAD_ERROR,s,i,r){return new Hs({type:ne.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Ye(e)||!Ye(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=vi(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=Ei(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=dh(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:s}=t;return r.key=s.decryptdata.key,{frag:e,keyInfo:s}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+Pe(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,ae.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){const s=function(e){const t=[];return ct(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(s.length){let t=s[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${Pe(t)}`),Ai.setKeyIdForUri(e.decryptdata.uri,t)):(t=Ai.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Pe(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!Ye(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(t=>(e.mediaKeySessionContext=t,s))).catch(s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=new(0,s.loader)(s);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{const{frag:a,keyInfo:o}=s,l=dh(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,ae.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,ye({url:a.url,data:void 0},e)))},onTimeout:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ae.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=dh(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function dh(e){if(e.keyFormat!==pi.FAIRPLAY){const t=e.keyId;if(t)return Pe(t)}return e.uri}function ch(e){const{type:t}=e;switch(t){case de:return ue.AUDIO;case ce:return ue.SUBTITLE;default:return ue.MAIN}}function uh(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class fh{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.on(oe.LEVEL_LOADING,this.onLevelLoading,this),e.on(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(oe.MANIFEST_LOADING,this.onManifestLoading,this),e.off(oe.LEVEL_LOADING,this.onLevelLoading,this),e.off(oe.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(oe.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(oe.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:le,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:he,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:de,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ce,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[he];if(s){const e=s.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(s.abort(),delete this.loaders[he])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===le?s.manifestLoadPolicy.default:pe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),se(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===he&&null!==e.level?t=this.hls.levels[e.level].details:e.type===de&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ce&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=pe({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),_i.isMediaPlaylist(n)||s.type!==le?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=uh(e,s),o=_i.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,h.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];At(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,Lt.audio[i.substring(0,4)]=2,t.splice(n,1)):At(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,Lt.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=_i.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!h[0].audioCodec||h[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 ti({}),bitrate:0,url:""}))}r.trigger(oe.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=uh(e,s),d=se(o)?o:se(a)?a:0,c=ch(s),u=_i.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===le){const e={attrs:new ti({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+zi(u,0),n.trigger(oe.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.MANIFEST_PARSING_ERROR,fatal:t.type===le,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===he?n+=`: ${e.level} id: ${e.id}`:e.type!==de&&e.type!==ce||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ae.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case le:o=s?ae.MANIFEST_LOAD_TIMEOUT:ae.MANIFEST_LOAD_ERROR,l=!0;break;case he:o=s?ae.LEVEL_LOAD_TIMEOUT:ae.LEVEL_LOAD_ERROR,l=!1;break;case de:o=s?ae.AUDIO_TRACK_LOAD_TIMEOUT:ae.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ce:o=s?ae.SUBTITLE_TRACK_LOAD_TIMEOUT:ae.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:ne.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){const s=(null==t?void 0:t.url)||e.url;d.response=ye({url:s,data:void 0},i)}this.hls.trigger(oe.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=uh(t,i),g=ch(i);let m="number"==typeof i.level&&g===ue.MAIN?l:void 0;const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(oe.ERROR,{type:ne.NETWORK_ERROR,details:ae.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case le:case he:if(m)if(h){if(h!==a.levels[m]){const e=a.levels.indexOf(h);e>-1&&(m=e)}}else m=0;a.trigger(oe.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:m||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===le});break;case de:a.trigger(oe.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case ce:a.trigger(oe.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}}}class gh{static get version(){return Pr}static isMSESupported(){return ah()}static isSupported(){return oh()}static getMediaSource(){return Ie()}static get Events(){return oe}static get MetadataSchema(){return Jr}static get ErrorTypes(){return ne}static get ErrorDetails(){return ae}static get DefaultConfig(){return gh.defaultConfig?gh.defaultConfig:ql}static set DefaultConfig(e){gh.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Dr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,s){const i=Le();if("object"==typeof console&&!0===e||"object"==typeof e){const n=["debug","log","info","warn","error"];n.forEach(t=>{i[t]=be(t,e,s)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(r){return Le()}n.forEach(t=>{Ae[t]=be(t,e)})}else pe(Ae,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=function(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=jl(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Jt(t[n])}`)}),ye(ye({},i),t)}(gh.DefaultConfig,e,t);this.userConfig=e,s.progressive&&function(e,t){const s=e.loader;s!==Gl&&s!==Yl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):Ul()&&(e.loader=Gl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),h=this.abrController=new i(this),d=new Ps(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,gh):null,f=this.bufferController=new r(this,d),g=this.capLevelController=new n(this),m=new o(this),p=new fh(this),v=s.contentSteeringController,y=v?new v(this):null,E=this.levelController=new ih(this,y),T=new th(this),S=new hh(this.config,this.logger),L=this.streamController=new lh(this,d,S),b=this.gapController=new Wl(this,d);g.setStreamController(L),m.setStreamController(L);const A=[p,E,L];u&&A.splice(1,0,u),y&&A.splice(1,0,y),this.networkControllers=A;const R=[h,f,b,g,m,T,d];this.audioTrackController=this.createController(s.audioTrackController,A);const I=s.audioStreamController;I&&A.push(this.audioStreamController=new I(this,d,S)),this.subtitleTrackController=this.createController(s.subtitleTrackController,A);const k=s.subtitleStreamController;k&&A.push(this.subtititleStreamController=new k(this,d,S)),this.createController(s.timelineController,R),S.emeController=this.emeController=this.createController(s.emeController,R),this.cmcdController=this.createController(s.cmcdController,R),this.latencyController=this.createController(sh,R),this.coreComponents=R,A.push(l);const D=l.onErrorOut;"function"==typeof D&&this.on(oe.ERROR,D,l),this.on(oe.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const t=e===oe.ERROR;this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.INTERNAL_EXCEPTION,fatal:t,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(oe.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(oe.ERROR,{type:ne.OTHER_ERROR,details:ae.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(oe.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(oe.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(oe.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Ue.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(oe.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ue.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ue.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ue.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Vt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let r=i;r--;){const t=e[r].attrs["HDCP-LEVEL"];if(t&&t<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Gt(e,es(t),navigator.mediaCapabilities)}}gh.defaultConfig=void 0;const mh=Object.freeze(Object.defineProperty({__proto__:null,AbrController:os,AttrList:ti,AudioStreamController:ta,AudioTrackController:aa,BasePlaylistController:sa,BaseSegment:Ve,BaseStreamController:Lr,BufferController:ca,CMCDController:lo,CapLevelController:ga,ChunkMetadata:Ys,ContentSteeringController:ho,Cues:Bl,DateRange:ri,EMEController:fo,ErrorActionFlags:Ls,ErrorController:bs,ErrorDetails:ae,ErrorTypes:ne,Events:oe,FPSController:yo,FetchLoader:Gl,Fragment:qe,Hls:gh,HlsSkip:qt,HlsUrlParameters:Wt,KeySystemFormats:pi,KeySystems:mi,Level:zt,LevelDetails:ni,LevelKey:Ai,LoadStats:$e,M3U8Parser:_i,MetadataSchema:Jr,NetworkErrorAction:Ss,Part:je,PlaylistLevelType:ue,SubtitleStreamController:$o,SubtitleTrackController:Ao,TimelineController:xl,XhrLoader:Yl,default:gh,fetchSupported:Ul,getMediaSource:Ie,isMSESupported:ah,isSupported:oh,requestMediaKeySystemAccess:Ti},Symbol.toStringTag,{value:"Module"}));e.applyContainerStyles=z,e.aspectRatioToPercent=W,e.create=ee,e.createEmbedPlayer=X,e.default=te,e.initAll=Z,e.initElement=Q,e.parseDataAttributes=j,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
2
2
|
//# sourceMappingURL=embed.umd.cjs.map
|