@mux/playback-core 0.32.2-canary.0 → 0.32.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.
@@ -55,7 +55,7 @@ Schedule: ${u.map(m=>tt(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Remo
55
55
  `:(n=i.childNodes)!=null&&n.length?ju(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Op(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,u)=>{let l=Cr(e,i,u)||Cr(r,i,u)||Cr(s,i,u);return l&&(o[u]=l),o},{})}function Cr(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function xl(r){return new Error(`Could not parse ttml timestamp ${r}`)}function wr(r,e){if(!r)return null;let t=Ku(r);return t===null&&(Wu.test(r)?t=Np(r,e):Yu.test(r)&&(t=Fp(r,e))),t}function Np(r,e){let t=Wu.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 Fp(r,e){let t=Yu.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 Zt=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Wn=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=Al(),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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Zt(this,"textTrack1"),t=new Zt(this,"textTrack2"),i=new Zt(this,"textTrack3"),s=new Zt(this,"textTrack4");this.cea608Parser1=new Us(1,e,t),this.cea608Parser2=new Us(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){let u=n[o],l=Up(u[0],u[1],t,i);if(l>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],i),a=!0,l/(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(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;i===G.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(u=>{this.initPTS[u.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,u):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:u.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){let n=i.textTracks[s];if(bl(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))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,Jt(i[e]),Bu(i[e],s);else{let u=this.createTextTrack("captions",n,a);u&&(u[e]=!0,i[e]=u)}}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(y.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,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:s}=this;Object.keys(s).forEach(n=>{Jt(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Al(),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++)Jt(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===Pr);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Lu(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?fs(a.textTracks):null;if(this.tracks.forEach((u,l)=>{let c;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&bl(o[h],u)){d=o[h],o[h]=null;break}d&&(c=d)}if(c)Jt(c);else{let d=Xu(u);c=this.createTextTrack(d,u.name,u.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){let u=o.filter(l=>l!==null).map(l=>l.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.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(y.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===G.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:u,sn:l}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(l!==o+1||l===o&&c!==this.lastPartIndex+1||u!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=u,this.lastSn=l,this.lastPartIndex=c}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.type===G.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],u=this.vttCCs;u[i.cc]||(u[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Pr?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;_l(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(y.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 u=this.hls,l=(t=i.initSegment)!=null&&t.data?Xe(i.initSegment.data,new Uint8Array(s)).buffer:s;Cp(l,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),u.trigger(y.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),u.logger.log(`Failed to parse VTT cue: ${c}`),!(d&&o>i.cc)&&u.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||_l(t,this.initPTS[e.cc],()=>{i.textCodec=Pr,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=>$u(s,n))}else{let s=this.tracks[t];if(!s)return;let n=s.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===G.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:s}=t;if(!(i.type===G.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){let a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[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(u=>Pn(o[u],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(u=>Pn(o[u],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++],u=127&e[s++];if(o===0&&u===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(u))}}return t}};function Xu(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function bl(r,e){return!!r&&r.kind===Xu(e)&&vn(e,r)}function Up(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Al(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var Bp=/\s/,$p={newCue(r,e,t,i){let s=[],n,a,o,u,l,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=!0,u=0,l="",!n.isEmpty()){var d;for(let m=0;m<n.chars.length;m++)Bp.test(n.chars[m].uchar)&&o?u++:(l+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;let f=qu(l.trim()),g=Ta(e,t,f);r!=null&&(d=r.cues)!=null&&d.getCueById(g)||(a=new c(e,t,f),a.id=g,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(u*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=>$u(r,h))),s}};function Gp(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Hp=/(\d+)-(\d+)\/(\d+)/,Bs=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||Wp,this.controller=new self.AbortController,this.stats=new xi}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=Kp(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&U(u)?u:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(Ci(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var h;this.response=this.loader=d;let f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(f-s.loading.start)),!d.ok){let{status:m,statusText:p}=d;throw new Yn(p||"fetch, bad network response",m,d)}s.loading.first=f,s.total=qp(d.headers)||s.total;let g=(h=this.callbacks)==null?void 0:h.onProgress;return g&&U(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,g):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,f;let g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let m=d[o];m&&(s.loaded=s.total=m);let p={url:g.url,data:d,code:g.status},E=(h=this.callbacks)==null?void 0:h.onProgress;E&&!U(t.highWaterMark)&&E(s,e,d,g),(f=this.callbacks)==null||f.onSuccess(p,s,e,g)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),s.aborted)return;let f=d&&d.code||0,g=d?d.message:null;(h=this.callbacks)==null||h.onError({code:f,text:g},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 Rs,o=e.body.getReader(),u=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=l.value,d=c.length;return t.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,c.buffer,e),u()}).catch(()=>Promise.reject());return u()}};function Kp(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(le({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Vp(r){let e=Hp.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function qp(r){let e=r.get("Content-Range");if(e){let i=Vp(e);if(U(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function Wp(r,e){return new self.Request(r.url,e)}var Yn=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Yp=/^age:\s*[\d.]+\s*$/im,$s=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 xi,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=>{var o;(o=this.callbacks)==null||o.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&&U(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 l=t.status,c=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){let g=c!=null?c:t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(i,e,g,t);let E={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(E,i,e,t);return}}let d=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:l};if(Ss(d,h,!1,f))this.retry(d);else{var u;oe.error(`${l} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ss(e,t,!0))this.retry(e);else{var i;oe.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=oa(e,i.retry),i.retry++,oe.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&&Yp.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}},jp={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Xp=ae(ae({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:$s,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Kr,bufferController:Sn,capLevelController:xn,errorController:qr,fpsController:Dn,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:Zl,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:jp},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},zp()),{},{subtitleStreamController:Fn,subtitleTrackController:kn,timelineController:Wn,audioStreamController:yn,audioTrackController:Tn,emeController:Ms,cmcdController:Ln,contentSteeringController:Rn,interstitialsController:Nn});function zp(){return{cueHandler:$p,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 Qp(r,e,t){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 i=jn(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,u=e[o]===void 0,l=[];n.forEach(c=>{let d=`${a}Loading${c}`,h=e[d];if(h!==void 0&&u){l.push(d);let f=i[o].default;switch(e[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${de(e[o])}`)}),ae(ae({},i),e)}function jn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(jn):Object.keys(r).reduce((e,t)=>(e[t]=jn(r[t]),e),{}):r}function Jp(r,e){let t=r.loader;t!==Bs&&t!==$s?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Gp()&&(r.loader=Bs,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var gs=2,Zp=.1,e0=.05,t0=100,Xn=class extends xs{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(t0),this.mediaSource=t.mediaSource;let i=this.media=t.media;Oe(i,"playing",this.onMediaPlaying),Oe(i,"waiting",this.onMediaWaiting),Oe(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(Ue(i,"playing",this.onMediaPlaying),Ue(i,"waiting",this.onMediaWaiting),Ue(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,u=this.seeking&&!o,l=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||u){u&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!Q.getBuffered(a).length){this.nudgeRetry=0;return}let d=Q.bufferInfo(a,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let A=Il(this.hls.inFlightFragments,e),x=d.len>gs,I=!h||A||h-e>gs&&!f.getPartialFragment(e);if(x||I)return;this.moved=!1}let g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;let x=Math.max(h,d.start||0)-e,L=!!(g!=null&&g.live)?g.targetduration*2:gs,b=as(e,f);if(x>0&&(x<=L||b)){a.paused||this._trySkipBufferHole(b);return}}let m=n.detectStallWithCurrentTimeMs,p=self.performance.now(),E=this.waiting,v=this.stalled;if(v===null)if(E>0&&p-E<m)v=this.stalled=E;else{this.stalled=p;return}let T=p-v;if(!o&&(T>=m||E)&&this.hls){var _;if(((_=this.mediaSource)==null?void 0:_.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}let S=Q.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){let n=Q.bufferedInfo(Q.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=Q.timeRangesToArray(s),o=Q.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let u=Q.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,c=a[o+1].start;if((u===-1||u>o)&&c-l<1&&e-l<2){let d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${c} buffered index: ${u}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=as(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=Q.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var s,n;let{fragmentTracker:a,media:o}=this,u=(s=this.hls)==null?void 0:s.config;if(!o||!a||!u)return;let l=(n=this.hls)==null?void 0:n.latestLevelDetails,c=as(i,a);if((c||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let d=e.buffered,h=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>u.maxBufferHole||e.nextStart&&(e.nextStart-i<u.maxBufferHole||h))&&(t>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,s=e.nextStart;if(i&&s){let n=i.getFragAtPos(t,G.MAIN),a=i.getFragAtPos(s,G.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${de(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;let a=s.currentTime,o=Q.bufferInfo(s,a,0),u=a<o.start?o.start:o.nextStart;if(u&&this.hls){let c=o.len<=n.maxBufferHole,d=o.len>0&&o.len<1&&s.readyState<3,h=u-a;if(h>0&&(c||d)){if(h>n.maxBufferHole){let g=!1;if(a===0){let m=i.getAppendedFrag(0,G.MAIN);m&&u<m.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Il(this.hls.inFlightFragments,u))return 0;let p=!1,E=e.end;for(;E<u;){let v=as(E,i);if(v)E+=v.duration;else{p=!0;break}}if(p)return 0}}let f=Math.max(u+e0,a+Zp);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(e!=null&&e.gap)){let g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),m={type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(y.ERROR,m)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,n=t==null?void 0:t.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){let o=a+(s+1)*n.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(u.message),i.currentTime=o,t.trigger(y.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Il(r,e){let t=Ll(r.main);if(t&&t.start<=e)return t;let i=Ll(r.audio);return i&&i.start<=e?i:null}function Ll(r){if(!r)return null;switch(r.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return r.frag}function as(r,e){return e.getAppendedFrag(r,G.MAIN)||e.getPartialFragment(r)}var i0=.25;function zn(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function Mr(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,de(s?ae({type:s},i):i))}return n}var os=(()=>{let r=zn();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Qn=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Jt(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Bu(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=zn();if(a)for(let o=0;o<n.length;o++){let u=n[o].type;if(u===Ke.emsg&&!i||!s)continue;let l=pu(n[o].data),c=n[o].pts,d=c+n[o].duration;d>os&&(d=os),d-c<=0&&(d=c+i0);for(let f=0;f<l.length;f++){let g=l[f];if(!yu(g)){this.updateId3CueEnds(c,u);let m=Mr(a,c,d,g,u);m&&this.id3Track.addCue(m)}}}}updateId3CueEnds(e,t){var i;let s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){let a=s[n];a.type===t&&a.startTime<e&&a.endTime===os&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:u}}=a;if(n&&(o||u)){let l;s==="audio"?l=c=>c.type===Ke.audioId3&&u:s==="video"?l=c=>c.type===Ke.emsg&&o:l=c=>c.type===Ke.audioId3&&u||c.type===Ke.emsg&&o,Pn(n,t,i,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=zn();if(i&&s&&!a){let{fragmentStart:m,fragmentEnd:p}=e,E=this.assetCue;E?(E.startTime=m,E.endTime=p):o&&(E=this.assetCue=Mr(o,m,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:u}=this,{dateRanges:l}=e,c=Object.keys(l),d=this.dateRangeCuesAppended;if(u&&t){var h;if((h=u.cues)!=null&&h.length){let m=Object.keys(d).filter(p=>!c.includes(p));for(let p=m.length;p--;){var f;let E=m[p],v=(f=d[E])==null?void 0:f.cues;delete d[E],v&&Object.keys(v).forEach(T=>{let _=v[T];if(_){_.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(_)}catch{}}})}}else d=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(c.length===0||!U(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<c.length;m++){let p=c[m],E=l[p],v=E.startTime,T=d[p],_=(T==null?void 0:T.cues)||{},S=(T==null?void 0:T.durationKnown)||!1,A=os,{duration:x,endDate:I}=E;if(I&&x!==null)A=v+x,S=!0;else if(E.endOnNext&&!S){let b=c.reduce((D,k)=>{if(k!==E.id){let F=l[k];if(F.class===E.class&&F.startDate>E.startDate&&(!D||E.startDate<D.startDate))return F}return D},null);b&&(A=b.startTime,S=!0)}let L=Object.keys(E.attr);for(let b=0;b<L.length;b++){let D=L[b];if(!og(D))continue;let k=_[D];if(k)S&&!(T!=null&&T.durationKnown)?k.endTime=A:Math.abs(k.startTime-v)>.01&&(k.startTime=v,k.endTime=A);else if(o){let F=E.attr[D];lg(D)&&(F=kl(F));let B=Mr(o,v,A,{key:D,data:F},Ke.dateRange);B&&(B.id=p,this.id3Track.addCue(B),_[D]=B,a&&(D==="X-ASSET-LIST"||D==="X-ASSET-URL")&&B.addEventListener("enter",this.onEventCueEnter))}}d[p]={cues:_,dateRange:E,durationKnown:S}}}}},Jn=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let s=this.computeLatency();if(s===null)return;this._latency=s;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;let o=this.targetLatency;if(o===null)return;let u=s-o,l=Math.min(this.maxLatency,o+i.targetduration);if(u<l&&u>.05&&this.forwardBufferLength>1){let d=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,u=this.hls.userConfig,l=o&&i||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*s);let c=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let i=this.levelDetails;if(i===null)return null;let s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Zn=class extends wi{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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,u=!1,l=!1;t.levels.forEach(c=>{let d=c.attrs,{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=ys(h,i)||void 0),f&&(f=c.videoCodec=kf(f));let{width:g,height:m,unknownCodecs:p}=c,E=(p==null?void 0:p.length)||0;if(o||(o=!!(g&&m)),u||(u=!!f),l||(l=!!h),E||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}let{CODECS:v,"FRAME-RATE":T,"HDCP-LEVEL":_,"PATHWAY-ID":S,RESOLUTION:A,"VIDEO-RANGE":x}=d,L=`${`${S||"."}-`}${c.bitrate}-${A}-${T}-${v}-${x}-${_}`;if(n[L])if(n[L].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let b=a[L]+=1;c.attrs["PATHWAY-ID"]=new Array(b+1).join(".");let D=this.createLevel(c);n[L]=D,s.push(D)}else n[L].addGroupId("audio",d.AUDIO),n[L].addGroupId("text",d.SUBTITLES);else{let b=this.createLevel(c);n[L]=b,a[L]=1,s.push(b)}}),this.filterAndSortMediaOptions(s,t,o,u,l)}createLevel(e){let t=new Ht(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=Hl(s,[])}return t}isAudioSupported(e){return bi(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return bi(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){var a;let o=[],u=[],l=e,c=((a=t.stats)==null?void 0:a.parsing)||{};if((i||s)&&n&&(l=l.filter(({videoCodec:v,videoRange:T,width:_,height:S})=>(!!v||!!(_&&S))&&Gf(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${de(t.levels.map(S=>S.attrs.CODECS).filter((S,A,x)=>x.indexOf(S)===A))}`,this.warn(T),v+=` (${T})`);let _=new Error(v);this.hls.trigger(y.ERROR,{type:q.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:_,reason:T})}}),c.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),Rl(o)),t.subtitles&&(u=t.subtitles,Rl(u));let d=l.slice(0);l.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return vs.indexOf(v.videoRange)-vs.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){let _=bo(v.videoCodec),S=bo(T.videoCodec);if(_!==S)return S-_}if(v.uri===T.uri&&v.codecSet!==T.codecSet){let _=ps(v.codecSet),S=ps(T.codecSet);if(_!==S)return S-_}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let h=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let v=0;v<d.length;v++)if(d[v].pathwayId===l[0].pathwayId){h=d[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===h){var f;this._firstLevel=v;let T=h.bitrate,_=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let S=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);S>_&&_===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}let g=n&&!s,m=this.hls.config,p=!!(m.audioStreamController&&m.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:p&&!g&&o.some(v=>!!v.url)};c.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}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(y.ERROR,{type:q.OTHER_ERROR,details:R.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&&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 u={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(y.LEVEL_SWITCHING,u);let l=a.details;if(!l||l.live){let c=this.switchParams(a.uri,s==null?void 0:s.details,l);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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===ee.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===G.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=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let u=a.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(s,t,u)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||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;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));ou(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Rl(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function zu(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qu(){if(!At())return!1;let e=zu();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function s0(){if(!Qu())return!1;let r=At();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(Ai(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Ai(e,"audio"))))}function r0(){var r;let e=zu();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var n0=100,ea=class extends Ri{constructor(e,t,i){super(e,t,i,"stream-controller",G.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,n=s?s.currentTime:null;if(n===null||!U(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(s,n,G.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(n0),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let u=this.getLevelDetails();if(u&&this._streamEnded(o,u)){let m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(y.BUFFER_EOS,m),this.state=P.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let l=a.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;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,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ve(f)&&this.fragmentTracker.getState(f)!==be.OK){var g;let p=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,E=l.fragments[p-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?ce.AUDIO:ce.VIDEO,E=(p===ce.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,p,G.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,G.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);s===be.NOT_LOADED||s===be.PARTIAL?ve(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,G.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,u=e[o],l=this.fragLastKbps;l&&this.fragCurrent?i=this.fragCurrent.duration*u.maxBitrate/(1e3*l)+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 u=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,c=Math.max(a.end,u+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(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 P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;Oe(i,"playing",this.onMediaPlaying),Oe(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(Ue(i,"playing",this.onMediaPlaying),Ue(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!r0(),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!==P.IDLE)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,u=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${u}`);let l=t.levelInfo,c=this.fragCurrent;c&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,d),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,u=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!u)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!u&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;let d=Q.bufferInfo(i,s,0);if(!((l=d.buffered)!=null&&l.length)){i.currentTime=s;return}if(d.start<=n){i.currentTime=s;return}let{nextStart:f}=Q.bufferedInfo(d.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{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];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let u=o.details;if(!u){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let l=o.videoCodec,c=u.PTSKnown||!u.live,d=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Cs(this.hls,G.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=g!==-1,p=new Li(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,m),E=this.initPTS[i.cc];f.push(n,d,h,l,i,s,u.totalduration,c,p,E)}onAudioTrackSwitching(e,t){let i=this.hls,s=this.altAudio!==0;if(Es(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;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();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),i.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=Es(t.url,this.hls);if(i){let s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let u=i[o];if(u.id==="main"){if(n=o,s=u,o==="video"){let l=i[o];l&&(this.videoBuffer=l.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,n=i.type===G.MAIN;if(n){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===P.PARSED&&(this.state=P.IDLE);return}let o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ve(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}let a=this.media;a&&(!this._hasEnoughToStart&&Q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(G.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ce.AUDIO||!this.altAudio){let i=(t===ce.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,G.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;s&&i&&(i+=s);let n=this.getLevelDetails(),a=Q.getBuffered(e),o=a.length?a.start(0):0,u=o-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<l||this.loadingParts&&u<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),i+=u,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),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,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:u,level:l}=a,{video:c,text:d,id3:h,initSegment:f}=s,{details:g}=l,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){let p=f.tracks;if(p){let _=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,p,_,n),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:_,id:t,tracks:p})}let E=f.initPTS,v=f.timescale,T=this.initPTS[o.cc];if(U(E)&&(!T||T.baseTime!==E||T.timescale!==v)){let _=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:v,trackId:_},i.trigger(y.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:v,trackId:_})}}if(c&&g){m&&c.type==="audiovideo"&&this.logMuxedErr(o);let p=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,v=!p||o.cc>p.cc;if(s.independent!==!1){let{startPTS:T,endPTS:_,startDTS:S,endDTS:A}=c;if(u)u.elementaryStreams[c.type]={startPTS:T,endPTS:_,startDTS:S,endDTS:A};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!v&&(this.couldBacktrack=!0),c.dropped&&c.independent){let x=this.getMainFwdBufferInfo(),I=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,L=c.firstKeyFramePTS?c.firstKeyFramePTS:T;if(!E&&I<L-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(c.type,o.start,_,o.start,A,!0)}else E&&T-(g.appliedTimelineOffset||0)>gs&&(o.gap=!0);o.setElementaryStreamInfo(c.type,T,_,S,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,u,n,E||v)}else if(E||v)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:p,endPTS:E,startDTS:v,endDTS:T}=m;u&&(u.elementaryStreams[ce.AUDIO]={startPTS:p,endPTS:E,startDTS:v,endDTS:T}),o.setElementaryStreamInfo(ce.AUDIO,p,E,v,T),this.bufferFragmentData(m,o,u,n)}if(g&&h!=null&&h.samples.length){let p={id:t,frag:o,details:g,samples:h.samples};i.trigger(y.FRAG_PARSING_METADATA,p)}if(g&&d){let p={id:t,frag:o,details:g,samples:d.samples};i.trigger(y.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${ve(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,c=ls(n.codec,l);c==="mp4a"&&(c="mp4a.40.5");let d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),l&&l!==c&&this.log(`Swapping manifest audio codec "${l}" for "${c}"`),n.levelCodec=c,n.id=G.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=G.MAIN;let l=a.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let u=Object.keys(t);if(u.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;u.forEach(l=>{let d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:l,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,G.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=P.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(Q.isBuffered(e,i)?t=this.getAppendedFrag(i):Q.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(y.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return U(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(U(t)){let i=this.getLevelDetails(),s=this.currentFrag||(i?Kt(null,i.fragments,t):null);if(s){let n=s.programDateTime;if(n!==null){let a=n+(t-s.start)*1e3;return new Date(a)}}}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}},ta=class extends Be{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let s=this.keyIdToKeyInfo[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.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,i,s,n){return new st({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){let a=t[s];if(e.cc<=a.cc&&(!ve(e)||!ve(a)||e.sn<a.sn)||!i&&s==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let u=cs(o);if(u)return this.emeController.getKeySystemAccess([u])})}if(this.config.requireKeySystemAccessOnStart){let s=vi(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Or(n),u=this.keyIdToKeyInfo[o];if((i=u)!=null&&i.decryptdata.key)return n.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if(this.emeController&&(s=u)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(u.decryptdata)){case"usable":case"usable-in-future":return u.keyLoadPromise.then(c=>{let{keyInfo:d}=c;return n.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Pe(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),u=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,R.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){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){let a=Tf(t.initSegment.data);if(a.length){let o=a[0];o.some(u=>u!==0)?(this.log(`Using keyId found in init segment ${Pe(o)}`),ni.setKeyIdForUri(e.decryptdata.uri,o)):(o=ni.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Pe(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!ve(t))return Promise.resolve(i);let n=this.emeController.loadKey(i);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}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 u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,g,m)=>{let{frag:p,keyInfo:E}=g,v=Or(E.decryptdata);if(!p.decryptdata||E!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(p,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));E.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,E.loader=null,a({frag:p,keyInfo:E})},onError:(h,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),g,ae({url:u.url,data:void 0},h)))},onTimeout:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(u,c,d)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let a=Or(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Or(r){if(r.keyFormat!==ke.FAIRPLAY){let e=r.keyId;if(e)return Pe(e)}return r.uri}function Dl(r){let{type:e}=r;switch(e){case ee.AUDIO_TRACK:return G.AUDIO;case ee.SUBTITLE_TRACK:return G.SUBTITLE;default:return G.MAIN}}function Nr(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var ia=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ee.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:u}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:ee.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:u})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ee.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ee.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[ee.LEVEL];if(i){let s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[ee.LEVEL])}}load(e){var t;let i=this.hls.config,s=this.getInternalLoader(e);if(s){let l=this.hls.logger,c=s.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===ee.MANIFEST?n=i.manifestLoadPolicy.default:n=le({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),U((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===ee.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===ee.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===ee.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){let c=l.partTarget,d=l.targetduration;if(c&&d){let h=Math.max(c*3,d*.8)*1e3;n=le({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},u={onSuccess:(l,c,d,h)=>{let f=this.getInternalLoader(d);this.resetInternalLoader(d.type);let g=l.data;c.parsing.start=performance.now(),Bt.isMediaPlaylist(g)||d.type!==ee.MANIFEST?this.handleTrackOrLevelPlaylist(l,c,d,h||null,f):this.handleMasterPlaylist(l,c,d,h)},onError:(l,c,d,h)=>{this.handleNetworkError(c,d,!1,l,h)},onTimeout:(l,c,d)=>{this.handleNetworkError(c,d,!0,void 0,l)}};s.load(e,o,u)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){let n=this.hls,a=e.data,o=Nr(e,i),u=Bt.parseMasterPlaylist(a,o);if(u.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,u.playlistParsingError,s,t);return}let{contentSteering:l,levels:c,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g}=u;this.variableList=g,c.forEach(v=>{let{unknownCodecs:T}=v;if(T){let{preferManagedMediaSource:_}=this.hls.config,{audioCodec:S,videoCodec:A}=v;for(let x=T.length;x--;){let I=T[x];bi(I,"audio",_)?(v.audioCodec=S=S?`${S},${I}`:I,ri.audio[S.substring(0,4)]=2,T.splice(x,1)):bi(I,"video",_)&&(v.videoCodec=A=A?`${A},${I}`:I,ri.video[A.substring(0,4)]=2,T.splice(x,1))}}});let{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=Bt.parseMasterPlaylistMedia(a,o,u);m.length&&!m.some(T=>!T.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ge({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:p,captions:E,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){let a=this.hls,{id:o,level:u,type:l}=i,c=Nr(e,i),d=U(u)?u:U(o)?o:0,h=Dl(i),f=Bt.parseLevelPlaylist(e.data,c,d,h,0,this.variableList);if(l===ee.MANIFEST){let g={attrs:new ge({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+ru(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(y.ERROR,{type:q.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===ee.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ee.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ee.AUDIO_TRACK||e.type===ee.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let u=R.UNKNOWN,l=!1,c=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:u=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case ee.LEVEL:u=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case ee.AUDIO_TRACK:u=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ee.SUBTITLE_TRACK:u=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}c&&this.resetInternalLoader(e.type);let d={type:q.NETWORK_ERROR,details:u,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){let h=(t==null?void 0:t.url)||e.url;d.response=ae({url:h,data:void 0},s)}this.hls.trigger(y.ERROR,d)}handlePlaylistLoaded(e,t,i,s,n,a){let o=this.hls,{type:u,level:l,levelOrTrack:c,id:d,groupId:h,deliveryDirectives:f}=s,g=Nr(t,s),m=Dl(s),p=typeof s.level=="number"&&m===G.MAIN?l:void 0,E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case ee.MANIFEST:case ee.LEVEL:if(p){if(!c)p=0;else if(c!==o.levels[p]){let v=o.levels.indexOf(c);v>-1&&(p=v)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:p||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:u===ee.MANIFEST});break;case ee.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case ee.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},Oi=class r{static get version(){return Di}static isMSESupported(){return Qu()}static isSupported(){return s0()}static getMediaSource(){return At()}static get Events(){return y}static get MetadataSchema(){return Ke}static get ErrorTypes(){return q}static get ErrorDetails(){return R}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:Xp}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ca,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=lf(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=Qp(r.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Jp(i,t);let{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:u}=i,l=new o(this),c=this.abrController=new s(this),d=new Wr(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,r):null,g=this.bufferController=new n(this,d),m=this.capLevelController=new a(this),p=new u(this),E=new ia(this),v=i.contentSteeringController,T=v?new v(this):null,_=this.levelController=new Zn(this,T),S=new Qn(this),A=new ta(this.config,this.logger),x=this.streamController=new ea(this,d,A),I=this.gapController=new Xn(this,d);m.setStreamController(x),p.setStreamController(x);let L=[E,_,x];f&&L.splice(1,0,f),T&&L.splice(1,0,T),this.networkControllers=L;let b=[c,g,I,m,p,S,d];this.audioTrackController=this.createController(i.audioTrackController,L);let D=i.audioStreamController;D&&L.push(this.audioStreamController=new D(this,d,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,L);let k=i.subtitleStreamController;k&&L.push(this.subtititleStreamController=new k(this,d,A)),this.createController(i.timelineController,b),A.emeController=this.emeController=this.createController(i.emeController,b),this.cmcdController=this.createController(i.cmcdController,b),this.latencyController=this.createController(Jn,b),this.coreComponents=b,L.push(l);let F=l.onErrorOut;typeof F=="function"&&this.on(y.ERROR,F,l),this.on(y.MANIFEST_LOADED,E.onManifestLoaded,E)}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(this.logger.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===y.ERROR;this.trigger(y.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.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){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:q.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(y.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,s=this._url=sa.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[G.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[G.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[G.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=yp()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.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 abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){$f(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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0: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}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=ql(t);return Kl(e,i,navigator.mediaCapabilities)}};Oi.defaultConfig=void 0;var J=Oi;var he={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ne={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},Vs=r=>r===he.VIDEO?"playback":r,qe=class qe extends Error{constructor(e,t=qe.MEDIA_ERR_CUSTOM,i,s){var n;super(e),this.name="MediaError",this.code=t,this.context=s,this.fatal=i!=null?i:t>=qe.MEDIA_ERR_NETWORK&&t<=qe.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=qe.defaultMessages[this.code])!=null?n:"")}};qe.MEDIA_ERR_ABORTED=1,qe.MEDIA_ERR_NETWORK=2,qe.MEDIA_ERR_DECODE=3,qe.MEDIA_ERR_SRC_NOT_SUPPORTED=4,qe.MEDIA_ERR_ENCRYPTED=5,qe.MEDIA_ERR_CUSTOM=100,qe.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 V=qe;var a0=r=>r==null,Ni=(r,e)=>a0(e)?!1:r in e,qs={ANY:"any",MUTED:"muted"},Se={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Ea={MSE:"mse",NATIVE:"native"},oi={HEADER:"header",QUERY:"query",NONE:"none"},ny=Object.values(oi),rt={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},Ws={HLS:rt.M3U8},ay=Object.keys(Ws),oy=[...Object.values(rt),"hls","HLS"],ly={upTo720p:"720p",upTo1080p:"1080p",upTo1440p:"1440p",upTo2160p:"2160p"},uy={noLessThan480p:"480p",noLessThan540p:"540p",noLessThan720p:"720p",noLessThan1080p:"1080p",noLessThan1440p:"1440p",noLessThan2160p:"2160p"},cy={DESCENDING:"desc"},dy={upTo720p:"720p",upTo1080p:"1080p",upTo1440p:"1440p",upTo2160p:"2160p"};var o0="en",Ys={code:o0};var fe=(r,e,t,i,s=r)=>{s.addEventListener(e,t,i),r.addEventListener("teardown",()=>{s.removeEventListener(e,t)},{once:!0})};function Ju(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 js=r=>{let e=r.indexOf("?");if(e<0)return[r];let t=r.slice(0,e),i=r.slice(e);return[t,i]},Fi=r=>{let{type:e}=r;if(e){let t=e.toUpperCase();return Ni(t,Ws)?Ws[t]:e}return l0(r)},Sa=r=>r==="VOD"?Se.ON_DEMAND:Se.LIVE,xa=r=>r==="EVENT"?Number.POSITIVE_INFINITY:r==="VOD"?Number.NaN:0,l0=r=>{let{src:e}=r;if(!e)return"";let t="";try{t=new URL(e).pathname}catch{console.error("invalid url")}let i=t.lastIndexOf(".");if(i<0)return c0(r)?rt.M3U8:"";let n=t.slice(i+1).toUpperCase();return Ni(n,rt)?rt[n]:""},u0="mux.com",c0=({src:r,customDomain:e=u0})=>{let t;try{t=new URL(`${r}`)}catch{return!1}let i=t.protocol==="https:",s=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return i&&s&&a&&o},ba=r=>{let e=(r!=null?r:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(function(s){return"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(i)}catch{return}},Zu=({exp:r},e=Date.now())=>!r||r*1e3<e,ec=({sub:r},e)=>r!==e,tc=({aud:r},e)=>!r,ic=({aud:r},e)=>r!==e,sc="en";function ie(r,e=!0){var s,n;let t=e&&(n=(s=Ys)==null?void 0:s[r])!=null?n:r,i=e?Ys.code:sc;return new _a(t,i)}var _a=class{constructor(e,t=(i=>(i=Ys)!=null?i:sc)()){this.message=e,this.locale=t}format(e){return this.message.replace(/\{(\w+)\}/g,(t,i)=>{var s;return(s=e[i])!=null?s:""})}toString(){return this.message}};var d0=Object.values(qs),rc=r=>typeof r=="boolean"||typeof r=="string"&&d0.includes(r),nc=(r,e,t)=>{let{autoplay:i}=r,s=!1,n=!1,a=rc(i)?i:!!i,o=()=>{s||fe(e,"playing",()=>{s=!0},{once:!0})};if(o(),fe(e,"loadstart",()=>{s=!1,o(),Aa(e,a)},{once:!0}),fe(e,"loadstart",()=>{t||(r.streamType&&r.streamType!==Se.UNKNOWN?n=r.streamType===Se.LIVE:n=!Number.isFinite(e.duration)),Aa(e,a)},{once:!0}),t&&t.once(J.Events.LEVEL_LOADED,(l,c)=>{var d;r.streamType&&r.streamType!==Se.UNKNOWN?n=r.streamType===Se.LIVE:n=(d=c.details.live)!=null?d:!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&&fe(e,"play",()=>{e.preload==="metadata"?t.once(J.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{s||(a=rc(l)?l:!!l,Aa(e,a))}},Aa=(r,e)=>{if(!e)return;let t=r.muted,i=()=>r.muted=t;switch(e){case qs.ANY:r.play().catch(()=>{r.muted=!0,r.play().catch(i)});break;case qs.MUTED:r.muted=!0,r.play().catch(i);break;default:r.play().catch(()=>{});break}};var ac=({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,u=i.config.maxBufferSize,l=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=u),c())},c=()=>{!n&&e&&(n=!0,i.loadSource(e))};return fe(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=u,c()},{once:!0}),l(r),l};function oc(r,e){var o;if(!("videoTracks"in r))return;let t=new WeakMap;e.on(J.Events.MANIFEST_PARSED,function(u,l){a();let c=r.addVideoTrack("main");c.selected=!0;for(let[d,h]of l.levels.entries()){let f=c.addRendition(h.url[0],h.width,h.height,h.videoCodec,h.bitrate);t.set(h,`${d}`),f.id=`${d}`}}),e.on(J.Events.AUDIO_TRACKS_UPDATED,function(u,l){n();for(let c of l.audioTracks){let d=c.default?"main":"alternative",h=r.addAudioTrack(d,c.name,c.lang);h.id=`${c.id}`,c.default&&(h.enabled=!0)}}),r.audioTracks.addEventListener("change",()=>{var c;let u=+((c=[...r.audioTracks].find(d=>d.enabled))==null?void 0:c.id),l=e.audioTracks.map(d=>d.id);u!=e.audioTrack&&l.includes(u)&&(e.audioTrack=u)}),e.on(J.Events.LEVELS_UPDATED,function(u,l){var h;let c=r.videoTracks[(h=r.videoTracks.selectedIndex)!=null?h:0];if(!c)return;let d=l.levels.map(f=>t.get(f));for(let f of r.videoRenditions)f.id&&!d.includes(f.id)&&c.removeRendition(f)});let i=u=>{let l=u.target.selectedIndex;l!=e.nextLevel&&(e.nextLevel=l)};(o=r.videoRenditions)==null||o.addEventListener("change",i);let s=()=>{for(let u of r.videoTracks)r.removeVideoTrack(u)},n=()=>{for(let u of r.audioTracks)r.removeAudioTrack(u)},a=()=>{s(),n()};e.once(J.Events.DESTROYING,a)}var Ia=r=>"time"in r?r.time:r.startTime;function lc(r,e){e.on(J.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,{tracks:n})=>{n.forEach(a=>{var c,d;let o=(c=a.subtitleTrack)!=null?c:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:g})=>h==(o==null?void 0:o.lang)&&f===a.label&&g.toLowerCase()===a.kind),l=((d=a._id)!=null?d:a.default)?"default":`${a.kind}${u}`;La(r,a.kind,a.label,o==null?void 0:o.lang,l,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let s=Array.from(r.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!s)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(s==null?void 0:s.id)!==a){let o=e.subtitleTracks.findIndex(({lang:u,name:l,type:c,default:d})=>s.id==="default"&&d||u==s.language&&l===s.label&&c.toLowerCase()===s.kind);e.subtitleTrack=o}(s==null?void 0:s.id)===a&&s.cues&&Array.from(s.cues).forEach(o=>{s.addCue(o)})};r.textTracks.addEventListener("change",t),e.on(J.Events.CUES_PARSED,(s,{track:n,cues:a})=>{let o=r.textTracks.getTrackById(n);if(!o)return;let u=o.mode==="disabled";u&&(o.mode="hidden"),a.forEach(l=>{var c;(c=o.cues)!=null&&c.getCueById(l.id)||o.addCue(l)}),u&&(o.mode="disabled")}),e.once(J.Events.DESTROYING,()=>{r.textTracks.removeEventListener("change",t),r.querySelectorAll("track[data-removeondestroy]").forEach(n=>{n.remove()})});let i=()=>{Array.from(r.textTracks).forEach(s=>{var n,a;if(!["subtitles","caption"].includes(s.kind)&&(s.label==="thumbnails"||s.kind==="chapters")){if(!((n=s.cues)!=null&&n.length)){let o="track";s.kind&&(o+=`[kind="${s.kind}"]`),s.label&&(o+=`[label="${s.label}"]`);let u=r.querySelector(o),l=(a=u==null?void 0:u.getAttribute("src"))!=null?a:"";u==null||u.removeAttribute("src"),setTimeout(()=>{u==null||u.setAttribute("src",l)},0)}s.mode!=="hidden"&&(s.mode="hidden")}})};e.once(J.Events.MANIFEST_LOADED,i),e.once(J.Events.MEDIA_ATTACHED,i)}function La(r,e,t,i,s,n){let a=document.createElement("track");return a.kind=e,a.label=t,i&&(a.srclang=i),s&&(a.id=s),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),r.append(a),a.track}function h0(r,e){let t=Array.prototype.find.call(r.querySelectorAll("track"),i=>i.track===e);t==null||t.remove()}function li(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 uc(r,e,t,i){let s=li(r,t,i);return s||(s=La(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)=>Ia(a)-Ia(n)).forEach(n=>{var u,l;let a=n.value,o=Ia(n);if("endTime"in n&&n.endTime!=null)s==null||s.addCue(new VTTCue(o,n.endTime,i==="chapters"?a:JSON.stringify(a!=null?a:null)));else{let c=Array.prototype.findIndex.call(s==null?void 0:s.cues,g=>g.startTime>=o),d=(u=s==null?void 0:s.cues)==null?void 0:u[c],h=d?d.startTime:Number.isFinite(r.duration)?r.duration:Number.MAX_SAFE_INTEGER,f=(l=s==null?void 0:s.cues)==null?void 0:l[c-1];f&&(f.endTime=o),s==null||s.addCue(new VTTCue(o,h,i==="chapters"?a:JSON.stringify(a!=null?a:null)))}}),r.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),s}var Ra="cuepoints",cc=Object.freeze({label:Ra});async function dc(r,e,t=cc){return uc(r,e,t.label,"metadata")}var Xs=r=>({time:r.startTime,value:JSON.parse(r.text)});function f0(r,e={label:Ra}){let t=li(r,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,i=>Xs(i)):[]}function hc(r,e={label:Ra}){var n,a;let t=li(r,e.label,"metadata");if(!((n=t==null?void 0:t.activeCues)!=null&&n.length))return;if(t.activeCues.length===1)return Xs(t.activeCues[0]);let{currentTime:i}=r,s=Array.prototype.find.call((a=t.activeCues)!=null?a:[],({startTime:o,endTime:u})=>o<=i&&u>i);return Xs(s||t.activeCues[0])}async function fc(r,e=cc){return new Promise(t=>{fe(r,"loadstart",async()=>{let i=await dc(r,[],e);fe(r,"cuechange",()=>{let s=hc(r);if(s){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}var Da="chapters",gc=Object.freeze({label:Da}),zs=r=>({startTime:r.startTime,endTime:r.endTime,value:r.text});async function mc(r,e,t=gc){return uc(r,e,t.label,"chapters")}function g0(r,e={label:Da}){var i;let t=li(r,e.label,"chapters");return(i=t==null?void 0:t.cues)!=null&&i.length?Array.from(t.cues,s=>zs(s)):[]}function pc(r,e={label:Da}){var n,a;let t=li(r,e.label,"chapters");if(!((n=t==null?void 0:t.activeCues)!=null&&n.length))return;if(t.activeCues.length===1)return zs(t.activeCues[0]);let{currentTime:i}=r,s=Array.prototype.find.call((a=t.activeCues)!=null?a:[],({startTime:o,endTime:u})=>o<=i&&u>i);return zs(s||t.activeCues[0])}async function yc(r,e=gc){return new Promise(t=>{fe(r,"loadstart",async()=>{let i=await mc(r,[],e);fe(r,"cuechange",()=>{let s=pc(r);if(s){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:s});r.dispatchEvent(n)}},{},i),t(i)})})}function m0(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 p0(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 Pa={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},y0=r=>{if(r===he.VIDEO)return Pa.VIDEO;if(r===he.DRM)return Pa.DRM},v0=(r,e)=>{var s,n;let t=Vs(r),i=`${t}Token`;return(s=e.tokens)!=null&&s[t]?(n=e.tokens)==null?void 0:n[t]:Ni(i,e)?e[i]:void 0},Ui=(r,e,t,i,s=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var p,E;if(n){let v=ie("Your device appears to be offline",s),T=void 0,_=V.MEDIA_ERR_NETWORK,S=new V(v,_,!1,T);return S.errorCategory=e,S.muxCode=ne.NETWORK_OFFLINE,S.data=r,S}let o="status"in r?r.status:r.code,u=Date.now(),l=V.MEDIA_ERR_NETWORK;if(o===200)return;let c=Vs(e),d=v0(e,t),h=y0(e),[f]=js((p=t.playbackId)!=null?p:"");if(!o||!f)return;let g=ba(d);if(d&&!g){let v=ie("The {tokenNamePrefix}-token provided is invalid or malformed.",s).format({tokenNamePrefix:c}),T=ie("Compact JWT string: {token}",s).format({token:d}),_=new V(v,l,!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_TOKEN_MALFORMED,_.data=r,_}if(o>=500){let v=new V("",l,i!=null?i:!0);return v.errorCategory=e,v.muxCode=ne.NETWORK_UNKNOWN_ERROR,v}if(o===403)if(g){if(Zu(g,u)){let v={timeStyle:"medium",dateStyle:"medium"},T=ie("The video\u2019s secured {tokenNamePrefix}-token has expired.",s).format({tokenNamePrefix:c}),_=ie("Expired at: {expiredDate}. Current time: {currentDate}.",s).format({expiredDate:new Intl.DateTimeFormat("en",v).format((E=g.exp)!=null?E:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(u)}),S=new V(T,l,!0,_);return S.errorCategory=e,S.muxCode=ne.NETWORK_TOKEN_EXPIRED,S.data=r,S}if(ec(g,f)){let v=ie("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",s).format({tokenNamePrefix:c}),T=ie("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",s).format({tokenNamePrefix:c,playbackId:f,tokenPlaybackId:g.sub}),_=new V(v,l,!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_TOKEN_SUB_MISMATCH,_.data=r,_}if(tc(g,h)){let v=ie("The {tokenNamePrefix}-token is formatted with incorrect information.",s).format({tokenNamePrefix:c}),T=ie("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",s).format({tokenNamePrefix:c,expectedAud:h}),_=new V(v,l,!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_TOKEN_AUD_MISSING,_.data=r,_}if(ic(g,h)){let v=ie("The {tokenNamePrefix}-token is formatted with incorrect information.",s).format({tokenNamePrefix:c}),T=ie("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",s).format({tokenNamePrefix:c,expectedAud:h,aud:g.aud}),_=new V(v,l,!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_TOKEN_AUD_MISMATCH,_.data=r,_}}else{let v=ie("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",s).format({tokenNamePrefix:c,category:e}),T=ie("Specified playback ID: {playbackId}",s).format({playbackId:f}),_=new V(v,l,i!=null?i:!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_TOKEN_MISSING,_.data=r,_}if(o===412){let v=ie("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",s),T=ie("Specified playback ID: {playbackId}",s).format({playbackId:f}),_=new V(v,l,i!=null?i:!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_NOT_READY,_.streamType=t.streamType===Se.LIVE?"live":t.streamType===Se.ON_DEMAND?"on-demand":"unknown",_.data=r,_}if(o===404){let v=ie("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",s),T=ie("Specified playback ID: {playbackId}",s).format({playbackId:f}),_=new V(v,l,i!=null?i:!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_NOT_FOUND,_.data=r,_}if(o===400){let v=ie("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),T=ie("Specified playback ID: {playbackId}",s).format({playbackId:f}),_=new V(v,l,i!=null?i:!0,T);return _.errorCategory=e,_.muxCode=ne.NETWORK_INVALID_URL,_.data=r,_}let m=new V("",l,i!=null?i:!0);return m.errorCategory=e,m.muxCode=ne.NETWORK_UNKNOWN_ERROR,m.data=r,m};var vc=J.DefaultConfig.capLevelController,T0={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function E0(r){let e=r.toLowerCase().trim();return T0[e]}var Lt=class Lt extends vc{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?Lt.maxAutoResolution.set(e,t):Lt.maxAutoResolution.delete(e)}getMaxAutoResolution(){var t;let e=this.hls;return(t=Lt.maxAutoResolution.get(e))!=null?t:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,i)=>this.isLevelAllowed(t)&&i<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),i=this.getMaxAutoResolution();if(!i)return super.getMaxLevel(e);let s=E0(i);if(!s)return super.getMaxLevel(e);let n=t.filter(u=>u.width*u.height<=s),a=n.findIndex(u=>u.width*u.height===s);if(a!==-1){let u=n[a];return t.findIndex(l=>l===u)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(u=>u===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),i=this.getValidLevels(e);if(!i[t])return t;let s=Math.min(i[t].width,i[t].height),n=Lt.minMaxResolution;return s>=n?t:vc.getMaxLevelByMediaSize(i,n*(16/9),n)}};Lt.minMaxResolution=720,Lt.maxAutoResolution=new WeakMap;var ka=Lt,Qs=ka;var Js={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},_0=r=>{if(r.includes("fps"))return Js.FAIRPLAY;if(r.includes("playready"))return Js.PLAYREADY;if(r.includes("widevine"))return Js.WIDEVINE},S0=r=>{let e=r.split(`
56
56
  `).find((t,i,s)=>i&&s[i-1].startsWith("#EXT-X-STREAM-INF"));return fetch(e).then(t=>t.status!==200?Promise.reject(t):t.text())},x0=r=>{let e=r.split(`
57
57
  `).filter(i=>i.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let i of e){let s=A0(i),n=s["DATA-ID"];n&&(t[n]={...s})}return{sessionData:t}},b0=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function A0(r){let e=[...r.matchAll(b0)];return Object.fromEntries(e.map(([,t,i])=>[t,i]))}var I0=r=>{var o,u,l;let e=r.split(`
58
- `),i=(u=((o=e.find(c=>c.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?o:"").split(":")[1])==null?void 0:u.trim(),s=Sa(i),n=xa(i),a;if(s===Se.LIVE){let c=e.find(h=>h.startsWith("#EXT-X-PART-INF"));if(!!c)a=+c.split(":")[1].split("=")[1]*2;else{let h=e.find(m=>m.startsWith("#EXT-X-TARGETDURATION")),f=(l=h==null?void 0:h.split(":"))==null?void 0:l[1];a=+(f!=null?f:6)*3}}return{streamType:s,targetLiveWindow:n,liveEdgeStartOffset:a}},L0=async(r,e)=>{if(e===rt.MP4)return{streamType:Se.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===rt.M3U8){let t=await fetch(r);if(!t.ok)return Promise.reject(t);let i=await t.text(),s=await S0(i);return{...x0(i),...I0(s)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},R0=async(r,e,t=Fi({src:r}))=>{var u,l,c,d;let{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,sessionData:a}=await L0(r,t),o=a==null?void 0:a["com.apple.hls.chapters"];(o!=null&&o.URI||o!=null&&o.VALUE.toLocaleLowerCase().startsWith("http"))&&wa((u=o.URI)!=null?u:o.VALUE,e),((l=ye.get(e))!=null?l:{}).liveEdgeStartOffset=n,((c=ye.get(e))!=null?c:{}).targetLiveWindow=s,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((d=ye.get(e))!=null?d:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wa=async(r,e)=>{var t,i;try{let s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch Mux metadata: ${s.status} ${s.statusText}`);let n=await s.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let u of n[0].metadata)u.key&&u.value&&(a[u.key]=u.value);((i=ye.get(e))!=null?i:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(s){console.error(s)}},D0=r=>{var a;let e=r.type,t=Sa(e),i=xa(e),s,n=!!((a=r.partList)!=null&&a.length);return t===Se.LIVE&&(s=n?r.partTarget*2:r.targetduration*3),{streamType:t,targetLiveWindow:i,liveEdgeStartOffset:s,lowLatency:n}},P0=(r,e,t)=>{var o,u,l,c,d,h,f,g;let{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}=D0(r);if(i===Se.LIVE){a?(t.config.backBufferLength=(o=t.userConfig.backBufferLength)!=null?o:4,t.config.maxFragLookUpTolerance=(u=t.userConfig.maxFragLookUpTolerance)!=null?u:.001,t.config.abrBandWidthUpFactor=(l=t.userConfig.abrBandWidthUpFactor)!=null?l:t.config.abrBandWidthFactor):t.config.backBufferLength=(c=t.userConfig.backBufferLength)!=null?c:8;let m=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var E;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(E=t.liveSyncPosition)!=null?E:e.seekable.end(p)}});((d=ye.get(e))!=null?d:{}).seekable=m}((h=ye.get(e))!=null?h:{}).liveEdgeStartOffset=n,((f=ye.get(e))!=null?f:{}).targetLiveWindow=s,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((g=ye.get(e))!=null?g:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Ec,_c,Lc=(_c=(Ec=globalThis==null?void 0:globalThis.navigator)==null?void 0:Ec.userAgent)!=null?_c:"",Sc,xc,bc,k0=(bc=(xc=(Sc=globalThis==null?void 0:globalThis.navigator)==null?void 0:Sc.userAgentData)==null?void 0:xc.platform)!=null?bc:"",C0=Lc.toLowerCase().includes("android")||["x11","android"].some(r=>k0.toLowerCase().includes(r)),w0=r=>/^((?!chrome|android).)*safari/i.test(Lc)&&!!r.canPlayType("application/vnd.apple.mpegurl"),ye=new WeakMap,Tt="mux.com",Ac,Ic,Rc=(Ic=(Ac=J).isSupported)==null?void 0:Ic.call(Ac),M0=r=>C0||!w0(r),tv=()=>Yi.utils.now(),O0=Yi.utils.generateUUID,iv=({playbackId:r,customDomain:e=Tt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:u,playbackToken:l,tokens:{playback:c=l}={},extraSourceParams:d={}}={})=>{if(!r)return;let[h,f=""]=js(r),g=new URL(`https://stream.${e}/${h}.m3u8${f}`);return c||g.searchParams.has("token")?(g.searchParams.forEach((m,p)=>{p!="token"&&g.searchParams.delete(p)}),c&&g.searchParams.set("token",c)):(t&&g.searchParams.set("max_resolution",t),i&&(g.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&&g.searchParams.set("rendition_order",s),n&&g.searchParams.set("program_start_time",`${n}`),a&&g.searchParams.set("program_end_time",`${a}`),o&&g.searchParams.set("asset_start_time",`${o}`),u&&g.searchParams.set("asset_end_time",`${u}`),Object.entries(d).forEach(([m,p])=>{p!=null&&g.searchParams.set(m,p)})),g.toString()},er=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Dc=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},N0=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Oc(r)&&(i=(t=er(r.playbackId))!=null?t:Dc(r.src))!=null?i:r.src},F0=r=>{var e;return(e=ye.get(r))==null?void 0:e.error},sv=r=>{var e;return(e=ye.get(r))==null?void 0:e.metadata},Tc=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.streamType)!=null?t:Se.UNKNOWN},rv=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Pc=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.seekable)!=null?t:r.seekable},nv=r=>{var i;let e=(i=ye.get(r))==null?void 0:i.liveEdgeStartOffset;if(typeof e!="number")return Number.NaN;let t=Pc(r);return t.length?t.end(t.length-1)-e:Number.NaN},Ma=.034,U0=(r,e,t=Ma)=>Math.abs(r-e)<=t,kc=(r,e,t=Ma)=>r>e||U0(r,e,t),B0=(r,e=Ma)=>r.paused&&kc(r.currentTime,r.duration,e),Cc=(r,e)=>{var l,c,d;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let t=e.currentLevel>=0?(c=(l=e.levels)==null?void 0:l[e.currentLevel])==null?void 0:c.details:(d=e.levels.find(h=>!!h.details))==null?void 0:d.details;if(!t||t.live)return;let{fragments:i}=t;if(!(i!=null&&i.length))return;if(r.currentTime<r.duration-(t.targetduration+.5))return!1;let s=i[i.length-1];if(r.currentTime<=s.start)return!1;let n=s.start+s.duration/2,a=r.buffered.start(r.buffered.length-1),o=r.buffered.end(r.buffered.length-1);return n>a&&n<o},$0=(r,e)=>r.ended||r.loop?r.ended:e&&Cc(r,e)?!0:B0(r),av=(r,e,t)=>{G0(e,t,r);let{metadata:i={}}=r,{view_session_id:s=O0()}=i,n=N0(r);i.view_session_id=s,i.video_id=n,r.metadata=i;let a=c=>{var d;(d=e.mux)==null||d.emit("hb",{view_drm_type:c})};r.drmTypeCb=a,ye.set(e,{retryCount:0});let o=H0(r,e),u=ac(r,e,o);r!=null&&r.muxDataKeepSession&&(e!=null&&e.mux)&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?J:void 0}):j0(r,e,o),X0(r,e,o),fc(e),yc(e);let l=nc(r,e,o);return{engine:o,setAutoplay:l,setPreload:u}},G0=(r,e,t)=>{let i=e==null?void 0:e.engine;r!=null&&r.mux&&!r.mux.deleted&&(t!=null&&t.muxDataKeepSession?i&&r.mux.removeHLSJS():(r.mux.destroy(),delete r.mux)),i&&(i.detachMedia(),i.destroy()),r&&(r.hasAttribute("src")&&(r.removeAttribute("src"),r.load()),r.removeEventListener("error",Fc),r.removeEventListener("error",Ca),r.removeEventListener("durationchange",Nc),ye.delete(r),r.dispatchEvent(new Event("teardown")))};function wc(r,e){var l;let t=Fi(r);if(!(t===rt.M3U8))return!0;let s=!t||((l=e.canPlayType(t))!=null?l:!0),{preferPlayback:n}=r,a=n===Ea.MSE,o=n===Ea.NATIVE,u=Rc&&(a||M0(e));return s&&(o||!u)}var H0=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:u}=r,c=Fi(r)===rt.M3U8,d=wc(r,e);if(c&&!d&&Rc){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},f=K0(i),g=V0(r),m=[oi.QUERY,oi.HEADER].includes(a)?{useHeaders:a===oi.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,p=o.capLevelToPlayerSize==null?{capLevelController:Qs}:{},E=new J({debug:t,startPosition:s,cmcd:m,xhrSetup:(v,T)=>{var A,x;if(a&&a!==oi.QUERY)return;let _=new URL(T);if(!_.searchParams.has("CMCD"))return;let S=((x=(A=_.searchParams.get("CMCD"))==null?void 0:A.split(","))!=null?x:[]).filter(I=>I.startsWith("sid")||I.startsWith("cid")).join(",");_.searchParams.set("CMCD",S),v.open("GET",_)},...p,...h,...f,...g,...o});return p.capLevelController===Qs&&u!==void 0&&Qs.setMaxAutoResolution(E,u),E.on(J.Events.MANIFEST_PARSED,async function(v,T){var S,A;let _=(S=T.sessionData)==null?void 0:S["com.apple.hls.chapters"];(_!=null&&_.URI||_!=null&&_.VALUE.toLocaleLowerCase().startsWith("http"))&&wa((A=_==null?void 0:_.URI)!=null?A:_==null?void 0:_.VALUE,e)}),E}},K0=r=>r===Se.LIVE?{backBufferLength:8}:{},V0=r=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:i}=r,s=er(t);return!e||!s?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Zs(r,"fairplay"),serverCertificateUrl:Mc(r,"fairplay")},"com.widevine.alpha":{licenseUrl:Zs(r,"widevine")},"com.microsoft.playready":{licenseUrl:Zs(r,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let u=(l=o.videoCapabilities)==null?void 0:l.map(c=>({...c,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:u}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let u=_0(n);return i==null||i(u),o}))}},q0=async r=>{let e=await fetch(r);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},W0=async(r,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r});if(t.status!==200)return Promise.reject(t);let i=await t.arrayBuffer();return new Uint8Array(i)},Y0=(r,e)=>{let t=async a=>{let o=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[a],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(l=>{var c;return(c=r.drmTypeCb)==null||c.call(r,Js.FAIRPLAY),l}).catch(()=>{let l=ie("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),c=new V(l,V.MEDIA_ERR_ENCRYPTED,!0);c.errorCategory=he.DRM,c.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,We(e,c)});if(!o)return;let u=await o.createMediaKeys();try{let l=await q0(Mc(r,"fairplay")).catch(c=>{if(c instanceof Response){let d=Ui(c,he.DRM,r);return console.error("mediaError",d==null?void 0:d.message,d==null?void 0:d.context),d?Promise.reject(d):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(c)});await u.setServerCertificate(l).catch(()=>{let c=ie("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),d=new V(c,V.MEDIA_ERR_ENCRYPTED,!0);return d.errorCategory=he.DRM,d.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(d)})}catch(l){We(e,l);return}await e.setMediaKeys(u)},i=a=>{let o;if(a==="internal-error"){let u=ie("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");o=new V(u,V.MEDIA_ERR_ENCRYPTED,!0),o.errorCategory=he.DRM,o.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(a==="output-restricted"||a==="output-downscaled"){let u=ie("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");o=new V(u,V.MEDIA_ERR_ENCRYPTED,!1),o.errorCategory=he.DRM,o.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}o&&We(e,o)},s=async(a,o)=>{let u=e.mediaKeys.createSession(),l=()=>{u.keyStatuses.forEach(d=>i(d))},c=async d=>{let h=d.message;try{let f=await W0(h,Zs(r,"fairplay"));try{await u.update(f)}catch{let g=ie("Failed to update DRM license. This may be an issue with the player or your protected content."),m=new V(g,V.MEDIA_ERR_ENCRYPTED,!0);m.errorCategory=he.DRM,m.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,We(e,m)}}catch(f){if(f instanceof Response){let g=Ui(f,he.DRM,r);if(console.error("mediaError",g==null?void 0:g.message,g==null?void 0:g.context),g){We(e,g);return}console.error("Unexpected error in license key request",f);return}console.error(f)}};u.addEventListener("keystatuseschange",l),u.addEventListener("message",c),e.addEventListener("teardown",()=>{u.removeEventListener("keystatuseschange",l),u.removeEventListener("message",c),u.close()},{once:!0}),await u.generateRequest(a,o).catch(d=>{console.error("Failed to generate license request",d);let h=ie("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),f=new V(h,V.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=he.DRM,f.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,Promise.reject(f)})};fe(e,"encrypted",async a=>{try{let o=a.initDataType;if(o!=="skd"){console.error(`Received unexpected initialization data type "${o}"`);return}e.mediaKeys||await t(o);let u=a.initData;if(u==null){console.error(`Could not start encrypted playback due to missing initData in ${a.type} event`);return}await s(o,u)}catch(o){We(e,o);return}})},Zs=({playbackId:r,tokens:{drm:e}={},customDomain:t=Tt},i)=>{let s=er(r);return`https://license.${t.toLocaleLowerCase().endsWith(Tt)?t:Tt}/license/${i}/${s}?token=${e}`},Mc=({playbackId:r,tokens:{drm:e}={},customDomain:t=Tt},i)=>{let s=er(r);return`https://license.${t.toLocaleLowerCase().endsWith(Tt)?t:Tt}/appcert/${i}/${s}?token=${e}`},Oc=({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(Tt)||!!t&&s.includes(t.toLocaleLowerCase())},j0=(r,e,t)=>{var u;let{envKey:i,disableTracking:s,muxDataSDK:n=Yi,muxDataSDKOptions:a={}}=r,o=Oc(r);if(!s&&(i||o)){let{playerInitTime:l,playerSoftwareName:c,playerSoftwareVersion:d,beaconCollectionDomain:h,debug:f,disableCookies:g}=r,m={...r.metadata,video_title:((u=r==null?void 0:r.metadata)==null?void 0:u.video_title)||void 0},p=E=>typeof E.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(E):E;n.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?J:void 0,automaticErrorTracking:!1,errorTranslator:p,disableCookies:g,...a,data:{...i?{env_key:i}:{},player_software_name:c,player_software:c,player_software_version:d,player_init_time:l,...m}})}},X0=(r,e,t)=>{var c,d;let i=wc(r,e),{src:s,customDomain:n=Tt}=r,a=()=>{e.ended||r.disablePseudoEnded||!$0(e,t)||(Cc(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,u,l=()=>{let h=Pc(e),f,g;h.length>0&&(f=h.start(0),g=h.end(0)),(u!==g||o!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=f,u=g};if(fe(e,"durationchange",l),e&&i){let h=Fi(r);if(typeof s=="string"){if(s.endsWith(".mp4")&&s.includes(n)){let m=Dc(s),p=new URL(`https://stream.${n}/${m}/metadata.json`);wa(p.toString(),e)}let f=()=>{if(Tc(e)!==Se.LIVE||Number.isFinite(e.duration))return;let m=setInterval(l,1e3);e.addEventListener("teardown",()=>{clearInterval(m)},{once:!0}),fe(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(m)})},g=async()=>R0(s,e,h).then(f).catch(m=>{if(m instanceof Response){let p=Ui(m,he.VIDEO,r);if(p){We(e,p);return}}else m instanceof Error});if(e.preload==="none"){let m=()=>{g(),e.removeEventListener("loadedmetadata",p)},p=()=>{g(),e.removeEventListener("play",m)};fe(e,"play",m,{once:!0}),fe(e,"loadedmetadata",p,{once:!0})}else g();(c=r.tokens)!=null&&c.drm?Y0(r,e):fe(e,"encrypted",()=>{let m=ie("Attempting to play DRM-protected content without providing a DRM token."),p=new V(m,V.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=he.DRM,p.muxCode=ne.ENCRYPTED_MISSING_TOKEN,We(e,p)},{once:!0}),e.setAttribute("src",s),r.startTime&&(((d=ye.get(e))!=null?d:{}).startTime=r.startTime,e.addEventListener("durationchange",Nc,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Fc),e.addEventListener("error",Ca),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(g=>{g.remove()})},{once:!0}),fe(e,"pause",a),fe(e,"seeked",a),fe(e,"play",()=>{e.ended||kc(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&s?(t.once(J.Events.LEVEL_LOADED,(h,f)=>{P0(f.details,e,t),l(),Tc(e)===Se.LIVE&&!Number.isFinite(e.duration)&&(t.on(J.Events.LEVEL_UPDATED,l),fe(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(J.Events.LEVELS_UPDATED,l)}))}),t.on(J.Events.ERROR,(h,f)=>{var m,p;let g=z0(f,r);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=ye.get(e))!=null?m:{},T=(p=v.retryCount)!=null?p:0;if(T<6){let _=T===0?5e3:6e4,S=new V(`Retrying in ${_/1e3} seconds...`,g.code,g.fatal);Object.assign(S,g),We(e,S),setTimeout(()=>{v.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},_);return}else{v.retryCount=0;let _=new V('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(_,g),We(e,_);return}}We(e,g)}),t.on(J.Events.MANIFEST_LOADED,()=>{let h=ye.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ca),fe(e,"waiting",a),oc(r,t),lc(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 Nc(r){var i;let e=r.target,t=(i=ye.get(e))==null?void 0:i.startTime;if(t&&Ju(e.seekable,e.duration,t)){let s=e.preload==="auto";s&&(e.preload="none"),e.currentTime=t,s&&(e.preload="auto")}}async function Fc(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 V(t,i);if(e.src&&i===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var a;let n=(a=F0(e))!=null?a:e.error;(n==null?void 0:n.code)===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&We(e,s)},500);return}if(e.src&&(i!==V.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}We(e,s)}function We(r,e){var t;e.fatal&&(((t=ye.get(r))!=null?t:{}).error=e,r.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ca(r){var i,s;if(!(r instanceof CustomEvent)||!(r.detail instanceof V))return;let e=r.target,t=r.detail;!t||!t.fatal||(((i=ye.get(e))!=null?i:{}).error=t,(s=e.mux)==null||s.emit("error",{player_error_code:t.code,player_error_message:t.message,player_error_context:t.context}))}var z0=(r,e)=>{var u,l,c;!r.fatal?e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",r):console.error("getErrorFromHlsErrorData()",r);let i={[J.ErrorTypes.NETWORK_ERROR]:V.MEDIA_ERR_NETWORK,[J.ErrorTypes.MEDIA_ERROR]:V.MEDIA_ERR_DECODE,[J.ErrorTypes.KEY_SYSTEM_ERROR]:V.MEDIA_ERR_ENCRYPTED},s=d=>[J.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,J.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(d.details)?V.MEDIA_ERR_NETWORK:i[d.type],n=d=>{if(d.type===J.ErrorTypes.KEY_SYSTEM_ERROR)return he.DRM;if(d.type===J.ErrorTypes.NETWORK_ERROR)return he.VIDEO},a,o=s(r);if(o===V.MEDIA_ERR_NETWORK&&r.response){let d=(u=n(r))!=null?u:he.VIDEO;a=(l=Ui(r.response,d,e,r.fatal))!=null?l:new V("",o,r.fatal)}else if(o===V.MEDIA_ERR_ENCRYPTED)if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let d=ie("Attempting to play DRM-protected content without providing a DRM token.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let d=ie("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_SESSION){let d=ie("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,!0),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let d=ie("Failed to update DRM license. This may be an issue with the player or your protected content.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let d=ie("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let d=ie("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(r.details===J.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let d=ie("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,!1),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else a=new V(r.error.message,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_ERROR;else a=new V("",o,r.fatal);return a.context||(a.context=`${r.url?`url: ${r.url}
58
+ `),i=(u=((o=e.find(c=>c.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?o:"").split(":")[1])==null?void 0:u.trim(),s=Sa(i),n=xa(i),a;if(s===Se.LIVE){let c=e.find(h=>h.startsWith("#EXT-X-PART-INF"));if(!!c)a=+c.split(":")[1].split("=")[1]*2;else{let h=e.find(m=>m.startsWith("#EXT-X-TARGETDURATION")),f=(l=h==null?void 0:h.split(":"))==null?void 0:l[1];a=+(f!=null?f:6)*3}}return{streamType:s,targetLiveWindow:n,liveEdgeStartOffset:a}},L0=async(r,e)=>{if(e===rt.MP4)return{streamType:Se.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===rt.M3U8){let t=await fetch(r);if(!t.ok)return Promise.reject(t);let i=await t.text(),s=await S0(i);return{...x0(i),...I0(s)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${r}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},R0=async(r,e,t=Fi({src:r}))=>{var u,l,c,d;let{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,sessionData:a}=await L0(r,t),o=a==null?void 0:a["com.apple.hls.chapters"];(o!=null&&o.URI||o!=null&&o.VALUE.toLocaleLowerCase().startsWith("http"))&&wa((u=o.URI)!=null?u:o.VALUE,e),((l=ye.get(e))!=null?l:{}).liveEdgeStartOffset=n,((c=ye.get(e))!=null?c:{}).targetLiveWindow=s,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((d=ye.get(e))!=null?d:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wa=async(r,e)=>{var t,i;try{let s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch Mux metadata: ${s.status} ${s.statusText}`);let n=await s.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let u of n[0].metadata)u.key&&u.value&&(a[u.key]=u.value);((i=ye.get(e))!=null?i:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(s){console.error(s)}},D0=r=>{var a;let e=r.type,t=Sa(e),i=xa(e),s,n=!!((a=r.partList)!=null&&a.length);return t===Se.LIVE&&(s=n?r.partTarget*2:r.targetduration*3),{streamType:t,targetLiveWindow:i,liveEdgeStartOffset:s,lowLatency:n}},P0=(r,e,t)=>{var o,u,l,c,d,h,f,g;let{streamType:i,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}=D0(r);if(i===Se.LIVE){a?(t.config.backBufferLength=(o=t.userConfig.backBufferLength)!=null?o:4,t.config.maxFragLookUpTolerance=(u=t.userConfig.maxFragLookUpTolerance)!=null?u:.001,t.config.abrBandWidthUpFactor=(l=t.userConfig.abrBandWidthUpFactor)!=null?l:t.config.abrBandWidthFactor):t.config.backBufferLength=(c=t.userConfig.backBufferLength)!=null?c:8;let m=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var E;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(E=t.liveSyncPosition)!=null?E:e.seekable.end(p)}});((d=ye.get(e))!=null?d:{}).seekable=m}((h=ye.get(e))!=null?h:{}).liveEdgeStartOffset=n,((f=ye.get(e))!=null?f:{}).targetLiveWindow=s,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((g=ye.get(e))!=null?g:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Ec,_c,Lc=(_c=(Ec=globalThis==null?void 0:globalThis.navigator)==null?void 0:Ec.userAgent)!=null?_c:"",Sc,xc,bc,k0=(bc=(xc=(Sc=globalThis==null?void 0:globalThis.navigator)==null?void 0:Sc.userAgentData)==null?void 0:xc.platform)!=null?bc:"",C0=Lc.toLowerCase().includes("android")||["x11","android"].some(r=>k0.toLowerCase().includes(r)),w0=r=>/^((?!chrome|android).)*safari/i.test(Lc)&&!!r.canPlayType("application/vnd.apple.mpegurl"),ye=new WeakMap,Tt="mux.com",Ac,Ic,Rc=(Ic=(Ac=J).isSupported)==null?void 0:Ic.call(Ac),M0=r=>C0||!w0(r),tv=()=>{if(typeof window!="undefined")return Yi.utils.now()},O0=Yi.utils.generateUUID,iv=({playbackId:r,customDomain:e=Tt,maxResolution:t,minResolution:i,renditionOrder:s,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:u,playbackToken:l,tokens:{playback:c=l}={},extraSourceParams:d={}}={})=>{if(!r)return;let[h,f=""]=js(r),g=new URL(`https://stream.${e}/${h}.m3u8${f}`);return c||g.searchParams.has("token")?(g.searchParams.forEach((m,p)=>{p!="token"&&g.searchParams.delete(p)}),c&&g.searchParams.set("token",c)):(t&&g.searchParams.set("max_resolution",t),i&&(g.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&&g.searchParams.set("rendition_order",s),n&&g.searchParams.set("program_start_time",`${n}`),a&&g.searchParams.set("program_end_time",`${a}`),o&&g.searchParams.set("asset_start_time",`${o}`),u&&g.searchParams.set("asset_end_time",`${u}`),Object.entries(d).forEach(([m,p])=>{p!=null&&g.searchParams.set(m,p)})),g.toString()},er=r=>{if(!r)return;let[e]=r.split("?");return e||void 0},Dc=r=>{if(!r||!r.startsWith("https://stream."))return;let[e]=new URL(r).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},N0=r=>{var e,t,i;return(e=r==null?void 0:r.metadata)!=null&&e.video_id?r.metadata.video_id:Oc(r)&&(i=(t=er(r.playbackId))!=null?t:Dc(r.src))!=null?i:r.src},F0=r=>{var e;return(e=ye.get(r))==null?void 0:e.error},sv=r=>{var e;return(e=ye.get(r))==null?void 0:e.metadata},Tc=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.streamType)!=null?t:Se.UNKNOWN},rv=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Pc=r=>{var e,t;return(t=(e=ye.get(r))==null?void 0:e.seekable)!=null?t:r.seekable},nv=r=>{var i;let e=(i=ye.get(r))==null?void 0:i.liveEdgeStartOffset;if(typeof e!="number")return Number.NaN;let t=Pc(r);return t.length?t.end(t.length-1)-e:Number.NaN},Ma=.034,U0=(r,e,t=Ma)=>Math.abs(r-e)<=t,kc=(r,e,t=Ma)=>r>e||U0(r,e,t),B0=(r,e=Ma)=>r.paused&&kc(r.currentTime,r.duration,e),Cc=(r,e)=>{var l,c,d;if(!e||!r.buffered.length)return;if(r.readyState>2)return!1;let t=e.currentLevel>=0?(c=(l=e.levels)==null?void 0:l[e.currentLevel])==null?void 0:c.details:(d=e.levels.find(h=>!!h.details))==null?void 0:d.details;if(!t||t.live)return;let{fragments:i}=t;if(!(i!=null&&i.length))return;if(r.currentTime<r.duration-(t.targetduration+.5))return!1;let s=i[i.length-1];if(r.currentTime<=s.start)return!1;let n=s.start+s.duration/2,a=r.buffered.start(r.buffered.length-1),o=r.buffered.end(r.buffered.length-1);return n>a&&n<o},$0=(r,e)=>r.ended||r.loop?r.ended:e&&Cc(r,e)?!0:B0(r),av=(r,e,t)=>{G0(e,t,r);let{metadata:i={}}=r,{view_session_id:s=O0()}=i,n=N0(r);i.view_session_id=s,i.video_id=n,r.metadata=i;let a=c=>{var d;(d=e.mux)==null||d.emit("hb",{view_drm_type:c})};r.drmTypeCb=a,ye.set(e,{retryCount:0});let o=H0(r,e),u=ac(r,e,o);r!=null&&r.muxDataKeepSession&&(e!=null&&e.mux)&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?J:void 0}):j0(r,e,o),X0(r,e,o),fc(e),yc(e);let l=nc(r,e,o);return{engine:o,setAutoplay:l,setPreload:u}},G0=(r,e,t)=>{let i=e==null?void 0:e.engine;r!=null&&r.mux&&!r.mux.deleted&&(t!=null&&t.muxDataKeepSession?i&&r.mux.removeHLSJS():(r.mux.destroy(),delete r.mux)),i&&(i.detachMedia(),i.destroy()),r&&(r.hasAttribute("src")&&(r.removeAttribute("src"),r.load()),r.removeEventListener("error",Fc),r.removeEventListener("error",Ca),r.removeEventListener("durationchange",Nc),ye.delete(r),r.dispatchEvent(new Event("teardown")))};function wc(r,e){var l;let t=Fi(r);if(!(t===rt.M3U8))return!0;let s=!t||((l=e.canPlayType(t))!=null?l:!0),{preferPlayback:n}=r,a=n===Ea.MSE,o=n===Ea.NATIVE,u=Rc&&(a||M0(e));return s&&(o||!u)}var H0=(r,e)=>{let{debug:t,streamType:i,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:u}=r,c=Fi(r)===rt.M3U8,d=wc(r,e);if(c&&!d&&Rc){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},f=K0(i),g=V0(r),m=[oi.QUERY,oi.HEADER].includes(a)?{useHeaders:a===oi.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,p=o.capLevelToPlayerSize==null?{capLevelController:Qs}:{},E=new J({debug:t,startPosition:s,cmcd:m,xhrSetup:(v,T)=>{var A,x;if(a&&a!==oi.QUERY)return;let _=new URL(T);if(!_.searchParams.has("CMCD"))return;let S=((x=(A=_.searchParams.get("CMCD"))==null?void 0:A.split(","))!=null?x:[]).filter(I=>I.startsWith("sid")||I.startsWith("cid")).join(",");_.searchParams.set("CMCD",S),v.open("GET",_)},...p,...h,...f,...g,...o});return p.capLevelController===Qs&&u!==void 0&&Qs.setMaxAutoResolution(E,u),E.on(J.Events.MANIFEST_PARSED,async function(v,T){var S,A;let _=(S=T.sessionData)==null?void 0:S["com.apple.hls.chapters"];(_!=null&&_.URI||_!=null&&_.VALUE.toLocaleLowerCase().startsWith("http"))&&wa((A=_==null?void 0:_.URI)!=null?A:_==null?void 0:_.VALUE,e)}),E}},K0=r=>r===Se.LIVE?{backBufferLength:8}:{},V0=r=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:i}=r,s=er(t);return!e||!s?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Zs(r,"fairplay"),serverCertificateUrl:Mc(r,"fairplay")},"com.widevine.alpha":{licenseUrl:Zs(r,"widevine")},"com.microsoft.playready":{licenseUrl:Zs(r,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let u=(l=o.videoCapabilities)==null?void 0:l.map(c=>({...c,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:u}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let u=_0(n);return i==null||i(u),o}))}},q0=async r=>{let e=await fetch(r);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},W0=async(r,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:r});if(t.status!==200)return Promise.reject(t);let i=await t.arrayBuffer();return new Uint8Array(i)},Y0=(r,e)=>{let t=async a=>{let o=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[a],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(l=>{var c;return(c=r.drmTypeCb)==null||c.call(r,Js.FAIRPLAY),l}).catch(()=>{let l=ie("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),c=new V(l,V.MEDIA_ERR_ENCRYPTED,!0);c.errorCategory=he.DRM,c.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,We(e,c)});if(!o)return;let u=await o.createMediaKeys();try{let l=await q0(Mc(r,"fairplay")).catch(c=>{if(c instanceof Response){let d=Ui(c,he.DRM,r);return console.error("mediaError",d==null?void 0:d.message,d==null?void 0:d.context),d?Promise.reject(d):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(c)});await u.setServerCertificate(l).catch(()=>{let c=ie("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),d=new V(c,V.MEDIA_ERR_ENCRYPTED,!0);return d.errorCategory=he.DRM,d.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(d)})}catch(l){We(e,l);return}await e.setMediaKeys(u)},i=a=>{let o;if(a==="internal-error"){let u=ie("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");o=new V(u,V.MEDIA_ERR_ENCRYPTED,!0),o.errorCategory=he.DRM,o.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(a==="output-restricted"||a==="output-downscaled"){let u=ie("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");o=new V(u,V.MEDIA_ERR_ENCRYPTED,!1),o.errorCategory=he.DRM,o.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}o&&We(e,o)},s=async(a,o)=>{let u=e.mediaKeys.createSession(),l=()=>{u.keyStatuses.forEach(d=>i(d))},c=async d=>{let h=d.message;try{let f=await W0(h,Zs(r,"fairplay"));try{await u.update(f)}catch{let g=ie("Failed to update DRM license. This may be an issue with the player or your protected content."),m=new V(g,V.MEDIA_ERR_ENCRYPTED,!0);m.errorCategory=he.DRM,m.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,We(e,m)}}catch(f){if(f instanceof Response){let g=Ui(f,he.DRM,r);if(console.error("mediaError",g==null?void 0:g.message,g==null?void 0:g.context),g){We(e,g);return}console.error("Unexpected error in license key request",f);return}console.error(f)}};u.addEventListener("keystatuseschange",l),u.addEventListener("message",c),e.addEventListener("teardown",()=>{u.removeEventListener("keystatuseschange",l),u.removeEventListener("message",c),u.close()},{once:!0}),await u.generateRequest(a,o).catch(d=>{console.error("Failed to generate license request",d);let h=ie("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),f=new V(h,V.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=he.DRM,f.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,Promise.reject(f)})};fe(e,"encrypted",async a=>{try{let o=a.initDataType;if(o!=="skd"){console.error(`Received unexpected initialization data type "${o}"`);return}e.mediaKeys||await t(o);let u=a.initData;if(u==null){console.error(`Could not start encrypted playback due to missing initData in ${a.type} event`);return}await s(o,u)}catch(o){We(e,o);return}})},Zs=({playbackId:r,tokens:{drm:e}={},customDomain:t=Tt},i)=>{let s=er(r);return`https://license.${t.toLocaleLowerCase().endsWith(Tt)?t:Tt}/license/${i}/${s}?token=${e}`},Mc=({playbackId:r,tokens:{drm:e}={},customDomain:t=Tt},i)=>{let s=er(r);return`https://license.${t.toLocaleLowerCase().endsWith(Tt)?t:Tt}/appcert/${i}/${s}?token=${e}`},Oc=({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(Tt)||!!t&&s.includes(t.toLocaleLowerCase())},j0=(r,e,t)=>{var u;let{envKey:i,disableTracking:s,muxDataSDK:n=Yi,muxDataSDKOptions:a={}}=r,o=Oc(r);if(!s&&(i||o)){let{playerInitTime:l,playerSoftwareName:c,playerSoftwareVersion:d,beaconCollectionDomain:h,debug:f,disableCookies:g}=r,m={...r.metadata,video_title:((u=r==null?void 0:r.metadata)==null?void 0:u.video_title)||void 0},p=E=>typeof E.player_error_code=="string"?!1:typeof r.errorTranslator=="function"?r.errorTranslator(E):E;n.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?J:void 0,automaticErrorTracking:!1,errorTranslator:p,disableCookies:g,...a,data:{...i?{env_key:i}:{},player_software_name:c,player_software:c,player_software_version:d,player_init_time:l,...m}})}},X0=(r,e,t)=>{var c,d;let i=wc(r,e),{src:s,customDomain:n=Tt}=r,a=()=>{e.ended||r.disablePseudoEnded||!$0(e,t)||(Cc(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},o,u,l=()=>{let h=Pc(e),f,g;h.length>0&&(f=h.start(0),g=h.end(0)),(u!==g||o!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),o=f,u=g};if(fe(e,"durationchange",l),e&&i){let h=Fi(r);if(typeof s=="string"){if(s.endsWith(".mp4")&&s.includes(n)){let m=Dc(s),p=new URL(`https://stream.${n}/${m}/metadata.json`);wa(p.toString(),e)}let f=()=>{if(Tc(e)!==Se.LIVE||Number.isFinite(e.duration))return;let m=setInterval(l,1e3);e.addEventListener("teardown",()=>{clearInterval(m)},{once:!0}),fe(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(m)})},g=async()=>R0(s,e,h).then(f).catch(m=>{if(m instanceof Response){let p=Ui(m,he.VIDEO,r);if(p){We(e,p);return}}else m instanceof Error});if(e.preload==="none"){let m=()=>{g(),e.removeEventListener("loadedmetadata",p)},p=()=>{g(),e.removeEventListener("play",m)};fe(e,"play",m,{once:!0}),fe(e,"loadedmetadata",p,{once:!0})}else g();(c=r.tokens)!=null&&c.drm?Y0(r,e):fe(e,"encrypted",()=>{let m=ie("Attempting to play DRM-protected content without providing a DRM token."),p=new V(m,V.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=he.DRM,p.muxCode=ne.ENCRYPTED_MISSING_TOKEN,We(e,p)},{once:!0}),e.setAttribute("src",s),r.startTime&&(((d=ye.get(e))!=null?d:{}).startTime=r.startTime,e.addEventListener("durationchange",Nc,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Fc),e.addEventListener("error",Ca),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(g=>{g.remove()})},{once:!0}),fe(e,"pause",a),fe(e,"seeked",a),fe(e,"play",()=>{e.ended||kc(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&s?(t.once(J.Events.LEVEL_LOADED,(h,f)=>{P0(f.details,e,t),l(),Tc(e)===Se.LIVE&&!Number.isFinite(e.duration)&&(t.on(J.Events.LEVEL_UPDATED,l),fe(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(J.Events.LEVELS_UPDATED,l)}))}),t.on(J.Events.ERROR,(h,f)=>{var m,p;let g=z0(f,r);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=ye.get(e))!=null?m:{},T=(p=v.retryCount)!=null?p:0;if(T<6){let _=T===0?5e3:6e4,S=new V(`Retrying in ${_/1e3} seconds...`,g.code,g.fatal);Object.assign(S,g),We(e,S),setTimeout(()=>{v.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},_);return}else{v.retryCount=0;let _=new V('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(_,g),We(e,_);return}}We(e,g)}),t.on(J.Events.MANIFEST_LOADED,()=>{let h=ye.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ca),fe(e,"waiting",a),oc(r,t),lc(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 Nc(r){var i;let e=r.target,t=(i=ye.get(e))==null?void 0:i.startTime;if(t&&Ju(e.seekable,e.duration,t)){let s=e.preload==="auto";s&&(e.preload="none"),e.currentTime=t,s&&(e.preload="auto")}}async function Fc(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 V(t,i);if(e.src&&i===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var a;let n=(a=F0(e))!=null?a:e.error;(n==null?void 0:n.code)===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&We(e,s)},500);return}if(e.src&&(i!==V.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}We(e,s)}function We(r,e){var t;e.fatal&&(((t=ye.get(r))!=null?t:{}).error=e,r.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ca(r){var i,s;if(!(r instanceof CustomEvent)||!(r.detail instanceof V))return;let e=r.target,t=r.detail;!t||!t.fatal||(((i=ye.get(e))!=null?i:{}).error=t,(s=e.mux)==null||s.emit("error",{player_error_code:t.code,player_error_message:t.message,player_error_context:t.context}))}var z0=(r,e)=>{var u,l,c;!r.fatal?e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",r):console.error("getErrorFromHlsErrorData()",r);let i={[J.ErrorTypes.NETWORK_ERROR]:V.MEDIA_ERR_NETWORK,[J.ErrorTypes.MEDIA_ERROR]:V.MEDIA_ERR_DECODE,[J.ErrorTypes.KEY_SYSTEM_ERROR]:V.MEDIA_ERR_ENCRYPTED},s=d=>[J.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,J.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(d.details)?V.MEDIA_ERR_NETWORK:i[d.type],n=d=>{if(d.type===J.ErrorTypes.KEY_SYSTEM_ERROR)return he.DRM;if(d.type===J.ErrorTypes.NETWORK_ERROR)return he.VIDEO},a,o=s(r);if(o===V.MEDIA_ERR_NETWORK&&r.response){let d=(u=n(r))!=null?u:he.VIDEO;a=(l=Ui(r.response,d,e,r.fatal))!=null?l:new V("",o,r.fatal)}else if(o===V.MEDIA_ERR_ENCRYPTED)if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let d=ie("Attempting to play DRM-protected content without providing a DRM token.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let d=ie("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(r.details===J.ErrorDetails.KEY_SYSTEM_NO_SESSION){let d=ie("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,!0),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let d=ie("Failed to update DRM license. This may be an issue with the player or your protected content.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let d=ie("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(r.details===J.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let d=ie("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(r.details===J.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let d=ie("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");a=new V(d,V.MEDIA_ERR_ENCRYPTED,!1),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else a=new V(r.error.message,V.MEDIA_ERR_ENCRYPTED,r.fatal),a.errorCategory=he.DRM,a.muxCode=ne.ENCRYPTED_ERROR;else a=new V("",o,r.fatal);return a.context||(a.context=`${r.url?`url: ${r.url}
59
59
  `:""}${r.response&&(r.response.code||r.response.text)?`response: ${r.response.code}, ${r.response.text}
60
60
  `:""}${r.reason?`failure reason: ${r.reason}
61
61
  `:""}${r.level?`level: ${r.level}