@mux/mux-audio 0.13.1 → 0.13.2
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/dist/index.cjs.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/mux-audio.js +1 -1
- package/dist/mux-audio.mjs +1 -1
- package/package.json +7 -7
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var U=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ct=Object.prototype.hasOwnProperty;var ht=(i,e,t)=>e in i?U(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var mt=(i,e)=>{for(var t in e)U(i,t,{get:e[t],enumerable:!0})},ft=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let d of dt(e))!ct.call(i,d)&&d!==t&&U(i,d,{get:()=>e[d],enumerable:!(o=lt(e,d))||o.enumerable});return i};var bt=i=>ft(U({},"__esModule",{value:!0}),i);var $=(i,e,t)=>(ht(i,typeof e!="symbol"?e+"":e,t),t),z=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)};var u=(i,e,t)=>(z(i,e,"read from private field"),t?t.call(i):e.get(i)),c=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},g=(i,e,t,o)=>(z(i,e,"write to private field"),o?o.call(i,t):e.set(i,t),t);var m=(i,e,t)=>(z(i,e,"access private method"),t);var Rt={};mt(Rt,{Attributes:()=>n,AudioEvents:()=>X,MediaError:()=>l.MediaError,default:()=>Pt});module.exports=bt(Rt);var v=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends v{}globalThis.DocumentFragment=i}var w=class extends v{},W=class extends v{},pt={get(i){},define(i,e,t){},upgrade(i){},whenDefined(i){return Promise.resolve(w)}},B,J=class{constructor(e,t={}){c(this,B,void 0);g(this,B,t==null?void 0:t.detail)}get detail(){return u(this,B)}initCustomEvent(){}};B=new WeakMap;function gt(i,e){return new w}var Z={document:{createElement:gt},DocumentFragment,customElements:pt,CustomEvent:J,EventTarget:v,HTMLElement:w,HTMLVideoElement:W},tt=typeof window=="undefined"||typeof globalThis.customElements=="undefined",V=tt?Z:globalThis,It=tt?Z.document:globalThis.document;var l=require("@mux/playback-core");var At=()=>{try{return"0.13.
|
|
1
|
+
"use strict";var U=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ct=Object.prototype.hasOwnProperty;var ht=(i,e,t)=>e in i?U(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var mt=(i,e)=>{for(var t in e)U(i,t,{get:e[t],enumerable:!0})},ft=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let d of dt(e))!ct.call(i,d)&&d!==t&&U(i,d,{get:()=>e[d],enumerable:!(o=lt(e,d))||o.enumerable});return i};var bt=i=>ft(U({},"__esModule",{value:!0}),i);var $=(i,e,t)=>(ht(i,typeof e!="symbol"?e+"":e,t),t),z=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)};var u=(i,e,t)=>(z(i,e,"read from private field"),t?t.call(i):e.get(i)),c=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},g=(i,e,t,o)=>(z(i,e,"write to private field"),o?o.call(i,t):e.set(i,t),t);var m=(i,e,t)=>(z(i,e,"access private method"),t);var Rt={};mt(Rt,{Attributes:()=>n,AudioEvents:()=>X,MediaError:()=>l.MediaError,default:()=>Pt});module.exports=bt(Rt);var v=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends v{}globalThis.DocumentFragment=i}var w=class extends v{},W=class extends v{},pt={get(i){},define(i,e,t){},upgrade(i){},whenDefined(i){return Promise.resolve(w)}},B,J=class{constructor(e,t={}){c(this,B,void 0);g(this,B,t==null?void 0:t.detail)}get detail(){return u(this,B)}initCustomEvent(){}};B=new WeakMap;function gt(i,e){return new w}var Z={document:{createElement:gt},DocumentFragment,customElements:pt,CustomEvent:J,EventTarget:v,HTMLElement:w,HTMLVideoElement:W},tt=typeof window=="undefined"||typeof globalThis.customElements=="undefined",V=tt?Z:globalThis,It=tt?Z.document:globalThis.document;var l=require("@mux/playback-core");var At=()=>{try{return"0.13.2"}catch{}return"UNKNOWN"},Et=At(),et=()=>Et;var X=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function yt(i){return`
|
|
2
2
|
<style>
|
|
3
3
|
:host {
|
|
4
4
|
display: inline-flex;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ut=Object.defineProperty;var lt=(e,i,t)=>i in e?ut(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var H=(e,i,t)=>(lt(e,typeof i!="symbol"?i+"":i,t),t),q=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var u=(e,i,t)=>(q(e,i,"read from private field"),t?t.call(e):i.get(e)),l=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},p=(e,i,t,o)=>(q(e,i,"write to private field"),o?o.call(e,t):i.set(e,t),t);var c=(e,i,t)=>(q(e,i,"access private method"),t);var k=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class e extends k{}globalThis.DocumentFragment=e}var D=class extends k{},z=class extends k{},dt={get(e){},define(e,i,t){},upgrade(e){},whenDefined(e){return Promise.resolve(D)}},w,W=class{constructor(i,t={}){l(this,w,void 0);p(this,w,t==null?void 0:t.detail)}get detail(){return u(this,w)}initCustomEvent(){}};w=new WeakMap;function ct(e,i){return new D}var Q={document:{createElement:ct},DocumentFragment,customElements:dt,CustomEvent:W,EventTarget:k,HTMLElement:D,HTMLVideoElement:z},X=typeof window=="undefined"||typeof globalThis.customElements=="undefined",U=X?Q:globalThis,St=X?Q.document:globalThis.document;import{initialize as At,teardown as Et,generatePlayerInitTime as yt,PlaybackTypes as V,toMuxVideoURL as Tt,MediaError as Vt,getStartDate as Mt,getCurrentPdt as _t,getEnded as Ct}from"@mux/playback-core";var ht=()=>{try{return"0.13.
|
|
1
|
+
var ut=Object.defineProperty;var lt=(e,i,t)=>i in e?ut(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var H=(e,i,t)=>(lt(e,typeof i!="symbol"?i+"":i,t),t),q=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var u=(e,i,t)=>(q(e,i,"read from private field"),t?t.call(e):i.get(e)),l=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},p=(e,i,t,o)=>(q(e,i,"write to private field"),o?o.call(e,t):i.set(e,t),t);var c=(e,i,t)=>(q(e,i,"access private method"),t);var k=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class e extends k{}globalThis.DocumentFragment=e}var D=class extends k{},z=class extends k{},dt={get(e){},define(e,i,t){},upgrade(e){},whenDefined(e){return Promise.resolve(D)}},w,W=class{constructor(i,t={}){l(this,w,void 0);p(this,w,t==null?void 0:t.detail)}get detail(){return u(this,w)}initCustomEvent(){}};w=new WeakMap;function ct(e,i){return new D}var Q={document:{createElement:ct},DocumentFragment,customElements:dt,CustomEvent:W,EventTarget:k,HTMLElement:D,HTMLVideoElement:z},X=typeof window=="undefined"||typeof globalThis.customElements=="undefined",U=X?Q:globalThis,St=X?Q.document:globalThis.document;import{initialize as At,teardown as Et,generatePlayerInitTime as yt,PlaybackTypes as V,toMuxVideoURL as Tt,MediaError as Vt,getStartDate as Mt,getCurrentPdt as _t,getEnded as Ct}from"@mux/playback-core";var ht=()=>{try{return"0.13.2"}catch{}return"UNKNOWN"},mt=ht(),Z=()=>mt;var it=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function ft(e){return`
|
|
2
2
|
<style>
|
|
3
3
|
:host {
|
|
4
4
|
display: inline-flex;
|
package/dist/mux-audio.js
CHANGED
|
@@ -39,7 +39,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
39
39
|
`:(n=i.childNodes)!=null&&n.length?zo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Cf(r,e,t){let i="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{let u=Xs(e,i,l)||Xs(r,i,l)||Xs(s,i,l);return u&&(o[l]=u),o},{})}function Xs(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function ja(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Qs(r,e){if(!r)return null;let t=Vo(r);return t===null&&(Yo.test(r)?t=Pf(r,e):jo.test(r)&&(t=Of(r,e))),t}function Pf(r,e){let t=Yo.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Of(r,e){let t=jo.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}var jr=class{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=Xa(),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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){let e=new Dt(this,"textTrack1"),t=new Dt(this,"textTrack2"),i=new Dt(this,"textTrack3"),s=new Dt(this,"textTrack4");this.cea608Parser1=new os(1,e,t),this.cea608Parser2=new os(3,i,s)}}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){let l=n[o],u=Mf(l[0],l[1],t,i);if(u>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{let o=this.Cues.newCue(null,t,i,s);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){let{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(v.FRAG_LOADED,o)}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){let n=i.textTracks[s];if(za(n,{name:e,lang:t,attrs:{}}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,It(i[e]),yo(i[e],s);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){let s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{It(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Xa(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)It(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===js);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ho(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?Ci(a.textTracks):null;if(this.tracks.forEach((l,u)=>{let c;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&za(o[h],l)){d=o[h],o[h]=null;break}d&&(c=d)}if(c)It(c);else{let d=Xo(l);c=this.createTextTrack(d,l.name,l.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){let l=o.filter(u=>u!==null).map(u=>u.label);l.length&&L.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.type===H.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===js?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;Wa(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{L.log(`Failed to parse IMSC1: ${s}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;let{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,u=(t=i.initSegment)!=null&&t.data?Me(i.initSegment.data,new Uint8Array(s)):s;Df(u,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{let d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,s),L.log(`Failed to parse VTT cue: ${c}`),!(d&&o>i.cc)&&l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||Wa(t,this.initPTS[e.cc],()=>{i.textCodec=js,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>To(s,n))}else{let s=this.tracks[t];if(!s)return;let n=s.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===H.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();let{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;let{frag:n,samples:a}=t;if(!(n.type===H.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){let l=a[o].bytes;if(l){let u=this.extractCea608Data(l);i.addData(a[o].pts,u[0]),s.addData(a[o].pts,u[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>nr(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>nr(o[l],t,s))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,s=2;for(let n=0;n<i;n++){let a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l))}}return t}};function Xo(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function za(r,e){return!!r&&r.kind===Xo(e)&&Pr(e,r)}function Mf(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Xa(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var zr=class r{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(){let{hls:e}=this;e.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&F(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&L.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,r.getMaxLevelByMediaSize(i,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;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}},Xr=class{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(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,u=this.hls;if(u.trigger(v.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let c=u.currentLevel;L.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=c)&&(c=c-1,u.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},wi="[eme]",ls=class r{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=r.CDMCleanupPromise?[r.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=L.debug.bind(L,wi),this.log=L.log.bind(L,wi),this.warn=L.warn.bind(L,wi),this.error=L.error.bind(L,wi),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===te.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=u=>{let c=u.shift();this.getMediaKeysPromise(c,s,n).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{u.length?l(u):d instanceof Ie?o(d):o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return ro===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){let s=bd(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e],a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(e,s);let o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let u=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),u.then(d=>d?this.setMediaKeysServerCertificate(c,e,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${qe.hexDump(e.keyId||[])}`);let s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return qe.hexDump(e.keyId)}updateKeySession(e,t){var i;let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${qe.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
|
|
40
40
|
} (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){let 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){return new Promise((t,i)=>{let s=Os(this.config),n=e.map(ca).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{let o=da(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),u="cenc";return this.generateRequestWithPreferredKeySession(l,u,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ie?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let s=ca(e.keyFormat),n=s?[s]:Os(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Os(this.config)),e.length===0)throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let s,n;if(t==="sinf"&&this.config.drmSystems[te.FAIRPLAY]){let c=fe(new Uint8Array(i));try{let d=cn(JSON.parse(c).sinf),h=fo(new Uint8Array(d));if(!h)return;s=h.subarray(8,24),n=te.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{let c=zd(i);if(c===null)return;c.version===0&&c.systemId===so.WIDEVINE&&c.data&&(s=c.data.subarray(8,24)),n=_d(c.systemId)}if(!n||!s)return;let a=qe.hexDump(s),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this,u=o[a];for(let c=0;c<l.length;c++){let d=l[c],h=d.decryptdata;if(h.pssh||!h.keyId)continue;let f=qe.hexDump(h.keyId);if(a===f||h.uri.replace(/-/g,"").indexOf(a)!==-1){u=o[f],delete o[f],h.pssh=new Uint8Array(i),h.keyId=s,u=o[a]=u.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}u||(u=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:c,mediaKeys:d})=>{var h;this.throwIfDestroyed();let f=new Zt("ISO-23001-7",a,(h=da(c))!=null?h:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(c,d).then(()=>{this.throwIfDestroyed();let m=this.createMediaKeySessionContext({decryptdata:f,keySystem:c,mediaKeys:d});return this.generateRequestWithPreferredKeySession(m,t,i,"encrypted-event-no-match")})})),u.catch(c=>this.handleError(c))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,a;let o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);let u=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${u} (init data type: ${t} length: ${i?i.byteLength:null})`);let c=new vn,d=e._onmessage=m=>{let g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}let{messageType:p,message:y}=m;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${y.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,y).catch(E=>{this.handleError(E),c.emit("error",E)}):p==="license-release"?e.keySystem===te.FAIRPLAY&&(this.updateKeySession(e,ir("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let p=e.keyStatus;c.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${u}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",h);let f=new Promise((m,g)=>{c.on("error",g),c.on("keyStatus",p=>{p.startsWith("usable")?m():p==="output-restricted"?g(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${u}`)}).catch(m=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw c.removeAllListeners(),this.removeSession(e),m}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${qe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${qe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},u=t.certLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{a(h.data)},onError:(h,f,m,g)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Ee({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};s.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let d=0,h=n.length;d<h;d++){var a,o;c=n[d];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=s.querySelector("Challenge"),u=l==null?void 0:l.textContent;if(!u)throw new Error("Cannot find <Challenge> in key message");return ir(atob(u))}setupLicenseXHR(e,t,i,s){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let u=this.config.licenseResponseCallback;if(u)try{l=u.call(this.hls,o,a,e)}catch(c){this.error(c)}s(l)}else{let l=i.errorRetry,u=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let c=u-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:u})=>{e.keySystem==te.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(l,u)),l.send(u)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Zt.clearKeyUriToKeyIdMap();let i=t.length;r.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}};ls.CDMCleanupPromise=void 0;var Ie=class 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}},be;(function(r){r.MANIFEST="m",r.AUDIO="a",r.VIDEO="v",r.MUXED="av",r.INIT="i",r.CAPTION="c",r.TIMED_TEXT="tt",r.KEY="k",r.OTHER="o"})(be||(be={}));var Qr;(function(r){r.DASH="d",r.HLS="h",r.SMOOTH="s",r.OTHER="o"})(Qr||(Qr={}));var pt;(function(r){r.OBJECT="CMCD-Object",r.REQUEST="CMCD-Request",r.SESSION="CMCD-Session",r.STATUS="CMCD-Status"})(pt||(pt={}));var Nf={[pt.OBJECT]:["br","d","ot","tb"],[pt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[pt.SESSION]:["cid","pr","sf","sid","st","v"],[pt.STATUS]:["bs","rtp"]},ai=class r{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof r?i:new r(i))),this.value=e,this.params=t}},us=class{constructor(e){this.description=void 0,this.description=e}},Ff="Dict";function Uf(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Bf(r,e,t,i){return new Error(`failed to ${r} "${Uf(e)}" as ${t}`,{cause:i})}var Qa="Bare Item",$f="Boolean",Gf="Byte Sequence",Hf="Decimal",Kf="Integer";function Vf(r){return r<-999999999999999||999999999999999<r}var qf=/[\x00-\x1f\x7f]+/,Wf="Token",Yf="Key";function ze(r,e,t){return Bf("serialize",r,e,t)}function jf(r){if(typeof r!="boolean")throw ze(r,$f);return r?"?1":"?0"}function zf(r){return btoa(String.fromCharCode(...r))}function Xf(r){if(ArrayBuffer.isView(r)===!1)throw ze(r,Gf);return`:${zf(r)}:`}function Qo(r){if(Vf(r))throw ze(r,Kf);return r.toString()}function Qf(r){return`@${Qo(r.getTime()/1e3)}`}function Jo(r,e){if(r<0)return-Jo(-r,e);let t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){let s=Math.floor(r*t);return(s%2===0?s:s+1)/t}else return Math.round(r*t)/t}function Jf(r){let e=Jo(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ze(r,Hf);let t=e.toString();return t.includes(".")?t:`${t}.0`}var Zf="String";function em(r){if(qf.test(r))throw ze(r,Zf);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function tm(r){return r.description||r.toString().slice(7,-1)}function Ja(r){let e=tm(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ze(e,Wf);return e}function Jr(r){switch(typeof r){case"number":if(!F(r))throw ze(r,Qa);return Number.isInteger(r)?Qo(r):Jf(r);case"string":return em(r);case"symbol":return Ja(r);case"boolean":return jf(r);case"object":if(r instanceof Date)return Qf(r);if(r instanceof Uint8Array)return Xf(r);if(r instanceof us)return Ja(r);default:throw ze(r,Qa)}}function Zr(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw ze(r,Yf);return r}function En(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Zr(e)}`:`;${Zr(e)}=${Jr(t)}`).join("")}function Zo(r){return r instanceof ai?`${Jr(r.value)}${En(r.params)}`:Jr(r)}function im(r){return`(${r.value.map(Zo).join(" ")})${En(r.params)}`}function sm(r,e={whitespace:!0}){if(typeof r!="object")throw ze(r,Ff);let t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof ai||(n=new ai(n));let a=Zr(s);return n.value===!0?a+=En(n.params):(a+="=",Array.isArray(n.value)?a+=im(n):a+=Zo(n)),a}).join(`,${i}`)}function rm(r,e){return sm(r,e)}var nm=r=>r==="ot"||r==="sf"||r==="st",am=r=>typeof r=="number"?F(r):r!=null&&r!==""&&r!==!1;function om(r,e){let t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;let s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function lm(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}var Fi=r=>Math.round(r),um=(r,e)=>(e!=null&&e.baseUrl&&(r=om(r,e.baseUrl)),encodeURIComponent(r)),ki=r=>Fi(r/100)*100,cm={br:Fi,d:Fi,bl:ki,dl:ki,mtp:ki,nor:um,rtp:ki,tb:Fi};function dm(r,e){let t={};if(r==null||typeof r!="object")return t;let i=Object.keys(r).sort(),s=ue({},cm,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=r[a],l=s[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||am(o)&&(nm(a)&&typeof o=="string"&&(o=new us(o)),t[a]=o))}),t}function el(r,e={}){return r?rm(dm(r,e),ue({whitespace:!1},e)):""}function hm(r,e={}){if(!r)return{};let t=Object.entries(r),i=Object.entries(Nf).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=t.reduce((n,a)=>{var o,l;let[u,c]=a,d=((o=i.find(h=>h[1].includes(u)))==null?void 0:o[0])||pt.REQUEST;return(l=n[d])!=null||(n[d]={}),n[d][u]=c,n},{});return Object.entries(s).reduce((n,[a,o])=>(n[a]=el(o,e),n),{})}function fm(r,e,t){return ue(r,hm(e,t))}var mm="CMCD";function gm(r,e={}){if(!r)return"";let t=el(r,e);return`${mm}=${encodeURIComponent(t)}`}var Za=/CMCD=[^&#]+/;function pm(r,e,t){let i=gm(e,t);if(!i)return r;if(Za.test(r))return r.replace(Za,i);let s=r.includes("?")?"&":"?";return`${r}${s}${i}`}var en=class{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=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(n){L.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{let n=s.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===be.VIDEO||o===be.AUDIO||o==be.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(n){L.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||lm(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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 i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:Qr.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ue(t,this.createData());let i=t.ot===be.INIT||t.ot===be.VIDEO||t.ot===be.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((n,a)=>(s.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),fm(e.headers,t)):e.url=pm(e.url,t)}getObjectType(e){let{type:t}=e;if(t==="subtitle")return be.TIMED_TEXT;if(e.sn==="initSegment")return be.INIT;if(t==="audio")return be.AUDIO;if(t==="main")return this.hls.audioTracks.length?be.VIDEO:be.MUXED}getTopBandwidth(e){let t=0,i,s=this.hls;if(e===be.AUDIO)i=s.audioTracks;else{let n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(let n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===be.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ee.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},vm=3e5,tn=class{constructor(e){this.hls=void 0,this.log=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.log=L.log.bind(L,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==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){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===ye.SendAlternateToPenaltyBox&&i.flags===Fe.MoveAllAlternatesMatchingHost){let s=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:u}=t.context;o&&s?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||L.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>vm&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,_o(t),this.hls.trigger(v.LEVELS_UPDATED,{levels:t});let u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===X.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===X.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let u=this.getLevelsForPathway(o).map(c=>{let d=new se(c.attrs);d["PATHWAY-ID"]=a;let h=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;h&&(i[d.AUDIO]=h,d.AUDIO=h),f&&(s[d.SUBTITLES]=f,d.SUBTITLES=f);let m=tl(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new st({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let p=1;p<c.audioGroups.length;p++)g.addGroupId("audio",`${c.audioGroups[p]}_clone_${a}`);if(c.subtitleGroups)for(let p=1;p<c.subtitleGroups.length;p++)g.addGroupId("text",`${c.subtitleGroups[p]}_clone_${a}`);return g});t.push(...u),eo(this.audioTracks,i,l,a),eo(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}let n={responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},u={onSuccess:(c,d,h,f)=>{this.log(`Loaded steering manifest: "${s}"`);let m=c.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":y}=m;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);let E={steeringManifest:m,url:s.toString()};this.hls.trigger(v.STEERING_MANIFEST_LOADED,E),y&&this.updatePathwayPriority(y)},onError:(c,d,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){let p=g.getResponseHeader("Retry-After");p&&(m=parseFloat(p)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,m)},onTimeout:(c,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function eo(r,e,t,i){r&&Object.keys(e).forEach(s=>{let n=r.filter(a=>a.groupId===s).map(a=>{let o=ue({},a);return o.details=void 0,o.attrs=new se(o.attrs),o.url=o.attrs.URI=tl(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function tl(r,e,t,i){let{HOST:s,PARAMS:n,[t]:a}=i,o;e&&(o=a==null?void 0:a[e],o&&(r=o));let l=new self.URL(r);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(u=>{u&&l.searchParams.set(u,n[u])}),l.href}var ym=/^age:\s*[\d.]+\s*$/im,cs=class{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 Ct,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){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=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);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),i.timeout=n&&F(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,u=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=u,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let c=this.callbacks.onProgress;if(c&&c(i,e,l,t),!this.callbacks)return;let d={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(d,i,e,t)}else{let l=n.loadPolicy.errorRetry,u=i.retry,c={url:e.url,data:void 0,code:a};ji(l,u,!1,c)?this.retry(l):(L.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ji(e,t,!0))this.retry(e);else{var i;L.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=fn(e,i.retry),i.retry++,L.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.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){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ym.test(this.loader.getAllResponseHeaders())){let 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}};function Tm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Em=/(\d+)-(\d+)\/(\d+)/,ds=class{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||bm,this.controller=new self.AbortController,this.stats=new Ct}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(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();let n=xm(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&F(u)?u:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;let h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},c-(h-s.loading.start)),!d.ok){let{status:f,statusText:m}=d;throw new sn(m||"fetch, bad network response",f,d)}return s.loading.first=h,s.total=_m(d.headers)||s.total,a&&F(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{let h=this.response;if(!h)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let f=d[l];f&&(s.loaded=s.total=f);let m={url:h.url,data:d,code:h.status};a&&!F(t.highWaterMark)&&a(s,e,d,h),i.onSuccess(m,s,e,h)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;let h=d&&d.code||0,f=d?d.message:null;i.onError({code:h,text:f},e,d?d.details:null,s)})}getCacheAge(){let e=null;if(this.response){let 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,i,s=0,n){let a=new Qi,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let c=u.value,d=c.length;return t.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush(),e)):n(t,i,c,e),l()}).catch(()=>Promise.reject());return l()}};function xm(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ue({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Sm(r){let e=Em.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function _m(r){let e=r.get("Content-Range");if(e){let i=Sm(e);if(F(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function bm(r,e){return new self.Request(r.url,e)}var sn=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Am=/\s/,Lm={newCue(r,e,t,i){let s=[],n,a,o,l,u,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=!0,l=0,u="",!n.isEmpty()){var d;for(let g=0;g<n.chars.length;g++)Am.test(n.chars[g].uchar)&&o?l++:(u+=n.chars[g].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Wo(u.trim()),m=Tn(e,t,f);r!=null&&(d=r.cues)!=null&&d.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),s.forEach(h=>To(r,h))),s}},Rm={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},il=Ee(Ee({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:cs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mr,bufferController:$r,capLevelController:zr,errorController:hr,fpsController:Xr,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:ro,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Rm},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Im()),{},{subtitleStreamController:Nr,subtitleTrackController:Ur,timelineController:jr,audioStreamController:Or,audioTrackController:Mr,emeController:ls,cmcdController:en,contentSteeringController:tn});function Im(){return{cueHandler:Lm,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Dm(r,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=rn(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{let a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];s.forEach(u=>{let c=`${n}Loading${u}`,d=e[c];if(d!==void 0&&o){l.push(c);let h=t[a].default;switch(e[a]={default:h},u){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&L.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),Ee(Ee({},t),e)}function rn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(rn):Object.keys(r).reduce((e,t)=>(e[t]=rn(r[t]),e),{}):r}function wm(r){let e=r.loader;e!==ds&&e!==cs?(L.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Tm()&&(r.loader=ds,r.progressive=!0,r.enableSoftwareAES=!0,L.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Js,nn=class extends ti{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(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,u=!1;t.levels.forEach(c=>{var d,h;let f=c.attrs,{audioCodec:m,videoCodec:g}=c;((d=m)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(Js||(Js=/chrome|firefox/i.test(navigator.userAgent)),Js&&(c.audioCodec=m=void 0)),m&&(c.audioCodec=m=Vi(m,i)),((h=g)==null?void 0:h.indexOf("avc1"))===0&&(g=c.videoCodec=ih(g));let{width:p,height:y,unknownCodecs:E}=c;if(o||(o=!!(p&&y)),l||(l=!!g),u||(u=!!m),E!=null&&E.length||m&&!Us(m,"audio",i)||g&&!Us(g,"video",i))return;let{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":x,"PATHWAY-ID":R,RESOLUTION:b,"VIDEO-RANGE":A}=f,_=`${`${R||"."}-`}${c.bitrate}-${b}-${S}-${T}-${A}-${x}`;if(n[_])if(n[_].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let D=a[_]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");let C=new st(c);n[_]=C,s.push(C)}else n[_].addGroupId("audio",f.AUDIO),n[_].addGroupId("text",f.SUBTITLES);else{let D=new st(c);n[_]=D,a[_]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,o,l,u)}filterAndSortMediaOptions(e,t,i,s,n){let a=[],o=[],l=e;if((i||s)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:p,height:y})=>(!!m||!!(p&&y))&&hh(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){let{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Us(g.audioCodec,"audio",m)),to(a)}t.subtitles&&(o=t.subtitles,to(o));let u=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return qi.indexOf(m.videoRange)-qi.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){let p=pa(m.videoCodec),y=pa(g.videoCodec);if(p!==y)return y-p}if(m.uri===g.uri&&m.codecSet!==g.codecSet){let p=Ki(m.codecSet),y=Ki(g.codecSet);if(p!==y)return y-p}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let c=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let m=0;m<u.length;m++)if(u[m].pathwayId===l[0].pathwayId){c=u[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===c){var d;this._firstLevel=m;let g=c.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((d=this.hls.userConfig)==null?void 0:d.abrEwmaDefaultEstimate)===void 0){let y=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);y>p&&p===il.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}let h=n&&!s,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:!h&&a.some(m=>!!m.url)};this.hls.trigger(v.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(v.ERROR,{type:V.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);let u=a.details;if(!u||u.live){let c=this.switchParams(a.uri,s==null?void 0:s.details,u);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===X.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;let{level:s,details:n}=t,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}let n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${s}`),this.clearTimer(),this.hls.trigger(v.LEVEL_LOADING,{url:s,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;let i=this._levels.filter((s,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));_o(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(v.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function to(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var an=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyUriToKeyInfo){let s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,i,s,n){return new Be({type:V.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:s}=e;for(let n=0;n<t.length;n++){let a=t[n];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,u))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(u=>(n.key=u.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=i.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{let{frag:p,keyInfo:y,url:E}=m;if(!p.decryptdata||y!==this.keyUriToKeyInfo[E])return o(this.createKeyLoadError(p,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));y.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,y.loader=null,a({frag:p,keyInfo:y})},onError:(h,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Ee({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,c,d)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}};function sl(){return self.SourceBuffer||self.WebKitSourceBuffer}function rl(){if(!yt())return!1;let e=sl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function km(){if(!rl())return!1;let r=yt();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(ei(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(ei(e,"audio"))))}function Cm(){var r;let e=sl();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var Pm=250,Ui=2,Om=.1,Mm=.05,on=class{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:i,media:s,stalled:n}=this;if(s===null)return;let{currentTime:a,seeking:o}=s,l=this.seeking&&!o,u=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){let p=self.performance.now()-n;L.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(u||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!ee.getBuffered(s).length){this.nudgeRetry=0;return}let c=ee.bufferInfo(s,a,0),d=c.nextStart||0;if(o){let p=c.len>Ui,y=!d||t&&t.start<=a||d-a>Ui&&!this.fragmentTracker.getPartialFragment(a);if(p||y)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var h;if(!(c.len>0)&&!d)return;let y=Math.max(d,c.start||0)-a,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(E==null||(h=E.details)==null?void 0:h.live)?E.details.targetduration*2:Ui,x=this.fragmentTracker.getPartialFragment(a);if(y>0&&(y<=S||x)){s.paused||this._trySkipBufferHole(x);return}}let f=self.performance.now();if(n===null){this.stalled=f;return}let m=f-n;if(!o&&m>=Pm&&(this._reportStall(c),!this.media))return;let g=ee.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;let a=n.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(L.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;let n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);L.warn(n.message),t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){let{config:t,hls:i,media:s}=this;if(s===null)return 0;let n=s.currentTime,a=ee.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o){let l=a.len<=t.maxBufferHole,u=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(l||u)){if(c>t.maxBufferHole){let{fragmentTracker:h}=this,f=!1;if(n===0){let m=h.getAppendedFrag(0,H.MAIN);m&&o<m.end&&(f=!0)}if(!f){let m=e||h.getAppendedFrag(n,H.MAIN);if(m){let g=!1,p=m.end;for(;p<o;){let y=h.getPartialFragment(p);if(y)p+=y.duration;else{g=!0;break}}if(g)return 0}}}let d=Math.max(o+Mm,n+Om);if(L.warn(`skipping hole, adjusting currentTime from ${n} to ${d}`),this.moved=!0,this.stalled=null,s.currentTime=d,e&&!e.gap){let h=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${d}`);i.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:e})}return d}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;let n=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){let a=n+(s+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);L.warn(o.message),i.currentTime=a,t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{let a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);L.error(a.message),t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}},Nm=100,ln=class extends ri{constructor(e,t,i){super(e,t,i,"[stream-controller]",H.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.ERROR,this.onError,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.ERROR,this.onError,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Nm),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=k.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=k.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case k.WAITING_LEVEL:{let{levels:t,level:i}=this,s=t==null?void 0:t[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(n))break;this.state=k.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=k.IDLE;break}break}case k.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){let{levels:s,level:n}=this,a=s==null?void 0:s[n];this.resetStartWhenNotLoaded(a||null),this.state=k.IDLE}}break}this.state===k.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let g={};this.altAudio&&(g.type="video"),this.hls.trigger(v.BUFFER_EOS,g),this.state=k.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let u=a.details;if(!u||this.state===k.WAITING_LEVEL||u.live&&this.levelLastLoaded!==a){this.level=n,this.state=k.WAITING_LEVEL;return}let c=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==Te.OK){var m;let p=((m=this.backtrackFragment)!=null?m:f).sn-u.startSN,y=u.fragments[p-1];y&&f.cc===y.cc&&(f=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?Z.AUDIO:Z.VIDEO,y=(p===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,H.MAIN)}f=this.getNextFragmentLoopLoading(f,u,o,H.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===Te.NOT_LOADED||s===Te.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],u=this.fragLastKbps;u&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*u)+1:i=0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case k.KEY_LOADING:case k.FRAG_LOADING:case k.FRAG_LOADING_WAITING_RETRY:case k.PARSING:case k.PARSED:this.state=k.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new on(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;F(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,s=!1;t.levels.forEach(n=>{let a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!Cm(),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){let{levels:i}=this;if(!i||this.state!==k.IDLE)return;let s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=k.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s}=this,n=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let l=s[n],u=this.fragCurrent;u&&(this.state===k.FRAG_LOADING||this.state===k.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(v.LEVEL_UPDATED,{details:a,level:n}),this.state===k.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=k.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let u=o.videoCodec,c=l.PTSKnown||!l.live,d=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new rs(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,g=m!==-1,p=new ii(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),y=this.initPTS[i.cc];f.push(n,d,h,u,i,s,l.totalduration,c,p,y)}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let n=this.hls;i&&(n.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=t.id,s=!!this.hls.audioTracks[i].url;if(s){let n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){let u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i&&i.type!==H.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===k.PARSED&&(this.state=k.IDLE);return}let n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=k.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===k.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===X.LEVEL&&(this.state=k.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===w.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ee.getBuffered(e).length){let i=this.state!==k.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=k.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Z.AUDIO||this.audioOnly&&!this.altAudio){let i=(t===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,H.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let s=ee.getBuffered(e),a=(s.length?s.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=k.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let i="main",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:u,level:c}=o,{video:d,text:h,id3:f,initSegment:m}=n,{details:g}=c,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=k.PARSING,m){if(m!=null&&m.tracks){let T=l.initSegment||l;this._bufferInitSegment(c,m.tracks,T,a),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:i,tracks:m.tracks})}let y=m.initPTS,E=m.timescale;F(y)&&(this.initPTS[l.cc]={baseTime:y,timescale:E},s.trigger(v.INIT_PTS_FOUND,{frag:l,id:i,initPTS:y,timescale:E}))}if(d&&g&&l.sn!=="initSegment"){let y=g.fragments[l.sn-1-g.startSN],E=l.sn===g.startSN,T=!y||l.cc>y.cc;if(n.independent!==!1){let{startPTS:S,endPTS:x,startDTS:R,endDTS:b}=d;if(u)u.elementaryStreams[d.type]={startPTS:S,endPTS:x,startDTS:R,endDTS:b};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){let A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,_=d.firstKeyFramePTS?d.firstKeyFramePTS:S;if(!E&&I<_-this.config.maxBufferHole&&!T){this.backtrack(l);return}else T&&(l.gap=!0);l.setElementaryStreamInfo(d.type,l.start,x,l.start,b,!0)}else E&&S>Ui&&(l.gap=!0);l.setElementaryStreamInfo(d.type,S,x,R,b),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,u,a,E||T)}else if(E||T)l.gap=!0;else{this.backtrack(l);return}}if(p){let{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=p;u&&(u.elementaryStreams[Z.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),l.setElementaryStreamInfo(Z.AUDIO,y,E,T,S),this.bufferFragmentData(p,l,u,a)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){let y={id:i,frag:l,details:g,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,y)}if(g&&h){let y={id:i,frag:l,details:g,samples:h.samples};s.trigger(v.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,s){if(this.state!==k.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(v.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{let c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:l,data:c,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,H.MAIN)}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=k.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(ee.isBuffered(e,i)?t=this.getAppendedFrag(i):ee.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&F(t)&&F(i.programDateTime)){let s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},oi=class r{static get version(){return"1.5.11"}static isMSESupported(){return rl()}static isSupported(){return km()}static getMediaSource(){return yt()}static get Events(){return v}static get ErrorTypes(){return V}static get ErrorDetails(){return w}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:il}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new vn,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,gd(e.debug||!1,"Hls instance");let t=this.config=Dm(r.DefaultConfig,e);this.userConfig=e,t.progressive&&wm(t);let{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),u=this.abrController=new i(this),c=this.bufferController=new s(this),d=this.capLevelController=new n(this),h=new o(this),f=new rr(this),m=new or(this),g=t.contentSteeringController,p=g?new g(this):null,y=this.levelController=new nn(this,p),E=new pr(this),T=new an(this.config),S=this.streamController=new ln(this,E,T);d.setStreamController(S),h.setStreamController(S);let x=[f,y,S];p&&x.splice(1,0,p),this.networkControllers=x;let R=[u,c,d,h,m,E];this.audioTrackController=this.createController(t.audioTrackController,x);let b=t.audioStreamController;b&&x.push(new b(this,E,T)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);let A=t.subtitleStreamController;A&&x.push(new A(this,E,T)),this.createController(t.timelineController,R),T.emeController=this.emeController=this.createController(t.emeController,R),this.cmcdController=this.createController(t.cmcdController,R),this.latencyController=this.createController(lr,R),this.coreComponents=R,x.push(l);let I=l.onErrorOut;typeof I=="function"&&this.on(v.ERROR,I,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(L.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===v.ERROR;this.trigger(v.ERROR,{type:V.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){L.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){L.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){L.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,s=this.url=un.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,L.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){L.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){L.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){L.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){L.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){L.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){L.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){L.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){L.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){L.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(L.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dh(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}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()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let 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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};oi.defaultConfig=void 0;var re=oi,rt=class li extends Error{constructor(e,t=li.MEDIA_ERR_CUSTOM,i,s){var n;super(e),this.name="MediaError",this.code=t,this.context=s,this.fatal=i!=null?i:t>=li.MEDIA_ERR_NETWORK&&t<=li.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=li.defaultMessages[this.code])!=null?n:"")}};rt.MEDIA_ERR_ABORTED=1,rt.MEDIA_ERR_NETWORK=2,rt.MEDIA_ERR_DECODE=3,rt.MEDIA_ERR_SRC_NOT_SUPPORTED=4,rt.MEDIA_ERR_ENCRYPTED=5,rt.MEDIA_ERR_CUSTOM=100,rt.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var Tt=rt,Fm=r=>r==null,ml=(r,e)=>Fm(e)?!1:r in e,bn={ANY:"any",MUTED:"muted"},we={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Et={MSE:"mse",NATIVE:"native"},fs={HEADER:"header",QUERY:"query",NONE:"none"},Ug=Object.values(fs),at={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},An={HLS:at.M3U8},Bg=Object.keys(An),$g=[...Object.values(at),"hls","HLS"];var ge=(r,e,t,i,s=r)=>{s.addEventListener(e,t,i),r.addEventListener("teardown",()=>{s.removeEventListener(e,t)},{once:!0})};function Um(r,e,t){e&&t>e&&(t=e);for(let i=0;i<r.length;i++)if(r.start(i)<=t&&r.end(i)>=t)return!0;return!1}var Bm=r=>{let e=r.indexOf("?");if(e<0)return[r];let t=r.slice(0,e),i=r.slice(e);return[t,i]},gs=r=>{let e=r.type;if(e){let i=e.toUpperCase();return ml(i,An)?An[i]:e}let{src:t}=r;return t?$m(t):""},gl=r=>r==="VOD"?we.ON_DEMAND:we.LIVE,pl=r=>r==="EVENT"?Number.POSITIVE_INFINITY:r==="VOD"?Number.NaN:0,$m=r=>{let e="";try{e=new URL(r).pathname}catch{console.error("invalid url")}let t=e.lastIndexOf(".");if(t<0)return"";let i=e.slice(t+1).toUpperCase();return ml(i,at)?at[i]:""},Gm=Object.values(bn),nl=r=>typeof r=="boolean"||typeof r=="string"&&Gm.includes(r),Hm=(r,e,t)=>{let{autoplay:i}=r,s=!1,n=!1,a=nl(i)?i:!!i,o=()=>{s||ge(e,"playing",()=>{s=!0},{once:!0})};if(o(),ge(e,"loadstart",()=>{s=!1,o(),xn(e,a)},{once:!0}),ge(e,"loadstart",()=>{t||(r.streamType&&r.streamType!==we.UNKNOWN?n=r.streamType===we.LIVE:n=!Number.isFinite(e.duration)),xn(e,a)},{once:!0}),t&&t.once(re.Events.LEVEL_LOADED,(l,u)=>{var c;r.streamType&&r.streamType!==we.UNKNOWN?n=r.streamType===we.LIVE:n=(c=u.details.live)!=null?c:!1}),!a){let l=()=>{!n||Number.isFinite(r.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&ge(e,"play",()=>{e.preload==="metadata"?t.once(re.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{s||(a=nl(l)?l:!!l,xn(e,a))}},xn=(r,e)=>{if(!e)return;let t=r.muted,i=()=>r.muted=t;switch(e){case bn.ANY:r.play().catch(()=>{r.muted=!0,r.play().catch(i)});break;case bn.MUTED:r.muted=!0,r.play().catch(i);break;default:r.play().catch(()=>{});break}},Km=({preload:r,src:e},t,i)=>{let s=d=>{d!=null&&["","none","metadata","auto"].includes(d)?t.setAttribute("preload",d):t.removeAttribute("preload")};if(!i)return s(r),s;let n=!1,a=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,u=d=>{s(d);let h=d!=null?d:t.preload;a||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),c())},c=()=>{!n&&e&&(n=!0,i.loadSource(e))};return ge(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,c()},{once:!0}),u(r),u};function Vm(r,e){var t;if(!("videoTracks"in r))return;let i=new WeakMap;e.on(re.Events.MANIFEST_PARSED,function(u,c){l();let d=r.addVideoTrack("main");d.selected=!0;for(let[h,f]of c.levels.entries()){let m=d.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);i.set(f,`${h}`),m.id=`${h}`}}),e.on(re.Events.AUDIO_TRACKS_UPDATED,function(u,c){o();for(let d of c.audioTracks){let h=d.default?"main":"alternative",f=r.addAudioTrack(h,d.name,d.lang);f.id=`${d.id}`,d.default&&(f.enabled=!0)}}),r.audioTracks.addEventListener("change",()=>{var u;let c=+((u=[...r.audioTracks].find(h=>h.enabled))==null?void 0:u.id),d=e.audioTracks.map(h=>h.id);c!=e.audioTrack&&d.includes(c)&&(e.audioTrack=c)}),e.on(re.Events.LEVELS_UPDATED,function(u,c){var d;let h=r.videoTracks[(d=r.videoTracks.selectedIndex)!=null?d:0];if(!h)return;let f=c.levels.map(m=>i.get(m));for(let m of r.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let s=u=>{let c=u.target.selectedIndex;c!=e.nextLevel&&n(c)},n=u=>{let c=r.currentTime,d=!1,h=(f,m)=>{d||(d=!Number.isFinite(m.endOffset))};e.on(re.Events.BUFFER_FLUSHING,h),e.nextLevel=u,e.off(re.Events.BUFFER_FLUSHING,h),d||e.trigger(re.Events.BUFFER_FLUSHING,{startOffset:c+10,endOffset:1/0,type:"video"})};(t=r.videoRenditions)==null||t.addEventListener("change",s);let a=()=>{for(let u of r.videoTracks)r.removeVideoTrack(u)},o=()=>{for(let u of r.audioTracks)r.removeAudioTrack(u)},l=()=>{a(),o()};e.once(re.Events.DESTROYING,l)}var Sn=r=>"time"in r?r.time:r.startTime;function qm(r,e){e.on(re.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,{tracks:n})=>{n.forEach(a=>{var o;let l=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:c,name:d,type:h})=>c==(l==null?void 0:l.lang)&&d===a.label&&h.toLowerCase()===a.kind);vl(r,a.kind,a.label,l==null?void 0:l.lang,`${a.kind}${u}`)})});let t=()=>{var s;if(!e.subtitleTracks.length)return;let n=Array.from(r.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind)),a=`${(s=e.subtitleTracks[e.subtitleTrack])==null?void 0:s.type.toLowerCase()}${e.subtitleTrack}`;if(n&&(e.subtitleTrack<0||(n==null?void 0:n.id)!==a)){let o=e.subtitleTracks.findIndex(({lang:l,name:u,type:c})=>l==n.language&&u===n.label&&c.toLowerCase()===n.kind);e.subtitleTrack=o}n&&(n==null?void 0:n.id)===a&&n.cues&&Array.from(n.cues).forEach(o=>{n.addCue(o)})};r.textTracks.addEventListener("change",t),e.on(re.Events.CUES_PARSED,(s,{track:n,cues:a})=>{let o=r.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(u=>{var c;(c=o.cues)!=null&&c.getCueById(u.id)||o.addCue(u)}),l&&(o.mode="disabled")}),e.once(re.Events.DESTROYING,()=>{r.textTracks.removeEventListener("change",t),r.querySelectorAll("track[data-removeondestroy]").forEach(s=>{s.remove()})});let i=()=>{Array.from(r.textTracks).forEach(s=>{var n,a;if(!["subtitles","caption"].includes(s.kind)&&s.label==="thumbnails"){if(!((n=s.cues)!=null&&n.length)){let o=r.querySelector('track[label="thumbnails"]'),l=(a=o==null?void 0:o.getAttribute("src"))!=null?a:"";o==null||o.removeAttribute("src"),setTimeout(()=>{o==null||o.setAttribute("src",l)},0)}s.mode!=="hidden"&&(s.mode="hidden")}})};e.once(re.Events.MANIFEST_LOADED,i),e.once(re.Events.MEDIA_ATTACHED,i)}function vl(r,e,t,i,s){let n=document.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),s&&(n.id=s),n.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",n.setAttribute("data-removeondestroy",""),r.append(n),n.track}function Rn(r,e,t){var i;return(i=Array.from(r.querySelectorAll("track")).find(s=>s.track.label===e&&s.track.kind===t))==null?void 0:i.track}async function yl(r,e,t,i){let s=Rn(r,t,i);return s||(s=vl(r,i,t),s.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),s.mode!=="hidden"&&(s.mode="hidden"),[...e].sort((n,a)=>Sn(a)-Sn(n)).forEach(n=>{var a,o;let l=n.value,u=Sn(n);if("endTime"in n&&n.endTime!=null)s==null||s.addCue(new VTTCue(u,n.endTime,i==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let c=Array.prototype.findIndex.call(s==null?void 0:s.cues,m=>m.startTime>=u),d=(a=s==null?void 0:s.cues)==null?void 0:a[c],h=d?d.startTime:Number.isFinite(r.duration)?r.duration:Number.MAX_SAFE_INTEGER,f=(o=s==null?void 0:s.cues)==null?void 0:o[c-1];f&&(f.endTime=u),s==null||s.addCue(new VTTCue(u,h,i==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),r.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),s}var Tl="cuepoints",El=Object.freeze({label:Tl});async function Wm(r,e,t=El){return yl(r,e,t.label,"metadata")}var al=r=>({time:r.startTime,value:JSON.parse(r.text)});function Ym(r,e={label:Tl}){var t,i;let s=Rn(r,e.label,"metadata");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return al(s.activeCues[0]);let{currentTime:n}=r,a=Array.prototype.find.call((i=s.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return al(a||s.activeCues[0])}async function jm(r,e=El){return new Promise(t=>{ge(r,"loadstart",async()=>{let i=await Wm(r,[],e);ge(r,"cuechange",()=>{let s=Ym(r);if(s){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}var xl="chapters",Sl=Object.freeze({label:xl}),ol=r=>({startTime:r.startTime,endTime:r.endTime,value:r.text});async function zm(r,e,t=Sl){return yl(r,e,t.label,"chapters")}function Xm(r,e={label:xl}){var t,i;let s=Rn(r,e.label,"chapters");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return ol(s.activeCues[0]);let{currentTime:n}=r,a=Array.prototype.find.call((i=s.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return ol(a||s.activeCues[0])}async function Qm(r,e=Sl){return new Promise(t=>{ge(r,"loadstart",async()=>{let i=await zm(r,[],e);ge(r,"cuechange",()=>{let s=Xm(r);if(s){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}function _l(r,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-r.currentTime*1e3)}return typeof r.getStartDate=="function"?r.getStartDate():new Date(NaN)}function bl(r,e){if(e&&e.playingDate)return e.playingDate;if(typeof r.getStartDate=="function"){let t=r.getStartDate();return new Date(t.getTime()+r.currentTime*1e3)}return new Date(NaN)}var Jm=async r=>fetch(r).then(e=>e.text()).then(e=>{let t=e.split(`
|
|
41
41
|
`).find((i,s,n)=>s&&n[s-1].startsWith("#EXT-X-STREAM-INF"));return fetch(t).then(i=>i.text()).then(i=>i.split(`
|
|
42
|
-
`))}),Zm=r=>{var e,t,i;let s=(t=((e=r.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),n=gl(s),a=pl(s),o;if(n===we.LIVE){let l=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(l)o=+l.split(":")[1].split("=")[1]*2;else{let u=r.find(d=>d.startsWith("#EXT-X-TARGETDURATION")),c=(i=u==null?void 0:u.split(":"))==null?void 0:i[1];o=+(c!=null?c:6)*3}}return{streamType:n,targetLiveWindow:a,liveEdgeStartOffset:o}},eg=async(r,e)=>{if(e===at.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===at.M3U8){let t=await Jm(r);return Zm(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},_n=async(r,e,t=gs({src:r}))=>{var i,s,n;let{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}=await eg(r,t);((i=ke.get(e))!=null?i:{}).liveEdgeStartOffset=l,((s=ke.get(e))!=null?s:{}).targetLiveWindow=o,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((n=ke.get(e))!=null?n:{}).streamType=a,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},tg=r=>{var e;let t=r.type,i=gl(t),s=pl(t),n,a=!!((e=r.partList)!=null&&e.length);return i===we.LIVE&&(n=a?r.partTarget*2:r.targetduration*3),{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},ig=(r,e,t)=>{var i,s,n,a,o,l,u,c;let{streamType:d,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=tg(r);if(d===we.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let g=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var y;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(y=t.liveSyncPosition)!=null?y:e.seekable.end(p)}});((o=ke.get(e))!=null?o:{}).seekable=g}((l=ke.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=ke.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((c=ke.get(e))!=null?c:{}).streamType=d,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},ll,ul,sg=(ul=(ll=globalThis==null?void 0:globalThis.navigator)==null?void 0:ll.userAgent)!=null?ul:"",rg=sg.toLowerCase().indexOf("android")!==-1,ke=new WeakMap,nt="mux.com",cl,dl,Al=(dl=(cl=re).isSupported)==null?void 0:dl.call(cl),ng=rg,Ll=()=>xi.utils.now(),ag=xi.utils.generateUUID,Rl=({playbackId:r,customDomain:e=nt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,tokens:{playback:o}={},extraSourceParams:l={}}={})=>{if(!r)return;let[u,c=""]=Bm(r),d=new URL(`https://stream.${e}/${u}.m3u8${c}`);return o||d.searchParams.has("token")?(d.searchParams.forEach((h,f)=>{f!="token"&&d.searchParams.delete(f)}),o&&d.searchParams.set("token",o)):(t&&d.searchParams.set("max_resolution",t),i&&(d.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),s&&d.searchParams.set("rendition_order",s),n&&d.searchParams.set("program_start_time",`${n}`),a&&d.searchParams.set("program_end_time",`${a}`),Object.entries(l).forEach(([h,f])=>{f!=null&&d.searchParams.set(h,f)})),d.toString()},og=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Il=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(".m3u8");return e||void 0},lg=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Ol(r)&&(i=(t=og(r.playbackId))!=null?t:Il(r.src))!=null?i:r.src};var hl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.streamType)!=null?t:we.UNKNOWN};var fl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.seekable)!=null?t:r.seekable};var In=.034,ug=(r,e,t=In)=>Math.abs(r-e)<=t,Dl=(r,e,t=In)=>r>e||ug(r,e,t),cg=(r,e=In)=>r.paused&&Dl(r.currentTime,r.duration,e),wl=(r,e)=>{var t,i,s;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(s=e.levels.find(d=>!!d.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(r.currentTime<r.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(r.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=r.buffered.start(r.buffered.length-1),c=r.buffered.end(r.buffered.length-1);return l>u&&l<c},Dn=(r,e)=>r.ended||r.loop?r.ended:e&&wl(r,e)?!0:cg(r),kl=(r,e,t)=>{wn(e,t);let{metadata:i={}}=r,{view_session_id:s=ag()}=i,n=lg(r);i.view_session_id=s,i.video_id=n,r.metadata=i,ke.set(e,{});let a=dg(r,e),o=Km(r,e,a);vg(r,e,a),yg(r,e,a),jm(e),Qm(e);let l=Hm(r,e,a);return{engine:a,setAutoplay:l,setPreload:o}},wn=(r,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),r!=null&&r.mux&&!r.mux.deleted&&(r.mux.destroy(),delete r.mux),r&&(r.removeAttribute("src"),r.load(),r.removeEventListener("error",Nl),r.removeEventListener("error",Ln),r.removeEventListener("durationchange",Ml),ke.delete(r),r.dispatchEvent(new Event("teardown")))};function Cl(r,e){var t;let i=gs(r);if(i!==at.M3U8)return!0;let s=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=r,a=n===Et.MSE,o=n===Et.NATIVE;return s&&(o||!(Al&&(a||ng)))}var dg=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=r,l=gs(r)===at.M3U8,u=Cl(r,e);if(l&&!u&&Al){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=hg(i),h=fg(r),f=a!==fs.NONE?{useHeaders:a===fs.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0;return new re({debug:t,startPosition:s,cmcd:f,xhrSetup:(m,g)=>{var p,y;if(a&&a!==fs.QUERY)return;let E=new URL(g);if(!E.searchParams.has("CMCD"))return;let T=((y=(p=E.searchParams.get("CMCD"))==null?void 0:p.split(","))!=null?y:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");E.searchParams.set("CMCD",T),m.open("GET",E)},...c,...d,...h,...o})}},hg=r=>r===we.LIVE?{backBufferLength:8}:{},fg=r=>{let{drmToken:e,src:t,playbackId:i=Il(t)}=r;return!e||!i?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:ms(r,"fairplay"),serverCertificateUrl:Pl(r,"fairplay")},"com.widevine.alpha":{licenseUrl:ms(r,"widevine")},"com.microsoft.playready":{licenseUrl:ms(r,"playready")}},requestMediaKeySystemAccessFunc:(s,n)=>(s==="com.widevine.alpha"&&(n=[...n.map(a=>{var o;let l=(o=a.videoCapabilities)==null?void 0:o.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...a,videoCapabilities:l}}),...n]),navigator.requestMediaKeySystemAccess(s,n))}},mg=async r=>await(await fetch(r)).arrayBuffer(),gg=async(r,e)=>{let t=await(await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r})).arrayBuffer();return new Uint8Array(t)},pg=(r,e)=>{ge(e,"encrypted",async t=>{try{let i=t.initDataType;if(i!=="skd"){console.error(`Received unexpected initialization data type "${i}"`);return}if(!e.mediaKeys){let l=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[i],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}])).createMediaKeys(),u=await mg(Pl(r,"fairplay"));await l.setServerCertificate(u),await e.setMediaKeys(l)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.generateRequest(i,s);let a=await new Promise(l=>{n.addEventListener("message",u=>{l(u.message)},{once:!0})}),o=await gg(a,ms(r,"fairplay"));return await n.update(o),n}catch(i){console.error(`Could not start encrypted playback due to exception "${i}"`)}})},ms=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/license/${i}/${r}?token=${e}`,Pl=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/appcert/${i}/${r}?token=${e}`,Ol=({playbackId:r,src:e,customDomain:t})=>{if(r)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,s=new URL(e,i).hostname.toLocaleLowerCase();return s.includes(nt)||!!t&&s.includes(t.toLocaleLowerCase())},vg=(r,e,t)=>{var i;let{envKey:s,disableTracking:n}=r,a=Ol(r);if(!n&&(s||a)){let{playerInitTime:o,playerSoftwareName:l,playerSoftwareVersion:u,beaconCollectionDomain:c,debug:d,disableCookies:h}=r,f={...r.metadata,video_title:((i=r==null?void 0:r.metadata)==null?void 0:i.video_title)||void 0},m=g=>typeof g.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(g):g;xi.monitor(e,{debug:d,beaconCollectionDomain:c,hlsjs:t,Hls:t?re:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:h,data:{...s?{env_key:s}:{},player_software_name:l,player_software:l,player_software_version:u,player_init_time:o,...f}})}},yg=(r,e,t)=>{var i;let s=Cl(r,e),{src:n}=r,a=()=>{e.ended||!Dn(e,t)||(wl(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,l,u=()=>{var c,d;let h=(c=fl(e))==null?void 0:c.start(0),f=(d=fl(e))==null?void 0:d.end(0);(l!==f||o!==h)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=h,l=f};if(ge(e,"durationchange",u),e&&s){let c=gs(r);if(typeof n=="string"){let d=()=>{if(hl(e)!==we.LIVE||Number.isFinite(e.duration))return;let h=setInterval(u,1e3);e.addEventListener("teardown",()=>{clearInterval(h)},{once:!0}),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(h)})};if(e.preload==="none"){let h=()=>{_n(n,e,c).then(d),e.removeEventListener("loadedmetadata",f)},f=()=>{_n(n,e,c).then(d),e.removeEventListener("play",h)};ge(e,"play",h,{once:!0}),ge(e,"loadedmetadata",f,{once:!0})}else _n(n,e,c).then(d);r.drmToken&&pg(r,e),e.setAttribute("src",n),r.startTime&&(((i=ke.get(e))!=null?i:{}).startTime=r.startTime,e.addEventListener("durationchange",Ml,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Nl),e.addEventListener("error",Ln),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(d=>{d.remove()})},{once:!0}),ge(e,"pause",a),ge(e,"seeked",a),ge(e,"play",()=>{e.ended||Dl(e.currentTime,e.duration)&&(e.currentTime=e.seekable.start(0))})}else t&&n?(t.once(re.Events.LEVEL_LOADED,(c,d)=>{ig(d.details,e,t),u(),hl(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(re.Events.LEVEL_UPDATED,u),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(re.Events.LEVELS_UPDATED,u)}))}),t.on(re.Events.ERROR,(c,d)=>{let h={[re.ErrorTypes.NETWORK_ERROR]:Tt.MEDIA_ERR_NETWORK,[re.ErrorTypes.MEDIA_ERROR]:Tt.MEDIA_ERR_DECODE},f=new Tt("",h[d.type]);f.fatal=d.fatal,f.data=d,e.dispatchEvent(new CustomEvent("error",{detail:f}))}),e.addEventListener("error",Ln),ge(e,"waiting",a),Vm(r,t),qm(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Ml(r){var e;let t=r.target,i=(e=ke.get(t))==null?void 0:e.startTime;if(i&&Um(t.seekable,t.duration,i)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=i,s&&(t.preload="auto")}}async function Nl(r){if(!r.isTrusted)return;r.stopImmediatePropagation();let e=r.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,s=new Tt(t,i);if(e.src&&(i!==Tt.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:s}))}function Ln(r){var e,t;if(!(r instanceof CustomEvent)||!(r.detail instanceof Tt))return;let i=r.target,s=r.detail;!s||!s.fatal||(((e=ke.get(i))!=null?e:{}).error=s,(t=i.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var Tg=()=>{try{return"0.13.1"}catch{}return"UNKNOWN"},Eg=Tg(),Fl=()=>Eg;var $l=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function xg(r){return`
|
|
42
|
+
`))}),Zm=r=>{var e,t,i;let s=(t=((e=r.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),n=gl(s),a=pl(s),o;if(n===we.LIVE){let l=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(l)o=+l.split(":")[1].split("=")[1]*2;else{let u=r.find(d=>d.startsWith("#EXT-X-TARGETDURATION")),c=(i=u==null?void 0:u.split(":"))==null?void 0:i[1];o=+(c!=null?c:6)*3}}return{streamType:n,targetLiveWindow:a,liveEdgeStartOffset:o}},eg=async(r,e)=>{if(e===at.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===at.M3U8){let t=await Jm(r);return Zm(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},_n=async(r,e,t=gs({src:r}))=>{var i,s,n;let{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}=await eg(r,t);((i=ke.get(e))!=null?i:{}).liveEdgeStartOffset=l,((s=ke.get(e))!=null?s:{}).targetLiveWindow=o,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((n=ke.get(e))!=null?n:{}).streamType=a,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},tg=r=>{var e;let t=r.type,i=gl(t),s=pl(t),n,a=!!((e=r.partList)!=null&&e.length);return i===we.LIVE&&(n=a?r.partTarget*2:r.targetduration*3),{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},ig=(r,e,t)=>{var i,s,n,a,o,l,u,c;let{streamType:d,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=tg(r);if(d===we.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let g=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var y;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(y=t.liveSyncPosition)!=null?y:e.seekable.end(p)}});((o=ke.get(e))!=null?o:{}).seekable=g}((l=ke.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=ke.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((c=ke.get(e))!=null?c:{}).streamType=d,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},ll,ul,sg=(ul=(ll=globalThis==null?void 0:globalThis.navigator)==null?void 0:ll.userAgent)!=null?ul:"",rg=sg.toLowerCase().indexOf("android")!==-1,ke=new WeakMap,nt="mux.com",cl,dl,Al=(dl=(cl=re).isSupported)==null?void 0:dl.call(cl),ng=rg,Ll=()=>xi.utils.now(),ag=xi.utils.generateUUID,Rl=({playbackId:r,customDomain:e=nt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,tokens:{playback:o}={},extraSourceParams:l={}}={})=>{if(!r)return;let[u,c=""]=Bm(r),d=new URL(`https://stream.${e}/${u}.m3u8${c}`);return o||d.searchParams.has("token")?(d.searchParams.forEach((h,f)=>{f!="token"&&d.searchParams.delete(f)}),o&&d.searchParams.set("token",o)):(t&&d.searchParams.set("max_resolution",t),i&&(d.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),s&&d.searchParams.set("rendition_order",s),n&&d.searchParams.set("program_start_time",`${n}`),a&&d.searchParams.set("program_end_time",`${a}`),Object.entries(l).forEach(([h,f])=>{f!=null&&d.searchParams.set(h,f)})),d.toString()},og=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Il=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(".m3u8");return e||void 0},lg=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Ol(r)&&(i=(t=og(r.playbackId))!=null?t:Il(r.src))!=null?i:r.src};var hl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.streamType)!=null?t:we.UNKNOWN};var fl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.seekable)!=null?t:r.seekable};var In=.034,ug=(r,e,t=In)=>Math.abs(r-e)<=t,Dl=(r,e,t=In)=>r>e||ug(r,e,t),cg=(r,e=In)=>r.paused&&Dl(r.currentTime,r.duration,e),wl=(r,e)=>{var t,i,s;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(s=e.levels.find(d=>!!d.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(r.currentTime<r.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(r.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=r.buffered.start(r.buffered.length-1),c=r.buffered.end(r.buffered.length-1);return l>u&&l<c},Dn=(r,e)=>r.ended||r.loop?r.ended:e&&wl(r,e)?!0:cg(r),kl=(r,e,t)=>{wn(e,t);let{metadata:i={}}=r,{view_session_id:s=ag()}=i,n=lg(r);i.view_session_id=s,i.video_id=n,r.metadata=i,ke.set(e,{});let a=dg(r,e),o=Km(r,e,a);vg(r,e,a),yg(r,e,a),jm(e),Qm(e);let l=Hm(r,e,a);return{engine:a,setAutoplay:l,setPreload:o}},wn=(r,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),r!=null&&r.mux&&!r.mux.deleted&&(r.mux.destroy(),delete r.mux),r&&(r.removeAttribute("src"),r.load(),r.removeEventListener("error",Nl),r.removeEventListener("error",Ln),r.removeEventListener("durationchange",Ml),ke.delete(r),r.dispatchEvent(new Event("teardown")))};function Cl(r,e){var t;let i=gs(r);if(i!==at.M3U8)return!0;let s=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=r,a=n===Et.MSE,o=n===Et.NATIVE;return s&&(o||!(Al&&(a||ng)))}var dg=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=r,l=gs(r)===at.M3U8,u=Cl(r,e);if(l&&!u&&Al){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=hg(i),h=fg(r),f=a!==fs.NONE?{useHeaders:a===fs.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0;return new re({debug:t,startPosition:s,cmcd:f,xhrSetup:(m,g)=>{var p,y;if(a&&a!==fs.QUERY)return;let E=new URL(g);if(!E.searchParams.has("CMCD"))return;let T=((y=(p=E.searchParams.get("CMCD"))==null?void 0:p.split(","))!=null?y:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");E.searchParams.set("CMCD",T),m.open("GET",E)},...c,...d,...h,...o})}},hg=r=>r===we.LIVE?{backBufferLength:8}:{},fg=r=>{let{drmToken:e,src:t,playbackId:i=Il(t)}=r;return!e||!i?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:ms(r,"fairplay"),serverCertificateUrl:Pl(r,"fairplay")},"com.widevine.alpha":{licenseUrl:ms(r,"widevine")},"com.microsoft.playready":{licenseUrl:ms(r,"playready")}},requestMediaKeySystemAccessFunc:(s,n)=>(s==="com.widevine.alpha"&&(n=[...n.map(a=>{var o;let l=(o=a.videoCapabilities)==null?void 0:o.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...a,videoCapabilities:l}}),...n]),navigator.requestMediaKeySystemAccess(s,n))}},mg=async r=>await(await fetch(r)).arrayBuffer(),gg=async(r,e)=>{let t=await(await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r})).arrayBuffer();return new Uint8Array(t)},pg=(r,e)=>{ge(e,"encrypted",async t=>{try{let i=t.initDataType;if(i!=="skd"){console.error(`Received unexpected initialization data type "${i}"`);return}if(!e.mediaKeys){let l=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[i],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}])).createMediaKeys(),u=await mg(Pl(r,"fairplay"));await l.setServerCertificate(u),await e.setMediaKeys(l)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.generateRequest(i,s);let a=await new Promise(l=>{n.addEventListener("message",u=>{l(u.message)},{once:!0})}),o=await gg(a,ms(r,"fairplay"));return await n.update(o),n}catch(i){console.error(`Could not start encrypted playback due to exception "${i}"`)}})},ms=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/license/${i}/${r}?token=${e}`,Pl=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/appcert/${i}/${r}?token=${e}`,Ol=({playbackId:r,src:e,customDomain:t})=>{if(r)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,s=new URL(e,i).hostname.toLocaleLowerCase();return s.includes(nt)||!!t&&s.includes(t.toLocaleLowerCase())},vg=(r,e,t)=>{var i;let{envKey:s,disableTracking:n}=r,a=Ol(r);if(!n&&(s||a)){let{playerInitTime:o,playerSoftwareName:l,playerSoftwareVersion:u,beaconCollectionDomain:c,debug:d,disableCookies:h}=r,f={...r.metadata,video_title:((i=r==null?void 0:r.metadata)==null?void 0:i.video_title)||void 0},m=g=>typeof g.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(g):g;xi.monitor(e,{debug:d,beaconCollectionDomain:c,hlsjs:t,Hls:t?re:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:h,data:{...s?{env_key:s}:{},player_software_name:l,player_software:l,player_software_version:u,player_init_time:o,...f}})}},yg=(r,e,t)=>{var i;let s=Cl(r,e),{src:n}=r,a=()=>{e.ended||!Dn(e,t)||(wl(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,l,u=()=>{var c,d;let h=(c=fl(e))==null?void 0:c.start(0),f=(d=fl(e))==null?void 0:d.end(0);(l!==f||o!==h)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=h,l=f};if(ge(e,"durationchange",u),e&&s){let c=gs(r);if(typeof n=="string"){let d=()=>{if(hl(e)!==we.LIVE||Number.isFinite(e.duration))return;let h=setInterval(u,1e3);e.addEventListener("teardown",()=>{clearInterval(h)},{once:!0}),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(h)})};if(e.preload==="none"){let h=()=>{_n(n,e,c).then(d),e.removeEventListener("loadedmetadata",f)},f=()=>{_n(n,e,c).then(d),e.removeEventListener("play",h)};ge(e,"play",h,{once:!0}),ge(e,"loadedmetadata",f,{once:!0})}else _n(n,e,c).then(d);r.drmToken&&pg(r,e),e.setAttribute("src",n),r.startTime&&(((i=ke.get(e))!=null?i:{}).startTime=r.startTime,e.addEventListener("durationchange",Ml,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Nl),e.addEventListener("error",Ln),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(d=>{d.remove()})},{once:!0}),ge(e,"pause",a),ge(e,"seeked",a),ge(e,"play",()=>{e.ended||Dl(e.currentTime,e.duration)&&(e.currentTime=e.seekable.start(0))})}else t&&n?(t.once(re.Events.LEVEL_LOADED,(c,d)=>{ig(d.details,e,t),u(),hl(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(re.Events.LEVEL_UPDATED,u),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(re.Events.LEVELS_UPDATED,u)}))}),t.on(re.Events.ERROR,(c,d)=>{let h={[re.ErrorTypes.NETWORK_ERROR]:Tt.MEDIA_ERR_NETWORK,[re.ErrorTypes.MEDIA_ERROR]:Tt.MEDIA_ERR_DECODE},f=new Tt("",h[d.type]);f.fatal=d.fatal,f.data=d,e.dispatchEvent(new CustomEvent("error",{detail:f}))}),e.addEventListener("error",Ln),ge(e,"waiting",a),Vm(r,t),qm(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Ml(r){var e;let t=r.target,i=(e=ke.get(t))==null?void 0:e.startTime;if(i&&Um(t.seekable,t.duration,i)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=i,s&&(t.preload="auto")}}async function Nl(r){if(!r.isTrusted)return;r.stopImmediatePropagation();let e=r.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,s=new Tt(t,i);if(e.src&&(i!==Tt.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:s}))}function Ln(r){var e,t;if(!(r instanceof CustomEvent)||!(r.detail instanceof Tt))return;let i=r.target,s=r.detail;!s||!s.fatal||(((e=ke.get(i))!=null?e:{}).error=s,(t=i.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var Tg=()=>{try{return"0.13.2"}catch{}return"UNKNOWN"},Eg=Tg(),Fl=()=>Eg;var $l=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function xg(r){return`
|
|
43
43
|
<style>
|
|
44
44
|
:host {
|
|
45
45
|
display: inline-flex;
|
package/dist/mux-audio.mjs
CHANGED
|
@@ -39,7 +39,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
39
39
|
`:(n=i.childNodes)!=null&&n.length?zo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Cf(r,e,t){let i="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{let u=Xs(e,i,l)||Xs(r,i,l)||Xs(s,i,l);return u&&(o[l]=u),o},{})}function Xs(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function ja(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Qs(r,e){if(!r)return null;let t=Vo(r);return t===null&&(Yo.test(r)?t=Pf(r,e):jo.test(r)&&(t=Of(r,e))),t}function Pf(r,e){let t=Yo.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Of(r,e){let t=jo.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}var jr=class{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=Xa(),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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){let e=new Dt(this,"textTrack1"),t=new Dt(this,"textTrack2"),i=new Dt(this,"textTrack3"),s=new Dt(this,"textTrack4");this.cea608Parser1=new os(1,e,t),this.cea608Parser2=new os(3,i,s)}}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){let l=n[o],u=Mf(l[0],l[1],t,i);if(u>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{let o=this.Cues.newCue(null,t,i,s);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){let{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(v.FRAG_LOADED,o)}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){let n=i.textTracks[s];if(za(n,{name:e,lang:t,attrs:{}}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,It(i[e]),yo(i[e],s);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){let s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{It(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Xa(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)It(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===js);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ho(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?Ci(a.textTracks):null;if(this.tracks.forEach((l,u)=>{let c;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&za(o[h],l)){d=o[h],o[h]=null;break}d&&(c=d)}if(c)It(c);else{let d=Xo(l);c=this.createTextTrack(d,l.name,l.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){let l=o.filter(u=>u!==null).map(u=>u.label);l.length&&L.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.type===H.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===js?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;Wa(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{L.log(`Failed to parse IMSC1: ${s}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;let{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,u=(t=i.initSegment)!=null&&t.data?Me(i.initSegment.data,new Uint8Array(s)):s;Df(u,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{let d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,s),L.log(`Failed to parse VTT cue: ${c}`),!(d&&o>i.cc)&&l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||Wa(t,this.initPTS[e.cc],()=>{i.textCodec=js,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>To(s,n))}else{let s=this.tracks[t];if(!s)return;let n=s.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===H.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();let{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;let{frag:n,samples:a}=t;if(!(n.type===H.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){let l=a[o].bytes;if(l){let u=this.extractCea608Data(l);i.addData(a[o].pts,u[0]),s.addData(a[o].pts,u[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>nr(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>nr(o[l],t,s))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,s=2;for(let n=0;n<i;n++){let a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l))}}return t}};function Xo(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function za(r,e){return!!r&&r.kind===Xo(e)&&Pr(e,r)}function Mf(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Xa(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var zr=class r{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(){let{hls:e}=this;e.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&F(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&L.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,r.getMaxLevelByMediaSize(i,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;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}},Xr=class{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(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,u=this.hls;if(u.trigger(v.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let c=u.currentLevel;L.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=c)&&(c=c-1,u.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},wi="[eme]",ls=class r{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=r.CDMCleanupPromise?[r.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=L.debug.bind(L,wi),this.log=L.log.bind(L,wi),this.warn=L.warn.bind(L,wi),this.error=L.error.bind(L,wi),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===te.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=u=>{let c=u.shift();this.getMediaKeysPromise(c,s,n).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{u.length?l(u):d instanceof Ie?o(d):o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return ro===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){let s=bd(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e],a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(e,s);let o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let u=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),u.then(d=>d?this.setMediaKeysServerCertificate(c,e,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${qe.hexDump(e.keyId||[])}`);let s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return qe.hexDump(e.keyId)}updateKeySession(e,t){var i;let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${qe.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
|
|
40
40
|
} (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){let 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){return new Promise((t,i)=>{let s=Os(this.config),n=e.map(ca).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{let o=da(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),u="cenc";return this.generateRequestWithPreferredKeySession(l,u,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ie?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let s=ca(e.keyFormat),n=s?[s]:Os(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Os(this.config)),e.length===0)throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let s,n;if(t==="sinf"&&this.config.drmSystems[te.FAIRPLAY]){let c=fe(new Uint8Array(i));try{let d=cn(JSON.parse(c).sinf),h=fo(new Uint8Array(d));if(!h)return;s=h.subarray(8,24),n=te.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{let c=zd(i);if(c===null)return;c.version===0&&c.systemId===so.WIDEVINE&&c.data&&(s=c.data.subarray(8,24)),n=_d(c.systemId)}if(!n||!s)return;let a=qe.hexDump(s),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this,u=o[a];for(let c=0;c<l.length;c++){let d=l[c],h=d.decryptdata;if(h.pssh||!h.keyId)continue;let f=qe.hexDump(h.keyId);if(a===f||h.uri.replace(/-/g,"").indexOf(a)!==-1){u=o[f],delete o[f],h.pssh=new Uint8Array(i),h.keyId=s,u=o[a]=u.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}u||(u=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:c,mediaKeys:d})=>{var h;this.throwIfDestroyed();let f=new Zt("ISO-23001-7",a,(h=da(c))!=null?h:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(c,d).then(()=>{this.throwIfDestroyed();let m=this.createMediaKeySessionContext({decryptdata:f,keySystem:c,mediaKeys:d});return this.generateRequestWithPreferredKeySession(m,t,i,"encrypted-event-no-match")})})),u.catch(c=>this.handleError(c))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,a;let o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);let u=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${u} (init data type: ${t} length: ${i?i.byteLength:null})`);let c=new vn,d=e._onmessage=m=>{let g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}let{messageType:p,message:y}=m;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${y.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,y).catch(E=>{this.handleError(E),c.emit("error",E)}):p==="license-release"?e.keySystem===te.FAIRPLAY&&(this.updateKeySession(e,ir("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let p=e.keyStatus;c.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${u}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",h);let f=new Promise((m,g)=>{c.on("error",g),c.on("keyStatus",p=>{p.startsWith("usable")?m():p==="output-restricted"?g(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${u}`)}).catch(m=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw c.removeAllListeners(),this.removeSession(e),m}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${qe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${qe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},u=t.certLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{a(h.data)},onError:(h,f,m,g)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Ee({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};s.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let d=0,h=n.length;d<h;d++){var a,o;c=n[d];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=s.querySelector("Challenge"),u=l==null?void 0:l.textContent;if(!u)throw new Error("Cannot find <Challenge> in key message");return ir(atob(u))}setupLicenseXHR(e,t,i,s){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let u=this.config.licenseResponseCallback;if(u)try{l=u.call(this.hls,o,a,e)}catch(c){this.error(c)}s(l)}else{let l=i.errorRetry,u=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new Ie({type:V.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let c=u-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:u})=>{e.keySystem==te.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(l,u)),l.send(u)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Zt.clearKeyUriToKeyIdMap();let i=t.length;r.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}};ls.CDMCleanupPromise=void 0;var Ie=class 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}},be;(function(r){r.MANIFEST="m",r.AUDIO="a",r.VIDEO="v",r.MUXED="av",r.INIT="i",r.CAPTION="c",r.TIMED_TEXT="tt",r.KEY="k",r.OTHER="o"})(be||(be={}));var Qr;(function(r){r.DASH="d",r.HLS="h",r.SMOOTH="s",r.OTHER="o"})(Qr||(Qr={}));var pt;(function(r){r.OBJECT="CMCD-Object",r.REQUEST="CMCD-Request",r.SESSION="CMCD-Session",r.STATUS="CMCD-Status"})(pt||(pt={}));var Nf={[pt.OBJECT]:["br","d","ot","tb"],[pt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[pt.SESSION]:["cid","pr","sf","sid","st","v"],[pt.STATUS]:["bs","rtp"]},ai=class r{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof r?i:new r(i))),this.value=e,this.params=t}},us=class{constructor(e){this.description=void 0,this.description=e}},Ff="Dict";function Uf(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Bf(r,e,t,i){return new Error(`failed to ${r} "${Uf(e)}" as ${t}`,{cause:i})}var Qa="Bare Item",$f="Boolean",Gf="Byte Sequence",Hf="Decimal",Kf="Integer";function Vf(r){return r<-999999999999999||999999999999999<r}var qf=/[\x00-\x1f\x7f]+/,Wf="Token",Yf="Key";function ze(r,e,t){return Bf("serialize",r,e,t)}function jf(r){if(typeof r!="boolean")throw ze(r,$f);return r?"?1":"?0"}function zf(r){return btoa(String.fromCharCode(...r))}function Xf(r){if(ArrayBuffer.isView(r)===!1)throw ze(r,Gf);return`:${zf(r)}:`}function Qo(r){if(Vf(r))throw ze(r,Kf);return r.toString()}function Qf(r){return`@${Qo(r.getTime()/1e3)}`}function Jo(r,e){if(r<0)return-Jo(-r,e);let t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){let s=Math.floor(r*t);return(s%2===0?s:s+1)/t}else return Math.round(r*t)/t}function Jf(r){let e=Jo(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ze(r,Hf);let t=e.toString();return t.includes(".")?t:`${t}.0`}var Zf="String";function em(r){if(qf.test(r))throw ze(r,Zf);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function tm(r){return r.description||r.toString().slice(7,-1)}function Ja(r){let e=tm(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ze(e,Wf);return e}function Jr(r){switch(typeof r){case"number":if(!F(r))throw ze(r,Qa);return Number.isInteger(r)?Qo(r):Jf(r);case"string":return em(r);case"symbol":return Ja(r);case"boolean":return jf(r);case"object":if(r instanceof Date)return Qf(r);if(r instanceof Uint8Array)return Xf(r);if(r instanceof us)return Ja(r);default:throw ze(r,Qa)}}function Zr(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw ze(r,Yf);return r}function En(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Zr(e)}`:`;${Zr(e)}=${Jr(t)}`).join("")}function Zo(r){return r instanceof ai?`${Jr(r.value)}${En(r.params)}`:Jr(r)}function im(r){return`(${r.value.map(Zo).join(" ")})${En(r.params)}`}function sm(r,e={whitespace:!0}){if(typeof r!="object")throw ze(r,Ff);let t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof ai||(n=new ai(n));let a=Zr(s);return n.value===!0?a+=En(n.params):(a+="=",Array.isArray(n.value)?a+=im(n):a+=Zo(n)),a}).join(`,${i}`)}function rm(r,e){return sm(r,e)}var nm=r=>r==="ot"||r==="sf"||r==="st",am=r=>typeof r=="number"?F(r):r!=null&&r!==""&&r!==!1;function om(r,e){let t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;let s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function lm(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}var Fi=r=>Math.round(r),um=(r,e)=>(e!=null&&e.baseUrl&&(r=om(r,e.baseUrl)),encodeURIComponent(r)),ki=r=>Fi(r/100)*100,cm={br:Fi,d:Fi,bl:ki,dl:ki,mtp:ki,nor:um,rtp:ki,tb:Fi};function dm(r,e){let t={};if(r==null||typeof r!="object")return t;let i=Object.keys(r).sort(),s=ue({},cm,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=r[a],l=s[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||am(o)&&(nm(a)&&typeof o=="string"&&(o=new us(o)),t[a]=o))}),t}function el(r,e={}){return r?rm(dm(r,e),ue({whitespace:!1},e)):""}function hm(r,e={}){if(!r)return{};let t=Object.entries(r),i=Object.entries(Nf).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=t.reduce((n,a)=>{var o,l;let[u,c]=a,d=((o=i.find(h=>h[1].includes(u)))==null?void 0:o[0])||pt.REQUEST;return(l=n[d])!=null||(n[d]={}),n[d][u]=c,n},{});return Object.entries(s).reduce((n,[a,o])=>(n[a]=el(o,e),n),{})}function fm(r,e,t){return ue(r,hm(e,t))}var mm="CMCD";function gm(r,e={}){if(!r)return"";let t=el(r,e);return`${mm}=${encodeURIComponent(t)}`}var Za=/CMCD=[^&#]+/;function pm(r,e,t){let i=gm(e,t);if(!i)return r;if(Za.test(r))return r.replace(Za,i);let s=r.includes("?")?"&":"?";return`${r}${s}${i}`}var en=class{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=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(n){L.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{let n=s.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===be.VIDEO||o===be.AUDIO||o==be.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(n){L.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||lm(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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 i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:Qr.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ue(t,this.createData());let i=t.ot===be.INIT||t.ot===be.VIDEO||t.ot===be.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((n,a)=>(s.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),fm(e.headers,t)):e.url=pm(e.url,t)}getObjectType(e){let{type:t}=e;if(t==="subtitle")return be.TIMED_TEXT;if(e.sn==="initSegment")return be.INIT;if(t==="audio")return be.AUDIO;if(t==="main")return this.hls.audioTracks.length?be.VIDEO:be.MUXED}getTopBandwidth(e){let t=0,i,s=this.hls;if(e===be.AUDIO)i=s.audioTracks;else{let n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(let n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===be.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ee.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},vm=3e5,tn=class{constructor(e){this.hls=void 0,this.log=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.log=L.log.bind(L,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==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){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===ye.SendAlternateToPenaltyBox&&i.flags===Fe.MoveAllAlternatesMatchingHost){let s=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:u}=t.context;o&&s?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||L.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>vm&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,_o(t),this.hls.trigger(v.LEVELS_UPDATED,{levels:t});let u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===X.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===X.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let u=this.getLevelsForPathway(o).map(c=>{let d=new se(c.attrs);d["PATHWAY-ID"]=a;let h=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;h&&(i[d.AUDIO]=h,d.AUDIO=h),f&&(s[d.SUBTITLES]=f,d.SUBTITLES=f);let m=tl(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new st({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let p=1;p<c.audioGroups.length;p++)g.addGroupId("audio",`${c.audioGroups[p]}_clone_${a}`);if(c.subtitleGroups)for(let p=1;p<c.subtitleGroups.length;p++)g.addGroupId("text",`${c.subtitleGroups[p]}_clone_${a}`);return g});t.push(...u),eo(this.audioTracks,i,l,a),eo(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}let n={responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},u={onSuccess:(c,d,h,f)=>{this.log(`Loaded steering manifest: "${s}"`);let m=c.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":y}=m;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);let E={steeringManifest:m,url:s.toString()};this.hls.trigger(v.STEERING_MANIFEST_LOADED,E),y&&this.updatePathwayPriority(y)},onError:(c,d,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){let p=g.getResponseHeader("Retry-After");p&&(m=parseFloat(p)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,m)},onTimeout:(c,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function eo(r,e,t,i){r&&Object.keys(e).forEach(s=>{let n=r.filter(a=>a.groupId===s).map(a=>{let o=ue({},a);return o.details=void 0,o.attrs=new se(o.attrs),o.url=o.attrs.URI=tl(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function tl(r,e,t,i){let{HOST:s,PARAMS:n,[t]:a}=i,o;e&&(o=a==null?void 0:a[e],o&&(r=o));let l=new self.URL(r);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(u=>{u&&l.searchParams.set(u,n[u])}),l.href}var ym=/^age:\s*[\d.]+\s*$/im,cs=class{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 Ct,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){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=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);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),i.timeout=n&&F(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,u=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=u,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let c=this.callbacks.onProgress;if(c&&c(i,e,l,t),!this.callbacks)return;let d={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(d,i,e,t)}else{let l=n.loadPolicy.errorRetry,u=i.retry,c={url:e.url,data:void 0,code:a};ji(l,u,!1,c)?this.retry(l):(L.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ji(e,t,!0))this.retry(e);else{var i;L.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=fn(e,i.retry),i.retry++,L.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.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){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ym.test(this.loader.getAllResponseHeaders())){let 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}};function Tm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Em=/(\d+)-(\d+)\/(\d+)/,ds=class{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||bm,this.controller=new self.AbortController,this.stats=new Ct}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(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();let n=xm(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&F(u)?u:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;let h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},c-(h-s.loading.start)),!d.ok){let{status:f,statusText:m}=d;throw new sn(m||"fetch, bad network response",f,d)}return s.loading.first=h,s.total=_m(d.headers)||s.total,a&&F(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{let h=this.response;if(!h)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let f=d[l];f&&(s.loaded=s.total=f);let m={url:h.url,data:d,code:h.status};a&&!F(t.highWaterMark)&&a(s,e,d,h),i.onSuccess(m,s,e,h)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;let h=d&&d.code||0,f=d?d.message:null;i.onError({code:h,text:f},e,d?d.details:null,s)})}getCacheAge(){let e=null;if(this.response){let 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,i,s=0,n){let a=new Qi,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let c=u.value,d=c.length;return t.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush(),e)):n(t,i,c,e),l()}).catch(()=>Promise.reject());return l()}};function xm(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ue({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Sm(r){let e=Em.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function _m(r){let e=r.get("Content-Range");if(e){let i=Sm(e);if(F(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function bm(r,e){return new self.Request(r.url,e)}var sn=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Am=/\s/,Lm={newCue(r,e,t,i){let s=[],n,a,o,l,u,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=!0,l=0,u="",!n.isEmpty()){var d;for(let g=0;g<n.chars.length;g++)Am.test(n.chars[g].uchar)&&o?l++:(u+=n.chars[g].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Wo(u.trim()),m=Tn(e,t,f);r!=null&&(d=r.cues)!=null&&d.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),s.forEach(h=>To(r,h))),s}},Rm={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},il=Ee(Ee({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:cs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mr,bufferController:$r,capLevelController:zr,errorController:hr,fpsController:Xr,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:ro,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Rm},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Im()),{},{subtitleStreamController:Nr,subtitleTrackController:Ur,timelineController:jr,audioStreamController:Or,audioTrackController:Mr,emeController:ls,cmcdController:en,contentSteeringController:tn});function Im(){return{cueHandler:Lm,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Dm(r,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=rn(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{let a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];s.forEach(u=>{let c=`${n}Loading${u}`,d=e[c];if(d!==void 0&&o){l.push(c);let h=t[a].default;switch(e[a]={default:h},u){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&L.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),Ee(Ee({},t),e)}function rn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(rn):Object.keys(r).reduce((e,t)=>(e[t]=rn(r[t]),e),{}):r}function wm(r){let e=r.loader;e!==ds&&e!==cs?(L.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Tm()&&(r.loader=ds,r.progressive=!0,r.enableSoftwareAES=!0,L.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Js,nn=class extends ti{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(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,u=!1;t.levels.forEach(c=>{var d,h;let f=c.attrs,{audioCodec:m,videoCodec:g}=c;((d=m)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(Js||(Js=/chrome|firefox/i.test(navigator.userAgent)),Js&&(c.audioCodec=m=void 0)),m&&(c.audioCodec=m=Vi(m,i)),((h=g)==null?void 0:h.indexOf("avc1"))===0&&(g=c.videoCodec=ih(g));let{width:p,height:y,unknownCodecs:E}=c;if(o||(o=!!(p&&y)),l||(l=!!g),u||(u=!!m),E!=null&&E.length||m&&!Us(m,"audio",i)||g&&!Us(g,"video",i))return;let{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":x,"PATHWAY-ID":R,RESOLUTION:b,"VIDEO-RANGE":A}=f,_=`${`${R||"."}-`}${c.bitrate}-${b}-${S}-${T}-${A}-${x}`;if(n[_])if(n[_].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let D=a[_]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");let C=new st(c);n[_]=C,s.push(C)}else n[_].addGroupId("audio",f.AUDIO),n[_].addGroupId("text",f.SUBTITLES);else{let D=new st(c);n[_]=D,a[_]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,o,l,u)}filterAndSortMediaOptions(e,t,i,s,n){let a=[],o=[],l=e;if((i||s)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:p,height:y})=>(!!m||!!(p&&y))&&hh(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){let{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Us(g.audioCodec,"audio",m)),to(a)}t.subtitles&&(o=t.subtitles,to(o));let u=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return qi.indexOf(m.videoRange)-qi.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){let p=pa(m.videoCodec),y=pa(g.videoCodec);if(p!==y)return y-p}if(m.uri===g.uri&&m.codecSet!==g.codecSet){let p=Ki(m.codecSet),y=Ki(g.codecSet);if(p!==y)return y-p}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let c=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let m=0;m<u.length;m++)if(u[m].pathwayId===l[0].pathwayId){c=u[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===c){var d;this._firstLevel=m;let g=c.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((d=this.hls.userConfig)==null?void 0:d.abrEwmaDefaultEstimate)===void 0){let y=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);y>p&&p===il.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}let h=n&&!s,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:!h&&a.some(m=>!!m.url)};this.hls.trigger(v.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(v.ERROR,{type:V.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);let u=a.details;if(!u||u.live){let c=this.switchParams(a.uri,s==null?void 0:s.details,u);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===X.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;let{level:s,details:n}=t,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}let n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${s}`),this.clearTimer(),this.hls.trigger(v.LEVEL_LOADING,{url:s,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;let i=this._levels.filter((s,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));_o(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(v.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function to(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var an=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyUriToKeyInfo){let s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,i,s,n){return new Be({type:V.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:s}=e;for(let n=0;n<t.length;n++){let a=t[n];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,u))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(u=>(n.key=u.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=i.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{let{frag:p,keyInfo:y,url:E}=m;if(!p.decryptdata||y!==this.keyUriToKeyInfo[E])return o(this.createKeyLoadError(p,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));y.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,y.loader=null,a({frag:p,keyInfo:y})},onError:(h,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Ee({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,c,d)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}};function sl(){return self.SourceBuffer||self.WebKitSourceBuffer}function rl(){if(!yt())return!1;let e=sl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function km(){if(!rl())return!1;let r=yt();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(ei(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(ei(e,"audio"))))}function Cm(){var r;let e=sl();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var Pm=250,Ui=2,Om=.1,Mm=.05,on=class{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:i,media:s,stalled:n}=this;if(s===null)return;let{currentTime:a,seeking:o}=s,l=this.seeking&&!o,u=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){let p=self.performance.now()-n;L.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(u||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!ee.getBuffered(s).length){this.nudgeRetry=0;return}let c=ee.bufferInfo(s,a,0),d=c.nextStart||0;if(o){let p=c.len>Ui,y=!d||t&&t.start<=a||d-a>Ui&&!this.fragmentTracker.getPartialFragment(a);if(p||y)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var h;if(!(c.len>0)&&!d)return;let y=Math.max(d,c.start||0)-a,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(E==null||(h=E.details)==null?void 0:h.live)?E.details.targetduration*2:Ui,x=this.fragmentTracker.getPartialFragment(a);if(y>0&&(y<=S||x)){s.paused||this._trySkipBufferHole(x);return}}let f=self.performance.now();if(n===null){this.stalled=f;return}let m=f-n;if(!o&&m>=Pm&&(this._reportStall(c),!this.media))return;let g=ee.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;let a=n.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(L.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;let n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);L.warn(n.message),t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){let{config:t,hls:i,media:s}=this;if(s===null)return 0;let n=s.currentTime,a=ee.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o){let l=a.len<=t.maxBufferHole,u=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(l||u)){if(c>t.maxBufferHole){let{fragmentTracker:h}=this,f=!1;if(n===0){let m=h.getAppendedFrag(0,H.MAIN);m&&o<m.end&&(f=!0)}if(!f){let m=e||h.getAppendedFrag(n,H.MAIN);if(m){let g=!1,p=m.end;for(;p<o;){let y=h.getPartialFragment(p);if(y)p+=y.duration;else{g=!0;break}}if(g)return 0}}}let d=Math.max(o+Mm,n+Om);if(L.warn(`skipping hole, adjusting currentTime from ${n} to ${d}`),this.moved=!0,this.stalled=null,s.currentTime=d,e&&!e.gap){let h=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${d}`);i.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:e})}return d}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;let n=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){let a=n+(s+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);L.warn(o.message),i.currentTime=a,t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{let a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);L.error(a.message),t.trigger(v.ERROR,{type:V.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}},Nm=100,ln=class extends ri{constructor(e,t,i){super(e,t,i,"[stream-controller]",H.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.ERROR,this.onError,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.ERROR,this.onError,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Nm),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=k.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=k.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case k.WAITING_LEVEL:{let{levels:t,level:i}=this,s=t==null?void 0:t[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(n))break;this.state=k.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=k.IDLE;break}break}case k.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){let{levels:s,level:n}=this,a=s==null?void 0:s[n];this.resetStartWhenNotLoaded(a||null),this.state=k.IDLE}}break}this.state===k.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let g={};this.altAudio&&(g.type="video"),this.hls.trigger(v.BUFFER_EOS,g),this.state=k.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let u=a.details;if(!u||this.state===k.WAITING_LEVEL||u.live&&this.levelLastLoaded!==a){this.level=n,this.state=k.WAITING_LEVEL;return}let c=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==Te.OK){var m;let p=((m=this.backtrackFragment)!=null?m:f).sn-u.startSN,y=u.fragments[p-1];y&&f.cc===y.cc&&(f=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?Z.AUDIO:Z.VIDEO,y=(p===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,H.MAIN)}f=this.getNextFragmentLoopLoading(f,u,o,H.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===Te.NOT_LOADED||s===Te.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],u=this.fragLastKbps;u&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*u)+1:i=0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case k.KEY_LOADING:case k.FRAG_LOADING:case k.FRAG_LOADING_WAITING_RETRY:case k.PARSING:case k.PARSED:this.state=k.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new on(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;F(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,s=!1;t.levels.forEach(n=>{let a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!Cm(),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){let{levels:i}=this;if(!i||this.state!==k.IDLE)return;let s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=k.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s}=this,n=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let l=s[n],u=this.fragCurrent;u&&(this.state===k.FRAG_LOADING||this.state===k.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(v.LEVEL_UPDATED,{details:a,level:n}),this.state===k.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=k.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let u=o.videoCodec,c=l.PTSKnown||!l.live,d=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new rs(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,g=m!==-1,p=new ii(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),y=this.initPTS[i.cc];f.push(n,d,h,u,i,s,l.totalduration,c,p,y)}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let n=this.hls;i&&(n.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=t.id,s=!!this.hls.audioTracks[i].url;if(s){let n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){let u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i&&i.type!==H.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===k.PARSED&&(this.state=k.IDLE);return}let n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=k.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===k.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===X.LEVEL&&(this.state=k.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===w.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ee.getBuffered(e).length){let i=this.state!==k.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=k.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Z.AUDIO||this.audioOnly&&!this.altAudio){let i=(t===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,H.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let s=ee.getBuffered(e),a=(s.length?s.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=k.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let i="main",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:u,level:c}=o,{video:d,text:h,id3:f,initSegment:m}=n,{details:g}=c,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=k.PARSING,m){if(m!=null&&m.tracks){let T=l.initSegment||l;this._bufferInitSegment(c,m.tracks,T,a),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:i,tracks:m.tracks})}let y=m.initPTS,E=m.timescale;F(y)&&(this.initPTS[l.cc]={baseTime:y,timescale:E},s.trigger(v.INIT_PTS_FOUND,{frag:l,id:i,initPTS:y,timescale:E}))}if(d&&g&&l.sn!=="initSegment"){let y=g.fragments[l.sn-1-g.startSN],E=l.sn===g.startSN,T=!y||l.cc>y.cc;if(n.independent!==!1){let{startPTS:S,endPTS:x,startDTS:R,endDTS:b}=d;if(u)u.elementaryStreams[d.type]={startPTS:S,endPTS:x,startDTS:R,endDTS:b};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){let A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,_=d.firstKeyFramePTS?d.firstKeyFramePTS:S;if(!E&&I<_-this.config.maxBufferHole&&!T){this.backtrack(l);return}else T&&(l.gap=!0);l.setElementaryStreamInfo(d.type,l.start,x,l.start,b,!0)}else E&&S>Ui&&(l.gap=!0);l.setElementaryStreamInfo(d.type,S,x,R,b),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,u,a,E||T)}else if(E||T)l.gap=!0;else{this.backtrack(l);return}}if(p){let{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=p;u&&(u.elementaryStreams[Z.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),l.setElementaryStreamInfo(Z.AUDIO,y,E,T,S),this.bufferFragmentData(p,l,u,a)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){let y={id:i,frag:l,details:g,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,y)}if(g&&h){let y={id:i,frag:l,details:g,samples:h.samples};s.trigger(v.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,s){if(this.state!==k.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(v.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{let c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:l,data:c,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,H.MAIN)}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=k.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(ee.isBuffered(e,i)?t=this.getAppendedFrag(i):ee.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&F(t)&&F(i.programDateTime)){let s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},oi=class r{static get version(){return"1.5.11"}static isMSESupported(){return rl()}static isSupported(){return km()}static getMediaSource(){return yt()}static get Events(){return v}static get ErrorTypes(){return V}static get ErrorDetails(){return w}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:il}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new vn,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,gd(e.debug||!1,"Hls instance");let t=this.config=Dm(r.DefaultConfig,e);this.userConfig=e,t.progressive&&wm(t);let{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),u=this.abrController=new i(this),c=this.bufferController=new s(this),d=this.capLevelController=new n(this),h=new o(this),f=new rr(this),m=new or(this),g=t.contentSteeringController,p=g?new g(this):null,y=this.levelController=new nn(this,p),E=new pr(this),T=new an(this.config),S=this.streamController=new ln(this,E,T);d.setStreamController(S),h.setStreamController(S);let x=[f,y,S];p&&x.splice(1,0,p),this.networkControllers=x;let R=[u,c,d,h,m,E];this.audioTrackController=this.createController(t.audioTrackController,x);let b=t.audioStreamController;b&&x.push(new b(this,E,T)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);let A=t.subtitleStreamController;A&&x.push(new A(this,E,T)),this.createController(t.timelineController,R),T.emeController=this.emeController=this.createController(t.emeController,R),this.cmcdController=this.createController(t.cmcdController,R),this.latencyController=this.createController(lr,R),this.coreComponents=R,x.push(l);let I=l.onErrorOut;typeof I=="function"&&this.on(v.ERROR,I,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(L.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===v.ERROR;this.trigger(v.ERROR,{type:V.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){L.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){L.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){L.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,s=this.url=un.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,L.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){L.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){L.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){L.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){L.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){L.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){L.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){L.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){L.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){L.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(L.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dh(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}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()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let 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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};oi.defaultConfig=void 0;var re=oi,rt=class li extends Error{constructor(e,t=li.MEDIA_ERR_CUSTOM,i,s){var n;super(e),this.name="MediaError",this.code=t,this.context=s,this.fatal=i!=null?i:t>=li.MEDIA_ERR_NETWORK&&t<=li.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=li.defaultMessages[this.code])!=null?n:"")}};rt.MEDIA_ERR_ABORTED=1,rt.MEDIA_ERR_NETWORK=2,rt.MEDIA_ERR_DECODE=3,rt.MEDIA_ERR_SRC_NOT_SUPPORTED=4,rt.MEDIA_ERR_ENCRYPTED=5,rt.MEDIA_ERR_CUSTOM=100,rt.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var Tt=rt,Fm=r=>r==null,ml=(r,e)=>Fm(e)?!1:r in e,bn={ANY:"any",MUTED:"muted"},we={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Et={MSE:"mse",NATIVE:"native"},fs={HEADER:"header",QUERY:"query",NONE:"none"},Ug=Object.values(fs),at={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},An={HLS:at.M3U8},Bg=Object.keys(An),$g=[...Object.values(at),"hls","HLS"];var ge=(r,e,t,i,s=r)=>{s.addEventListener(e,t,i),r.addEventListener("teardown",()=>{s.removeEventListener(e,t)},{once:!0})};function Um(r,e,t){e&&t>e&&(t=e);for(let i=0;i<r.length;i++)if(r.start(i)<=t&&r.end(i)>=t)return!0;return!1}var Bm=r=>{let e=r.indexOf("?");if(e<0)return[r];let t=r.slice(0,e),i=r.slice(e);return[t,i]},gs=r=>{let e=r.type;if(e){let i=e.toUpperCase();return ml(i,An)?An[i]:e}let{src:t}=r;return t?$m(t):""},gl=r=>r==="VOD"?we.ON_DEMAND:we.LIVE,pl=r=>r==="EVENT"?Number.POSITIVE_INFINITY:r==="VOD"?Number.NaN:0,$m=r=>{let e="";try{e=new URL(r).pathname}catch{console.error("invalid url")}let t=e.lastIndexOf(".");if(t<0)return"";let i=e.slice(t+1).toUpperCase();return ml(i,at)?at[i]:""},Gm=Object.values(bn),nl=r=>typeof r=="boolean"||typeof r=="string"&&Gm.includes(r),Hm=(r,e,t)=>{let{autoplay:i}=r,s=!1,n=!1,a=nl(i)?i:!!i,o=()=>{s||ge(e,"playing",()=>{s=!0},{once:!0})};if(o(),ge(e,"loadstart",()=>{s=!1,o(),xn(e,a)},{once:!0}),ge(e,"loadstart",()=>{t||(r.streamType&&r.streamType!==we.UNKNOWN?n=r.streamType===we.LIVE:n=!Number.isFinite(e.duration)),xn(e,a)},{once:!0}),t&&t.once(re.Events.LEVEL_LOADED,(l,u)=>{var c;r.streamType&&r.streamType!==we.UNKNOWN?n=r.streamType===we.LIVE:n=(c=u.details.live)!=null?c:!1}),!a){let l=()=>{!n||Number.isFinite(r.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&ge(e,"play",()=>{e.preload==="metadata"?t.once(re.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{s||(a=nl(l)?l:!!l,xn(e,a))}},xn=(r,e)=>{if(!e)return;let t=r.muted,i=()=>r.muted=t;switch(e){case bn.ANY:r.play().catch(()=>{r.muted=!0,r.play().catch(i)});break;case bn.MUTED:r.muted=!0,r.play().catch(i);break;default:r.play().catch(()=>{});break}},Km=({preload:r,src:e},t,i)=>{let s=d=>{d!=null&&["","none","metadata","auto"].includes(d)?t.setAttribute("preload",d):t.removeAttribute("preload")};if(!i)return s(r),s;let n=!1,a=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,u=d=>{s(d);let h=d!=null?d:t.preload;a||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),c())},c=()=>{!n&&e&&(n=!0,i.loadSource(e))};return ge(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,c()},{once:!0}),u(r),u};function Vm(r,e){var t;if(!("videoTracks"in r))return;let i=new WeakMap;e.on(re.Events.MANIFEST_PARSED,function(u,c){l();let d=r.addVideoTrack("main");d.selected=!0;for(let[h,f]of c.levels.entries()){let m=d.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);i.set(f,`${h}`),m.id=`${h}`}}),e.on(re.Events.AUDIO_TRACKS_UPDATED,function(u,c){o();for(let d of c.audioTracks){let h=d.default?"main":"alternative",f=r.addAudioTrack(h,d.name,d.lang);f.id=`${d.id}`,d.default&&(f.enabled=!0)}}),r.audioTracks.addEventListener("change",()=>{var u;let c=+((u=[...r.audioTracks].find(h=>h.enabled))==null?void 0:u.id),d=e.audioTracks.map(h=>h.id);c!=e.audioTrack&&d.includes(c)&&(e.audioTrack=c)}),e.on(re.Events.LEVELS_UPDATED,function(u,c){var d;let h=r.videoTracks[(d=r.videoTracks.selectedIndex)!=null?d:0];if(!h)return;let f=c.levels.map(m=>i.get(m));for(let m of r.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let s=u=>{let c=u.target.selectedIndex;c!=e.nextLevel&&n(c)},n=u=>{let c=r.currentTime,d=!1,h=(f,m)=>{d||(d=!Number.isFinite(m.endOffset))};e.on(re.Events.BUFFER_FLUSHING,h),e.nextLevel=u,e.off(re.Events.BUFFER_FLUSHING,h),d||e.trigger(re.Events.BUFFER_FLUSHING,{startOffset:c+10,endOffset:1/0,type:"video"})};(t=r.videoRenditions)==null||t.addEventListener("change",s);let a=()=>{for(let u of r.videoTracks)r.removeVideoTrack(u)},o=()=>{for(let u of r.audioTracks)r.removeAudioTrack(u)},l=()=>{a(),o()};e.once(re.Events.DESTROYING,l)}var Sn=r=>"time"in r?r.time:r.startTime;function qm(r,e){e.on(re.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,{tracks:n})=>{n.forEach(a=>{var o;let l=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:c,name:d,type:h})=>c==(l==null?void 0:l.lang)&&d===a.label&&h.toLowerCase()===a.kind);vl(r,a.kind,a.label,l==null?void 0:l.lang,`${a.kind}${u}`)})});let t=()=>{var s;if(!e.subtitleTracks.length)return;let n=Array.from(r.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind)),a=`${(s=e.subtitleTracks[e.subtitleTrack])==null?void 0:s.type.toLowerCase()}${e.subtitleTrack}`;if(n&&(e.subtitleTrack<0||(n==null?void 0:n.id)!==a)){let o=e.subtitleTracks.findIndex(({lang:l,name:u,type:c})=>l==n.language&&u===n.label&&c.toLowerCase()===n.kind);e.subtitleTrack=o}n&&(n==null?void 0:n.id)===a&&n.cues&&Array.from(n.cues).forEach(o=>{n.addCue(o)})};r.textTracks.addEventListener("change",t),e.on(re.Events.CUES_PARSED,(s,{track:n,cues:a})=>{let o=r.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(u=>{var c;(c=o.cues)!=null&&c.getCueById(u.id)||o.addCue(u)}),l&&(o.mode="disabled")}),e.once(re.Events.DESTROYING,()=>{r.textTracks.removeEventListener("change",t),r.querySelectorAll("track[data-removeondestroy]").forEach(s=>{s.remove()})});let i=()=>{Array.from(r.textTracks).forEach(s=>{var n,a;if(!["subtitles","caption"].includes(s.kind)&&s.label==="thumbnails"){if(!((n=s.cues)!=null&&n.length)){let o=r.querySelector('track[label="thumbnails"]'),l=(a=o==null?void 0:o.getAttribute("src"))!=null?a:"";o==null||o.removeAttribute("src"),setTimeout(()=>{o==null||o.setAttribute("src",l)},0)}s.mode!=="hidden"&&(s.mode="hidden")}})};e.once(re.Events.MANIFEST_LOADED,i),e.once(re.Events.MEDIA_ATTACHED,i)}function vl(r,e,t,i,s){let n=document.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),s&&(n.id=s),n.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",n.setAttribute("data-removeondestroy",""),r.append(n),n.track}function Rn(r,e,t){var i;return(i=Array.from(r.querySelectorAll("track")).find(s=>s.track.label===e&&s.track.kind===t))==null?void 0:i.track}async function yl(r,e,t,i){let s=Rn(r,t,i);return s||(s=vl(r,i,t),s.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),s.mode!=="hidden"&&(s.mode="hidden"),[...e].sort((n,a)=>Sn(a)-Sn(n)).forEach(n=>{var a,o;let l=n.value,u=Sn(n);if("endTime"in n&&n.endTime!=null)s==null||s.addCue(new VTTCue(u,n.endTime,i==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let c=Array.prototype.findIndex.call(s==null?void 0:s.cues,m=>m.startTime>=u),d=(a=s==null?void 0:s.cues)==null?void 0:a[c],h=d?d.startTime:Number.isFinite(r.duration)?r.duration:Number.MAX_SAFE_INTEGER,f=(o=s==null?void 0:s.cues)==null?void 0:o[c-1];f&&(f.endTime=u),s==null||s.addCue(new VTTCue(u,h,i==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),r.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),s}var Tl="cuepoints",El=Object.freeze({label:Tl});async function Wm(r,e,t=El){return yl(r,e,t.label,"metadata")}var al=r=>({time:r.startTime,value:JSON.parse(r.text)});function Ym(r,e={label:Tl}){var t,i;let s=Rn(r,e.label,"metadata");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return al(s.activeCues[0]);let{currentTime:n}=r,a=Array.prototype.find.call((i=s.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return al(a||s.activeCues[0])}async function jm(r,e=El){return new Promise(t=>{ge(r,"loadstart",async()=>{let i=await Wm(r,[],e);ge(r,"cuechange",()=>{let s=Ym(r);if(s){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}var xl="chapters",Sl=Object.freeze({label:xl}),ol=r=>({startTime:r.startTime,endTime:r.endTime,value:r.text});async function zm(r,e,t=Sl){return yl(r,e,t.label,"chapters")}function Xm(r,e={label:xl}){var t,i;let s=Rn(r,e.label,"chapters");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return ol(s.activeCues[0]);let{currentTime:n}=r,a=Array.prototype.find.call((i=s.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return ol(a||s.activeCues[0])}async function Qm(r,e=Sl){return new Promise(t=>{ge(r,"loadstart",async()=>{let i=await zm(r,[],e);ge(r,"cuechange",()=>{let s=Xm(r);if(s){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}function _l(r,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-r.currentTime*1e3)}return typeof r.getStartDate=="function"?r.getStartDate():new Date(NaN)}function bl(r,e){if(e&&e.playingDate)return e.playingDate;if(typeof r.getStartDate=="function"){let t=r.getStartDate();return new Date(t.getTime()+r.currentTime*1e3)}return new Date(NaN)}var Jm=async r=>fetch(r).then(e=>e.text()).then(e=>{let t=e.split(`
|
|
41
41
|
`).find((i,s,n)=>s&&n[s-1].startsWith("#EXT-X-STREAM-INF"));return fetch(t).then(i=>i.text()).then(i=>i.split(`
|
|
42
|
-
`))}),Zm=r=>{var e,t,i;let s=(t=((e=r.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),n=gl(s),a=pl(s),o;if(n===we.LIVE){let l=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(l)o=+l.split(":")[1].split("=")[1]*2;else{let u=r.find(d=>d.startsWith("#EXT-X-TARGETDURATION")),c=(i=u==null?void 0:u.split(":"))==null?void 0:i[1];o=+(c!=null?c:6)*3}}return{streamType:n,targetLiveWindow:a,liveEdgeStartOffset:o}},eg=async(r,e)=>{if(e===at.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===at.M3U8){let t=await Jm(r);return Zm(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},_n=async(r,e,t=gs({src:r}))=>{var i,s,n;let{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}=await eg(r,t);((i=ke.get(e))!=null?i:{}).liveEdgeStartOffset=l,((s=ke.get(e))!=null?s:{}).targetLiveWindow=o,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((n=ke.get(e))!=null?n:{}).streamType=a,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},tg=r=>{var e;let t=r.type,i=gl(t),s=pl(t),n,a=!!((e=r.partList)!=null&&e.length);return i===we.LIVE&&(n=a?r.partTarget*2:r.targetduration*3),{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},ig=(r,e,t)=>{var i,s,n,a,o,l,u,c;let{streamType:d,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=tg(r);if(d===we.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let g=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var y;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(y=t.liveSyncPosition)!=null?y:e.seekable.end(p)}});((o=ke.get(e))!=null?o:{}).seekable=g}((l=ke.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=ke.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((c=ke.get(e))!=null?c:{}).streamType=d,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},ll,ul,sg=(ul=(ll=globalThis==null?void 0:globalThis.navigator)==null?void 0:ll.userAgent)!=null?ul:"",rg=sg.toLowerCase().indexOf("android")!==-1,ke=new WeakMap,nt="mux.com",cl,dl,Al=(dl=(cl=re).isSupported)==null?void 0:dl.call(cl),ng=rg,Ll=()=>xi.utils.now(),ag=xi.utils.generateUUID,Rl=({playbackId:r,customDomain:e=nt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,tokens:{playback:o}={},extraSourceParams:l={}}={})=>{if(!r)return;let[u,c=""]=Bm(r),d=new URL(`https://stream.${e}/${u}.m3u8${c}`);return o||d.searchParams.has("token")?(d.searchParams.forEach((h,f)=>{f!="token"&&d.searchParams.delete(f)}),o&&d.searchParams.set("token",o)):(t&&d.searchParams.set("max_resolution",t),i&&(d.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),s&&d.searchParams.set("rendition_order",s),n&&d.searchParams.set("program_start_time",`${n}`),a&&d.searchParams.set("program_end_time",`${a}`),Object.entries(l).forEach(([h,f])=>{f!=null&&d.searchParams.set(h,f)})),d.toString()},og=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Il=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(".m3u8");return e||void 0},lg=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Ol(r)&&(i=(t=og(r.playbackId))!=null?t:Il(r.src))!=null?i:r.src};var hl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.streamType)!=null?t:we.UNKNOWN};var fl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.seekable)!=null?t:r.seekable};var In=.034,ug=(r,e,t=In)=>Math.abs(r-e)<=t,Dl=(r,e,t=In)=>r>e||ug(r,e,t),cg=(r,e=In)=>r.paused&&Dl(r.currentTime,r.duration,e),wl=(r,e)=>{var t,i,s;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(s=e.levels.find(d=>!!d.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(r.currentTime<r.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(r.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=r.buffered.start(r.buffered.length-1),c=r.buffered.end(r.buffered.length-1);return l>u&&l<c},Dn=(r,e)=>r.ended||r.loop?r.ended:e&&wl(r,e)?!0:cg(r),kl=(r,e,t)=>{wn(e,t);let{metadata:i={}}=r,{view_session_id:s=ag()}=i,n=lg(r);i.view_session_id=s,i.video_id=n,r.metadata=i,ke.set(e,{});let a=dg(r,e),o=Km(r,e,a);vg(r,e,a),yg(r,e,a),jm(e),Qm(e);let l=Hm(r,e,a);return{engine:a,setAutoplay:l,setPreload:o}},wn=(r,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),r!=null&&r.mux&&!r.mux.deleted&&(r.mux.destroy(),delete r.mux),r&&(r.removeAttribute("src"),r.load(),r.removeEventListener("error",Nl),r.removeEventListener("error",Ln),r.removeEventListener("durationchange",Ml),ke.delete(r),r.dispatchEvent(new Event("teardown")))};function Cl(r,e){var t;let i=gs(r);if(i!==at.M3U8)return!0;let s=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=r,a=n===Et.MSE,o=n===Et.NATIVE;return s&&(o||!(Al&&(a||ng)))}var dg=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=r,l=gs(r)===at.M3U8,u=Cl(r,e);if(l&&!u&&Al){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=hg(i),h=fg(r),f=a!==fs.NONE?{useHeaders:a===fs.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0;return new re({debug:t,startPosition:s,cmcd:f,xhrSetup:(m,g)=>{var p,y;if(a&&a!==fs.QUERY)return;let E=new URL(g);if(!E.searchParams.has("CMCD"))return;let T=((y=(p=E.searchParams.get("CMCD"))==null?void 0:p.split(","))!=null?y:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");E.searchParams.set("CMCD",T),m.open("GET",E)},...c,...d,...h,...o})}},hg=r=>r===we.LIVE?{backBufferLength:8}:{},fg=r=>{let{drmToken:e,src:t,playbackId:i=Il(t)}=r;return!e||!i?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:ms(r,"fairplay"),serverCertificateUrl:Pl(r,"fairplay")},"com.widevine.alpha":{licenseUrl:ms(r,"widevine")},"com.microsoft.playready":{licenseUrl:ms(r,"playready")}},requestMediaKeySystemAccessFunc:(s,n)=>(s==="com.widevine.alpha"&&(n=[...n.map(a=>{var o;let l=(o=a.videoCapabilities)==null?void 0:o.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...a,videoCapabilities:l}}),...n]),navigator.requestMediaKeySystemAccess(s,n))}},mg=async r=>await(await fetch(r)).arrayBuffer(),gg=async(r,e)=>{let t=await(await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r})).arrayBuffer();return new Uint8Array(t)},pg=(r,e)=>{ge(e,"encrypted",async t=>{try{let i=t.initDataType;if(i!=="skd"){console.error(`Received unexpected initialization data type "${i}"`);return}if(!e.mediaKeys){let l=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[i],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}])).createMediaKeys(),u=await mg(Pl(r,"fairplay"));await l.setServerCertificate(u),await e.setMediaKeys(l)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.generateRequest(i,s);let a=await new Promise(l=>{n.addEventListener("message",u=>{l(u.message)},{once:!0})}),o=await gg(a,ms(r,"fairplay"));return await n.update(o),n}catch(i){console.error(`Could not start encrypted playback due to exception "${i}"`)}})},ms=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/license/${i}/${r}?token=${e}`,Pl=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/appcert/${i}/${r}?token=${e}`,Ol=({playbackId:r,src:e,customDomain:t})=>{if(r)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,s=new URL(e,i).hostname.toLocaleLowerCase();return s.includes(nt)||!!t&&s.includes(t.toLocaleLowerCase())},vg=(r,e,t)=>{var i;let{envKey:s,disableTracking:n}=r,a=Ol(r);if(!n&&(s||a)){let{playerInitTime:o,playerSoftwareName:l,playerSoftwareVersion:u,beaconCollectionDomain:c,debug:d,disableCookies:h}=r,f={...r.metadata,video_title:((i=r==null?void 0:r.metadata)==null?void 0:i.video_title)||void 0},m=g=>typeof g.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(g):g;xi.monitor(e,{debug:d,beaconCollectionDomain:c,hlsjs:t,Hls:t?re:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:h,data:{...s?{env_key:s}:{},player_software_name:l,player_software:l,player_software_version:u,player_init_time:o,...f}})}},yg=(r,e,t)=>{var i;let s=Cl(r,e),{src:n}=r,a=()=>{e.ended||!Dn(e,t)||(wl(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,l,u=()=>{var c,d;let h=(c=fl(e))==null?void 0:c.start(0),f=(d=fl(e))==null?void 0:d.end(0);(l!==f||o!==h)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=h,l=f};if(ge(e,"durationchange",u),e&&s){let c=gs(r);if(typeof n=="string"){let d=()=>{if(hl(e)!==we.LIVE||Number.isFinite(e.duration))return;let h=setInterval(u,1e3);e.addEventListener("teardown",()=>{clearInterval(h)},{once:!0}),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(h)})};if(e.preload==="none"){let h=()=>{_n(n,e,c).then(d),e.removeEventListener("loadedmetadata",f)},f=()=>{_n(n,e,c).then(d),e.removeEventListener("play",h)};ge(e,"play",h,{once:!0}),ge(e,"loadedmetadata",f,{once:!0})}else _n(n,e,c).then(d);r.drmToken&&pg(r,e),e.setAttribute("src",n),r.startTime&&(((i=ke.get(e))!=null?i:{}).startTime=r.startTime,e.addEventListener("durationchange",Ml,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Nl),e.addEventListener("error",Ln),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(d=>{d.remove()})},{once:!0}),ge(e,"pause",a),ge(e,"seeked",a),ge(e,"play",()=>{e.ended||Dl(e.currentTime,e.duration)&&(e.currentTime=e.seekable.start(0))})}else t&&n?(t.once(re.Events.LEVEL_LOADED,(c,d)=>{ig(d.details,e,t),u(),hl(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(re.Events.LEVEL_UPDATED,u),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(re.Events.LEVELS_UPDATED,u)}))}),t.on(re.Events.ERROR,(c,d)=>{let h={[re.ErrorTypes.NETWORK_ERROR]:Tt.MEDIA_ERR_NETWORK,[re.ErrorTypes.MEDIA_ERROR]:Tt.MEDIA_ERR_DECODE},f=new Tt("",h[d.type]);f.fatal=d.fatal,f.data=d,e.dispatchEvent(new CustomEvent("error",{detail:f}))}),e.addEventListener("error",Ln),ge(e,"waiting",a),Vm(r,t),qm(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Ml(r){var e;let t=r.target,i=(e=ke.get(t))==null?void 0:e.startTime;if(i&&Um(t.seekable,t.duration,i)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=i,s&&(t.preload="auto")}}async function Nl(r){if(!r.isTrusted)return;r.stopImmediatePropagation();let e=r.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,s=new Tt(t,i);if(e.src&&(i!==Tt.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:s}))}function Ln(r){var e,t;if(!(r instanceof CustomEvent)||!(r.detail instanceof Tt))return;let i=r.target,s=r.detail;!s||!s.fatal||(((e=ke.get(i))!=null?e:{}).error=s,(t=i.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var Tg=()=>{try{return"0.13.1"}catch{}return"UNKNOWN"},Eg=Tg(),Fl=()=>Eg;var $l=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function xg(r){return`
|
|
42
|
+
`))}),Zm=r=>{var e,t,i;let s=(t=((e=r.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),n=gl(s),a=pl(s),o;if(n===we.LIVE){let l=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(l)o=+l.split(":")[1].split("=")[1]*2;else{let u=r.find(d=>d.startsWith("#EXT-X-TARGETDURATION")),c=(i=u==null?void 0:u.split(":"))==null?void 0:i[1];o=+(c!=null?c:6)*3}}return{streamType:n,targetLiveWindow:a,liveEdgeStartOffset:o}},eg=async(r,e)=>{if(e===at.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===at.M3U8){let t=await Jm(r);return Zm(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},_n=async(r,e,t=gs({src:r}))=>{var i,s,n;let{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}=await eg(r,t);((i=ke.get(e))!=null?i:{}).liveEdgeStartOffset=l,((s=ke.get(e))!=null?s:{}).targetLiveWindow=o,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((n=ke.get(e))!=null?n:{}).streamType=a,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},tg=r=>{var e;let t=r.type,i=gl(t),s=pl(t),n,a=!!((e=r.partList)!=null&&e.length);return i===we.LIVE&&(n=a?r.partTarget*2:r.targetduration*3),{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},ig=(r,e,t)=>{var i,s,n,a,o,l,u,c;let{streamType:d,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=tg(r);if(d===we.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let g=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var y;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(y=t.liveSyncPosition)!=null?y:e.seekable.end(p)}});((o=ke.get(e))!=null?o:{}).seekable=g}((l=ke.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=ke.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((c=ke.get(e))!=null?c:{}).streamType=d,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},ll,ul,sg=(ul=(ll=globalThis==null?void 0:globalThis.navigator)==null?void 0:ll.userAgent)!=null?ul:"",rg=sg.toLowerCase().indexOf("android")!==-1,ke=new WeakMap,nt="mux.com",cl,dl,Al=(dl=(cl=re).isSupported)==null?void 0:dl.call(cl),ng=rg,Ll=()=>xi.utils.now(),ag=xi.utils.generateUUID,Rl=({playbackId:r,customDomain:e=nt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,tokens:{playback:o}={},extraSourceParams:l={}}={})=>{if(!r)return;let[u,c=""]=Bm(r),d=new URL(`https://stream.${e}/${u}.m3u8${c}`);return o||d.searchParams.has("token")?(d.searchParams.forEach((h,f)=>{f!="token"&&d.searchParams.delete(f)}),o&&d.searchParams.set("token",o)):(t&&d.searchParams.set("max_resolution",t),i&&(d.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),s&&d.searchParams.set("rendition_order",s),n&&d.searchParams.set("program_start_time",`${n}`),a&&d.searchParams.set("program_end_time",`${a}`),Object.entries(l).forEach(([h,f])=>{f!=null&&d.searchParams.set(h,f)})),d.toString()},og=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Il=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(".m3u8");return e||void 0},lg=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Ol(r)&&(i=(t=og(r.playbackId))!=null?t:Il(r.src))!=null?i:r.src};var hl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.streamType)!=null?t:we.UNKNOWN};var fl=r=>{var e,t;return(t=(e=ke.get(r))==null?void 0:e.seekable)!=null?t:r.seekable};var In=.034,ug=(r,e,t=In)=>Math.abs(r-e)<=t,Dl=(r,e,t=In)=>r>e||ug(r,e,t),cg=(r,e=In)=>r.paused&&Dl(r.currentTime,r.duration,e),wl=(r,e)=>{var t,i,s;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(s=e.levels.find(d=>!!d.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(r.currentTime<r.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(r.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=r.buffered.start(r.buffered.length-1),c=r.buffered.end(r.buffered.length-1);return l>u&&l<c},Dn=(r,e)=>r.ended||r.loop?r.ended:e&&wl(r,e)?!0:cg(r),kl=(r,e,t)=>{wn(e,t);let{metadata:i={}}=r,{view_session_id:s=ag()}=i,n=lg(r);i.view_session_id=s,i.video_id=n,r.metadata=i,ke.set(e,{});let a=dg(r,e),o=Km(r,e,a);vg(r,e,a),yg(r,e,a),jm(e),Qm(e);let l=Hm(r,e,a);return{engine:a,setAutoplay:l,setPreload:o}},wn=(r,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),r!=null&&r.mux&&!r.mux.deleted&&(r.mux.destroy(),delete r.mux),r&&(r.removeAttribute("src"),r.load(),r.removeEventListener("error",Nl),r.removeEventListener("error",Ln),r.removeEventListener("durationchange",Ml),ke.delete(r),r.dispatchEvent(new Event("teardown")))};function Cl(r,e){var t;let i=gs(r);if(i!==at.M3U8)return!0;let s=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=r,a=n===Et.MSE,o=n===Et.NATIVE;return s&&(o||!(Al&&(a||ng)))}var dg=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=r,l=gs(r)===at.M3U8,u=Cl(r,e);if(l&&!u&&Al){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=hg(i),h=fg(r),f=a!==fs.NONE?{useHeaders:a===fs.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0;return new re({debug:t,startPosition:s,cmcd:f,xhrSetup:(m,g)=>{var p,y;if(a&&a!==fs.QUERY)return;let E=new URL(g);if(!E.searchParams.has("CMCD"))return;let T=((y=(p=E.searchParams.get("CMCD"))==null?void 0:p.split(","))!=null?y:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");E.searchParams.set("CMCD",T),m.open("GET",E)},...c,...d,...h,...o})}},hg=r=>r===we.LIVE?{backBufferLength:8}:{},fg=r=>{let{drmToken:e,src:t,playbackId:i=Il(t)}=r;return!e||!i?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:ms(r,"fairplay"),serverCertificateUrl:Pl(r,"fairplay")},"com.widevine.alpha":{licenseUrl:ms(r,"widevine")},"com.microsoft.playready":{licenseUrl:ms(r,"playready")}},requestMediaKeySystemAccessFunc:(s,n)=>(s==="com.widevine.alpha"&&(n=[...n.map(a=>{var o;let l=(o=a.videoCapabilities)==null?void 0:o.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...a,videoCapabilities:l}}),...n]),navigator.requestMediaKeySystemAccess(s,n))}},mg=async r=>await(await fetch(r)).arrayBuffer(),gg=async(r,e)=>{let t=await(await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r})).arrayBuffer();return new Uint8Array(t)},pg=(r,e)=>{ge(e,"encrypted",async t=>{try{let i=t.initDataType;if(i!=="skd"){console.error(`Received unexpected initialization data type "${i}"`);return}if(!e.mediaKeys){let l=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[i],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}])).createMediaKeys(),u=await mg(Pl(r,"fairplay"));await l.setServerCertificate(u),await e.setMediaKeys(l)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.generateRequest(i,s);let a=await new Promise(l=>{n.addEventListener("message",u=>{l(u.message)},{once:!0})}),o=await gg(a,ms(r,"fairplay"));return await n.update(o),n}catch(i){console.error(`Could not start encrypted playback due to exception "${i}"`)}})},ms=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/license/${i}/${r}?token=${e}`,Pl=({playbackId:r,drmToken:e,customDomain:t=nt},i)=>`https://license.${t.toLocaleLowerCase().endsWith(nt)?t:nt}/appcert/${i}/${r}?token=${e}`,Ol=({playbackId:r,src:e,customDomain:t})=>{if(r)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,s=new URL(e,i).hostname.toLocaleLowerCase();return s.includes(nt)||!!t&&s.includes(t.toLocaleLowerCase())},vg=(r,e,t)=>{var i;let{envKey:s,disableTracking:n}=r,a=Ol(r);if(!n&&(s||a)){let{playerInitTime:o,playerSoftwareName:l,playerSoftwareVersion:u,beaconCollectionDomain:c,debug:d,disableCookies:h}=r,f={...r.metadata,video_title:((i=r==null?void 0:r.metadata)==null?void 0:i.video_title)||void 0},m=g=>typeof g.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(g):g;xi.monitor(e,{debug:d,beaconCollectionDomain:c,hlsjs:t,Hls:t?re:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:h,data:{...s?{env_key:s}:{},player_software_name:l,player_software:l,player_software_version:u,player_init_time:o,...f}})}},yg=(r,e,t)=>{var i;let s=Cl(r,e),{src:n}=r,a=()=>{e.ended||!Dn(e,t)||(wl(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,l,u=()=>{var c,d;let h=(c=fl(e))==null?void 0:c.start(0),f=(d=fl(e))==null?void 0:d.end(0);(l!==f||o!==h)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=h,l=f};if(ge(e,"durationchange",u),e&&s){let c=gs(r);if(typeof n=="string"){let d=()=>{if(hl(e)!==we.LIVE||Number.isFinite(e.duration))return;let h=setInterval(u,1e3);e.addEventListener("teardown",()=>{clearInterval(h)},{once:!0}),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(h)})};if(e.preload==="none"){let h=()=>{_n(n,e,c).then(d),e.removeEventListener("loadedmetadata",f)},f=()=>{_n(n,e,c).then(d),e.removeEventListener("play",h)};ge(e,"play",h,{once:!0}),ge(e,"loadedmetadata",f,{once:!0})}else _n(n,e,c).then(d);r.drmToken&&pg(r,e),e.setAttribute("src",n),r.startTime&&(((i=ke.get(e))!=null?i:{}).startTime=r.startTime,e.addEventListener("durationchange",Ml,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Nl),e.addEventListener("error",Ln),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(d=>{d.remove()})},{once:!0}),ge(e,"pause",a),ge(e,"seeked",a),ge(e,"play",()=>{e.ended||Dl(e.currentTime,e.duration)&&(e.currentTime=e.seekable.start(0))})}else t&&n?(t.once(re.Events.LEVEL_LOADED,(c,d)=>{ig(d.details,e,t),u(),hl(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(re.Events.LEVEL_UPDATED,u),ge(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(re.Events.LEVELS_UPDATED,u)}))}),t.on(re.Events.ERROR,(c,d)=>{let h={[re.ErrorTypes.NETWORK_ERROR]:Tt.MEDIA_ERR_NETWORK,[re.ErrorTypes.MEDIA_ERROR]:Tt.MEDIA_ERR_DECODE},f=new Tt("",h[d.type]);f.fatal=d.fatal,f.data=d,e.dispatchEvent(new CustomEvent("error",{detail:f}))}),e.addEventListener("error",Ln),ge(e,"waiting",a),Vm(r,t),qm(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Ml(r){var e;let t=r.target,i=(e=ke.get(t))==null?void 0:e.startTime;if(i&&Um(t.seekable,t.duration,i)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=i,s&&(t.preload="auto")}}async function Nl(r){if(!r.isTrusted)return;r.stopImmediatePropagation();let e=r.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,s=new Tt(t,i);if(e.src&&(i!==Tt.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:s}))}function Ln(r){var e,t;if(!(r instanceof CustomEvent)||!(r.detail instanceof Tt))return;let i=r.target,s=r.detail;!s||!s.fatal||(((e=ke.get(i))!=null?e:{}).error=s,(t=i.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var Tg=()=>{try{return"0.13.2"}catch{}return"UNKNOWN"},Eg=Tg(),Fl=()=>Eg;var $l=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function xg(r){return`
|
|
43
43
|
<style>
|
|
44
44
|
:host {
|
|
45
45
|
display: inline-flex;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mux/mux-audio",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.2",
|
|
4
4
|
"description": "A custom mux audio element for the browser that Just Works™",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"audio",
|
|
@@ -65,16 +65,16 @@
|
|
|
65
65
|
"publish-release": "../../scripts/publish.sh"
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@mux/playback-core": "0.25.
|
|
68
|
+
"@mux/playback-core": "0.25.1",
|
|
69
69
|
"custom-media-element": "~1.3.1"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
|
-
"@open-wc/testing": "^
|
|
72
|
+
"@open-wc/testing": "^4.0.0",
|
|
73
73
|
"@typescript-eslint/eslint-plugin": "^5.48.0",
|
|
74
74
|
"@typescript-eslint/parser": "^5.48.0",
|
|
75
|
-
"@web/dev-server-esbuild": "^0.
|
|
76
|
-
"@web/dev-server-import-maps": "^0.
|
|
77
|
-
"@web/test-runner": "^0.
|
|
75
|
+
"@web/dev-server-esbuild": "^1.0.2",
|
|
76
|
+
"@web/dev-server-import-maps": "^0.2.1",
|
|
77
|
+
"@web/test-runner": "^0.18.2",
|
|
78
78
|
"downlevel-dts": "^0.11.0",
|
|
79
79
|
"esbuild": "^0.19.8",
|
|
80
80
|
"eslint": "^8.24.0",
|
|
@@ -84,5 +84,5 @@
|
|
|
84
84
|
"shx": "^0.3.4",
|
|
85
85
|
"typescript": "^4.9.4"
|
|
86
86
|
},
|
|
87
|
-
"gitHead": "
|
|
87
|
+
"gitHead": "31bf5057d37d4e57b630012fc09d52daedb2973a"
|
|
88
88
|
}
|