@mux/mux-player 3.6.2-canary.0 → 3.6.2-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base.cjs.js +4 -1
- package/dist/base.mjs +12 -9
- package/dist/mux-player.js +5 -2
- package/dist/mux-player.mjs +5 -2
- package/dist/themes/classic/index.cjs.js +3 -2
- package/dist/themes/classic/index.js +3 -2
- package/dist/themes/classic/index.mjs +3 -2
- package/dist/themes/gerwig/index.cjs.js +4 -1
- package/dist/themes/gerwig/index.js +4 -1
- package/dist/themes/gerwig/index.mjs +4 -1
- package/package.json +1 -1
package/dist/mux-player.js
CHANGED
|
@@ -55,7 +55,7 @@ Schedule: ${l.map(m=>Nr(m))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
55
55
|
`:(n=r.childNodes)!=null&&n.length?Ny(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}function ek(i,e,t){let r="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{let d=bf(e,r,l)||bf(i,r,l)||bf(s,r,l);return d&&(o[l]=d),o},{})}function bf(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function bE(i){return new Error(`Could not parse ttml timestamp ${i}`)}function _f(i,e){if(!i)return null;let t=Cy(i);return t===null&&(Py.test(i)?t=tk(i,e):Oy.test(i)&&(t=ik(i,e))),t}function tk(i,e){let t=Py.exec(i),r=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+r/e.frameRate}function ik(i,e){let t=Oy.exec(i),r=Number(t[1]);switch(t[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}var wn=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,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},km=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=AE(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new wn(this,"textTrack1"),t=new wn(this,"textTrack2"),r=new wn(this,"textTrack3"),s=new wn(this,"textTrack4");this.cea608Parser1=new jd(1,e,t),this.cea608Parser2=new jd(3,r,s)}addCues(e,t,r,s,n){let a=!1;for(let o=n.length;o--;){let l=n[o],d=rk(l[0],l[1],t,r);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],r),a=!0,d/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,r,s)}else{let o=this.Cues.newCue(null,t,r,s);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:s,timescale:n}){let{unparsedVttFrags:a}=this;r===X.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.initPTS[o.frag.cc]?this.onFragLoaded(v.FRAG_LOADED,o):this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:o.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:r}=this;if(r)for(let s=0;s<r.textTracks.length;s++){let n=r.textTracks[s];if(_E(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:r,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)r[e]=o,Cn(r[e]),Ly(r[e],s);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,r[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let r=t.label,s={_id:e,label:r,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,r){let s=this.media;if(s)return s.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let r=!!t.transferMedia;if(this.media=null,r)return;let{captionsTracks:s}=this;Object.keys(s).forEach(n=>{Cn(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=AE(),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 r=0;r<t.length;r++)Cn(t[r])}onSubtitleTracksUpdated(e,t){let r=t.subtitleTracks||[],s=r.some(n=>n.textCodec===yf);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ty(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){let a=this.media,o=a?_d(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let u;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&_E(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Cn(u);else{let c=Uy(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{let s=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=r.name,r.lang&&(a.languageCode=r.lang),a.media=r)})}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===X.MAIN){var r,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(r=(s=t.part)==null?void 0:s.index)!=null?r:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:r,payload:s}=t;if(r.type===X.SUBTITLE)if(s.byteLength){let n=r.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[r.level],l=this.vttCCs;l[r.cc]||(l[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===yf?this._parseIMSC1(r,s):this._parseVTTs(t)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let r=this.hls;yE(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),r.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{r.logger.log(`Failed to parse IMSC1: ${s}`),r.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;let{frag:r,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[r.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=r.initSegment)!=null&&t.data?oi(r.initSegment.data,new Uint8Array(s)).buffer:s;XR(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{let c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(r,s),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>r.cc)&&l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,t){let r=this.tracks[e.level];r.textCodec||yE(t,this.initPTS[e.cc],()=>{r.textCodec=yf,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){let r=this.hls;if(this.config.renderTextTracksNatively){let s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>Ry(s,n))}else{let s=this.tracks[t];if(!s)return;let n=s.default?"default":"subtitles"+t;r.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:r}=t;r.type===X.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:r,samples:s}=t;if(!(r.type===X.MAIN&&this.closedCaptionsForLevel(r)==="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:r,endOffsetSubtitles:s,type:n}){let{media:a}=this;if(!(!a||a.currentTime<r)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>fm(o[l],t,r))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>fm(o[l],t,s))}}}extractCea608Data(e){let t=[[],[]],r=e[0]&31,s=2;for(let n=0;n<r;n++){let a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){let u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function Uy(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function _E(i,e){return!!i&&i.kind===Uy(e)&&im(e,i)}function rk(i,e,t,r){return Math.min(e,r)-Math.max(i,t)}function AE(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var sk=/\s/,nk={newCue(i,e,t,r){let s=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(n=r.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)sk.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=My(d.trim()),m=tp(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return i&&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=>Ry(i,h))),s}};function ak(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var ok=/(\d+)-(\d+)\/(\d+)/,zd=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||ck,this.controller=new self.AbortController,this.stats=new no}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,r){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=lk(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&z(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(go(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;let f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},d-(f-s.loading.start)),!c.ok){let{status:p,statusText:g}=c;throw new Dm(g||"fetch, bad network response",p,c)}s.loading.first=f,s.total=uk(c.headers)||s.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&z(t.highWaterMark)?this.loadProgressively(c,s,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=c[o];p&&(s.loaded=s.total=p);let g={url:m.url,data:c,code:m.status},E=(h=this.callbacks)==null?void 0:h.onProgress;E&&!z(t.highWaterMark)&&E(s,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,s,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),s.aborted)return;let f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.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,r,s=0,n){let a=new Nd,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<s||a.dataLength?(a.push(u),a.dataLength>=s&&n(t,r,a.flush().buffer,e)):n(t,r,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function lk(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ne({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function dk(i){let e=ok.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function uk(i){let e=i.get("Content-Range");if(e){let r=dk(e);if(z(r))return r}let t=i.get("Content-Length");if(t)return parseInt(t)}function ck(i,e){return new self.Request(i.url,e)}var Dm=class extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}},hk=/^age:\s*[\d.]+\s*$/im,Qd=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 no,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,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let r=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!==r||this.stats.aborted))return n(r,t.url)}).catch(a=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),n(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:a.message},t,r,s)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=r.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),r.timeout=n&&z(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:r}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!r.aborted&&s>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=u!=null?u:t.response;if(m!=null){var a,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;r.loaded=r.total=p,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(r,e,m,t);let E={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(E,r,e,t);return}}let c=n.loadPolicy.errorRetry,h=r.retry,f={url:e.url,data:void 0,code:d};if(Cd(c,h,!1,f))this.retry(c);else{var l;Ce.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Cd(e,t,!0))this.retry(e);else{var r;Ce.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:r}=this;this.retryDelay=Vm(e,r.retry),r.retry++,Ce.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&hk.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}},fk={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},mk=Be(Be({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:Qd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Cf,bufferController:am,capLevelController:om,errorController:wf,fpsController:hm,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:qE,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:fk},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},pk()),{},{subtitleStreamController:Tm,subtitleTrackController:mm,timelineController:km,audioStreamController:tm,audioTrackController:rm,emeController:Vd,cmcdController:um,contentSteeringController:cm,interstitialsController:ym});function pk(){return{cueHandler:nk,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 gk(i,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 r=Cm(i),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(u=>{let c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);let f=r[o].default;switch(e[o]={default:f},u){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}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Xe(e[o])}`)}),Be(Be({},r),e)}function Cm(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Cm):Object.keys(i).reduce((e,t)=>(e[t]=Cm(i[t]),e),{}):i}function vk(i,e){let t=i.loader;t!==zd&&t!==Qd?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):ak()&&(i.loader=zd,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Ad=2,Ek=.1,yk=.05,Tk=100,wm=class extends wd{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,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 r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.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(Tk),this.mediaSource=t.mediaSource;let r=this.media=t.media;Qt(r,"playing",this.onMediaPlaying),Qt(r,"waiting",this.onMediaWaiting),Qt(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:r}=this;r&&(ai(r,"playing",this.onMediaPlaying),ai(r,"waiting",this.onMediaWaiting),ai(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((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 r,s;let n=(r=this.hls)==null?void 0:r.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=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&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1}));return}if(!ge.getBuffered(a).length){this.nudgeRetry=0;return}let c=ge.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let k=SE(this.hls.inFlightFragments,e),x=c.len>Ad,A=!h||k||h-e>Ad&&!f.getPartialFragment(e);if(x||A)return;this.moved=!1}let m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;let x=Math.max(h,c.start||0)-e,L=!!(m!=null&&m.live)?m.targetduration*2:Ad,I=f.getPartialFragment(e);if(x>0&&(x<=L||I)){a.paused||this._trySkipBufferHole(I);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),E=this.waiting,T=this.stalled;if(T===null)if(E>0&&g-E<p)T=this.stalled=E;else{this.stalled=g;return}let y=g-T;if(!o&&(y>=p||E)&&this.hls){var b;if(((b=this.mediaSource)==null?void 0:b.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let S=ge.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(S,y,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(v.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&s&&s.length>1&&e>s.end(0)){let n=ge.bufferedInfo(ge.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=ge.timeRangesToArray(s),o=ge.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=ge.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=this.fragmentTracker.getPartialFragment(e)||void 0,f=ge.bufferInfo(this.media,e,0);this.hls.trigger(v.ERROR,{type:ee.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,r){var s,n;let{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=a.getPartialFragment(r);if((u||d!=null&&d.live&&r<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-r<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let r=this.fragmentTracker,s=e.nextStart;if(r&&s){let n=r.getFragAtPos(t,X.MAIN),a=r.getFragAtPos(s,X.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:r,stallReported:s,stalled:n}=this;if(!s&&n!==null&&r&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Xe(e)})`);this.warn(a.message),t.trigger(v.ERROR,{type:ee.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:r,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!r||!n)return 0;let a=s.currentTime,o=ge.bufferInfo(s,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){let p=r.getAppendedFrag(0,X.MAIN);p&&l<p.end&&(m=!0)}if(!m){let p=e||r.getAppendedFrag(a,X.MAIN);if(p){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||SE(this.hls.inFlightFragments,l))return 0;let E=!1,T=p.end;for(;T<l;){let y=r.getAppendedFrag(T,X.MAIN)||r.getPartialFragment(T);if(y)T+=y.duration;else{E=!0;break}}if(E)return 0}}}let f=Math.max(l+yk,a+Ek);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`);this.hls.trigger(v.ERROR,{type:ee.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:e||void 0,buffer:o.len,bufferInfo:o})}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:r,nudgeRetry:s}=this,n=t==null?void 0:t.config;if(!r||!n)return 0;let a=r.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){let o=a+(s+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),r.currentTime=o,t.trigger(v.ERROR,{type:ee.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:l,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(v.ERROR,{type:ee.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function SE(i,e){let t=IE(i.main);if(t&&t.start<=e)return t;let r=IE(i.audio);return r&&r.start<=e?r:null}function IE(i){if(!i)return null;switch(i.state){case O.IDLE:case O.STOPPED:case O.ENDED:case O.ERROR:return null}return i.frag}var bk=.25;function Mm(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function xE(i,e,t,r,s){let n=new i(e,t,"");try{n.value=r,s&&(n.type=s)}catch{n=new i(e,t,Xe(s?Be({type:s},r):r))}return n}var gd=(()=>{let i=Mm();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function _k(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Pm=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(v.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.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){let e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Cn(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 r=e[t];if(r.kind==="metadata"&&r.label==="id3")return Ly(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;let{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:s}}}=this;if(!r&&!s)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Mm();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===zt.emsg&&!r||!s)continue;let d=dy(n[o].data);if(d){let u=n[o].pts,c=u+n[o].duration;c>gd&&(c=gd),c-u<=0&&(c=u+bk);for(let f=0;f<d.length;f++){let m=d[f];if(!uy(m)){this.updateId3CueEnds(u,l);let p=xE(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,t){var r;let s=(r=this.id3Track)==null?void 0:r.cues;if(s)for(let n=s.length;n--;){let a=s[n];a.type===t&&a.startTime<e&&a.endTime===gd&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:s}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;s==="audio"?d=u=>u.type===zt.audioId3&&l:s==="video"?d=u=>u.type===zt.emsg&&o:d=u=>u.type===zt.audioId3&&l||u.type===zt.emsg&&o,fm(n,t,r,d)}}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.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;let{id3Track:r}=this,{dateRanges:s}=e,n=Object.keys(s),a=this.dateRangeCuesAppended;if(r&&t){var o;if((o=r.cues)!=null&&o.length){let u=Object.keys(a).filter(c=>!n.includes(c));for(let c=u.length;c--;){let h=u[c],f=a[h].cues;delete a[h],Object.keys(f).forEach(m=>{try{let p=f[m];p.removeEventListener("enter",this.onEventCueEnter),r.removeCue(p)}catch{}})}}else a=this.dateRangeCuesAppended={}}let l=e.fragments[e.fragments.length-1];if(n.length===0||!z(l==null?void 0:l.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));let d=Mm();for(let u=0;u<n.length;u++){let c=n[u],h=s[c],f=h.startTime,m=a[c],p=(m==null?void 0:m.cues)||{},g=(m==null?void 0:m.durationKnown)||!1,E=gd,{duration:T,endDate:y}=h;if(y&&T!==null)E=f+T,g=!0;else if(h.endOnNext&&!g){let S=n.reduce((k,x)=>{if(x!==h.id){let A=s[x];if(A.class===h.class&&A.startDate>h.startDate&&(!k||h.startDate<k.startDate))return A}return k},null);S&&(E=S.startTime,g=!0)}let b=Object.keys(h.attr);for(let S=0;S<b.length;S++){let k=b[S];if(!Ox(k))continue;let x=p[k];if(x)g&&!m.durationKnown?x.endTime=E:Math.abs(x.startTime-f)>.01&&(x.startTime=f,x.endTime=E);else if(d){let A=h.attr[k];Nx(k)&&(A=_k(A));let I=xE(d,f,E,{key:k,data:A},zt.dateRange);I&&(I.id=c,this.id3Track.addCue(I),p[k]=I,this.hls.config.interstitialsController&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&I.addEventListener("enter",this.onEventCueEnter))}}a[c]={cues:p,dateRange:h,durationKnown:g}}}},Om=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,r=this.levelDetails;if(!t||!r)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||!r.live)return;let o=this.targetLatency;if(o===null)return;let l=s-o,d=Math.min(this.maxLatency,o+r.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,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:r,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*s);let u=s;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}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 r=this.levelDetails;if(r===null)return null;let s=r.edge,n=e-t-this.edgeStalled,a=s-r.totalduration,o=s-(this.config.lowLatencyMode&&r.partTarget||r.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 r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===w.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,s;e.playbackRate!==t&&((r=this.hls)==null||r.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}},Nm=class extends vo{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let r=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,d=!1;t.levels.forEach(u=>{let c=u.attrs,{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=xd(h,r)||void 0),f&&(f=u.videoCodec=ox(f));let{width:m,height:p,unknownCodecs:g}=u,E=g?g.length:0;if(g)for(let I=E;I--;){let C=g[I];this.isAudioSupported(C)?(u.audioCodec=h=h?`${h},${C}`:C,E--,Nn.audio[h.substring(0,4)]=2):this.isVideoSupported(C)&&(u.videoCodec=f=f?`${f},${C}`:C,E--,Nn.video[f.substring(0,4)]=2)}if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),E||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}let{CODECS:T,"FRAME-RATE":y,"HDCP-LEVEL":b,"PATHWAY-ID":S,RESOLUTION:k,"VIDEO-RANGE":x}=c,L=`${`${S||"."}-`}${u.bitrate}-${k}-${y}-${T}-${x}-${b}`;if(n[L])if(n[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let I=a[L]+=1;u.attrs["PATHWAY-ID"]=new Array(I+1).join(".");let C=this.createLevel(u);n[L]=C,s.push(C)}else n[L].addGroupId("audio",c.AUDIO),n[L].addGroupId("text",c.SUBTITLES);else{let I=this.createLevel(u);n[L]=I,a[L]=1,s.push(I)}}),this.filterAndSortMediaOptions(s,t,o,l,d)}createLevel(e){let t=new Ms(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){let s=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(s.message),t.supportedResult=BE(s,[])}return t}isAudioSupported(e){return Rf(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Rf(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,s,n){let a=[],o=[],l=e;if((r||s)&&n&&(l=l.filter(({videoCodec:g,videoRange:E,width:T,height:y})=>(!!g||!!(T&&y))&&px(E))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let g="no level with compatible codecs found in manifest",E=g;t.levels.length&&(E=`one or more CODECS in variant not supported: ${Xe(t.levels.map(y=>y.attrs.CODECS).filter((y,b,S)=>S.indexOf(y)===b))}`,this.warn(E),g+=` (${E})`);let T=new Error(g);this.hls.trigger(v.ERROR,{type:ee.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}});return}t.audioTracks&&(a=t.audioTracks.filter(g=>!g.audioCodec||this.isAudioSupported(g.audioCodec)),LE(a)),t.subtitles&&(o=t.subtitles,LE(o));let d=l.slice(0);l.sort((g,E)=>{if(g.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&g.height!==E.height)return g.height-E.height;if(g.frameRate!==E.frameRate)return g.frameRate-E.frameRate;if(g.videoRange!==E.videoRange)return Ld.indexOf(g.videoRange)-Ld.indexOf(E.videoRange);if(g.videoCodec!==E.videoCodec){let T=Lv(g.videoCodec),y=Lv(E.videoCodec);if(T!==y)return y-T}if(g.uri===E.uri&&g.codecSet!==E.codecSet){let T=Id(g.codecSet),y=Id(E.codecSet);if(T!==y)return y-T}return g.averageBitrate!==E.averageBitrate?g.averageBitrate-E.averageBitrate:0});let u=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let g=0;g<d.length;g++)if(d[g].pathwayId===l[0].pathwayId){u=d[g];break}}this._levels=l;for(let g=0;g<l.length;g++)if(l[g]===u){var c;this._firstLevel=g;let E=u.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${E}`),((c=this.hls.userConfig)==null?void 0:c.abrEwmaDefaultEstimate)===void 0){let y=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);y>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}let h=n&&!s,f=this.hls.config,m=!!(f.audioStreamController&&f.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:m&&!h&&a.some(g=>!!g.url)};this.hls.trigger(v.MANIFEST_PARSED,p)}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 u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(v.ERROR,{type:ee.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let r=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,r===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 ${r}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,s==null?void 0:s.details,d);this.loadPlaylist(u)}}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(),r=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=r}}onError(e,t){t.fatal||!t.context||t.context.type===Ae.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===X.MAIN){let r=t.elementaryStreams;if(!Object.keys(r).some(n=>!!r[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 r;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 l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,t,l)}else(r=t.deliveryDirectives)!=null&&r.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 r=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||""):""} ${r}`),this.hls.trigger(v.LEVEL_LOADING,{url:r,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 r=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));ey(r),this._levels=r,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=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(v.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}};function LE(i){let e={};i.forEach(t=>{let r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}function Fy(){return self.SourceBuffer||self.WebKitSourceBuffer}function By(){if(!Br())return!1;let e=Fy();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ak(){if(!By())return!1;let i=Br();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(ao(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(ao(e,"audio"))))}function Sk(){var i;let e=Fy();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var Ik=100,Um=class extends ho{constructor(e,t,r){super(e,t,r,"stream-controller",X.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||!z(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(s,n,X.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(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:r,hls:s}=this;if(this.stopLoad(),this.setInterval(Ik),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}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=O.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case O.WAITING_LEVEL:{let{levels:t,level:r}=this,s=t==null?void 0:t[r],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=O.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=O.IDLE;break}break}case O.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),r=this.retryDate;if(!r||t>=r||(e=this.media)!=null&&e.seeking){let{levels:s,level:n}=this,a=s==null?void 0:s[n];this.resetStartWhenNotLoaded(a||null),this.state=O.IDLE}}break}this.state===O.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:r,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(!(r!=null&&r[n]))return;let a=r[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(v.BUFFER_EOS,p),this.state=O.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 d=a.details;if(!d||this.state===O.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=O.WAITING_LEVEL,this.startFragRequested=!1;return}let u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&bt(f)&&this.fragmentTracker.getState(f)!==pt.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,E=d.fragments[g-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 g=this.audioOnly&&!this.altAudio?We.AUDIO:We.VIDEO,E=(g===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,g,X.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,X.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,r){let s=this.fragmentTracker.getState(e);s===pt.NOT_LOADED||s===pt.PARTIAL?bt(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,X.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 r,s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?r=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:r=0}else r=0;let a=this.getBufferedFrag(t.currentTime+r);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,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 O.KEY_LOADING:case O.FRAG_LOADING:case O.FRAG_LOADING_WAITING_RETRY:case O.PARSING:case O.PARSED:this.state=O.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 r=t.media;Qt(r,"playing",this.onMediaPlaying),Qt(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:r}=this;r&&(ai(r,"playing",this.onMediaPlaying),ai(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,s=!1;t.levels.forEach(n=>{let a=n.audioCodec;a&&(r=r||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=r&&s&&!Sk(),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:r}=this;if(!r||this.state!==O.IDLE)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var r;let{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,l=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:${l}`);let d=t.levelInfo,u=this.fragCurrent;u&&(this.state===O.FRAG_LOADING||this.state===O.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(r=d.details)!=null&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(v.LEVEL_UPDATED,{details:o,level:a}),this.state===O.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=O.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:r}=this;if(!r)return;let s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&r.duration>s&&(n<s||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&r.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),r.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 d;let c=ge.bufferInfo(r,s,0);if(!(c!=null&&(d=c.buffered)!=null&&d.length)){r.currentTime=s;return}if(c.start<=n){r.currentTime=s;return}let{nextStart:f}=ge.bufferedInfo(c.buffered,n,0);f&&(r.currentTime=f)}else r.currentTime=s}}_handleFragmentLoadProgress(e){var t;let r=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}let o=a[r.level];if(!o){this.warn(`Level ${r.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=r.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Gd(this.hls,X.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,p=m!==-1,g=new uo(r.level,r.sn,r.stats.chunkCount,n.byteLength,m,p),E=this.initPTS[r.cc];f.push(n,c,h,d,r,s,l.totalduration,u,g,E)}onAudioTrackSwitching(e,t){let r=this.hls,s=this.altAudio===2;if(kd(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;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.fragmentTracker.removeAllFragments(),r.once(v.BUFFER_FLUSHED,()=>{var a;(a=this.hls)==null||a.trigger(v.AUDIO_TRACK_SWITCHED,t)}),r.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let r=kd(t.url,this.hls);if(r){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=r?2:0,this.tick()}onBufferCreated(e,t){let r=t.tracks,s,n,a=!1;for(let o in r){let l=r[o];if(l.id==="main"){if(n=o,s=l,o==="video"){let d=r[o];d&&(this.videoBuffer=d.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:r,part:s}=t,n=r.type===X.MAIN;if(n){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}let o=s?s.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),bt(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,s)}let a=this.media;a&&(!this._hasEnoughToStart&&ge.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===Ae.LEVEL&&(this.state=O.IDLE);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=O.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==We.AUDIO||!this.altAudio){let r=(t===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,X.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,r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}let s=this.timelineOffset;s&&r&&(r+=s);let n=this.getLevelDetails(),a=ge.getBuffered(e),o=a.length?a.start(0):0,l=o-r,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),r+=l,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${o}`),e.currentTime=r)}}_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(r=>{let{hls:s}=this,n=r==null?void 0:r.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=O.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(v.FRAG_LOADED,r),n.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let r=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:u}=o,{video:c,text:h,id3:f,initSegment:m}=n,{details:p}=u,g=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=O.PARSING,m){if(m!=null&&m.tracks){let b=l.initSegment||l;this._bufferInitSegment(u,m.tracks,b,a),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:r,tracks:m.tracks})}let E=m.initPTS,T=m.timescale,y=this.initPTS[l.cc];z(E)&&(!y||y.baseTime!==E||y.timescale!==T)&&(this.initPTS[l.cc]={baseTime:E,timescale:T},s.trigger(v.INIT_PTS_FOUND,{frag:l,id:r,initPTS:E,timescale:T}))}if(c&&p){g&&c.type==="audiovideo"&&this.logMuxedErr(l);let E=p.fragments[l.sn-1-p.startSN],T=l.sn===p.startSN,y=!E||l.cc>E.cc;if(n.independent!==!1){let{startPTS:b,endPTS:S,startDTS:k,endDTS:x}=c;if(d)d.elementaryStreams[c.type]={startPTS:b,endPTS:S,startDTS:k,endDTS:x};else if(c.firstKeyFrame&&c.independent&&a.id===1&&!y&&(this.couldBacktrack=!0),c.dropped&&c.independent){let A=this.getMainFwdBufferInfo(),L=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,I=c.firstKeyFramePTS?c.firstKeyFramePTS:b;if(!T&&L<I-this.config.maxBufferHole&&!y){this.backtrack(l);return}else y&&(l.gap=!0);l.setElementaryStreamInfo(c.type,l.start,S,l.start,x,!0)}else T&&b-(p.appliedTimelineOffset||0)>Ad&&(l.gap=!0);l.setElementaryStreamInfo(c.type,b,S,k,x),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,a,T||y)}else if(T||y)l.gap=!0;else{this.backtrack(l);return}}if(g){let{startPTS:E,endPTS:T,startDTS:y,endDTS:b}=g;d&&(d.elementaryStreams[We.AUDIO]={startPTS:E,endPTS:T,startDTS:y,endDTS:b}),l.setElementaryStreamInfo(We.AUDIO,E,T,y,b),this.bufferFragmentData(g,l,d,a)}if(p&&f!=null&&(t=f.samples)!=null&&t.length){let E={id:r,frag:l,details:p,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,E)}if(p&&h){let E={id:r,frag:l,details:p,samples:h.samples};s.trigger(v.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${bt(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,s){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=vd(n.codec,d);u==="mp4a"&&(u="mp4a.40.5");let c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=X.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=X.MAIN;let d=a.codec;if((d==null?void 0:d.length)===4)switch(d){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||""}/${d}]${a.codec!==d?" 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 l=Object.keys(t);if(l.length){if(this.hls.trigger(v.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:d,data:c,frag:r,part:null,chunkMeta:s,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,X.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,r=e==null?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let r=e.currentTime;if(ge.isBuffered(e,r)?t=this.getAppendedFrag(r):ge.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;let s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return z(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(z(t)){let r=this.getLevelDetails(),s=this.currentFrag||(r?Ps(null,r.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}},Fm=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let r in this.keyUriToKeyInfo){let s=this.keyUriToKeyInfo[r].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,r,s,n){return new Ai({type:ee.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length){let{sn:r,cc:s}=e;for(let n=0;n<t.length;n++){let a=t[n];if(s<=a.cc&&(r==="initSegment"||a.sn==="initSegment"||r<a.sn))return this.emeController.selectKeySystemFormat(a).then(o=>{if(a.setKeyFormat(o),this.emeController&&this.config.requireKeySystemAccessOnStart){let l=yd(o);if(l)return this.emeController.getKeySystemAccess([l])}})}}else if(this.config.requireKeySystemAccessOnStart){let r=Ja(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,s;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((r=o)!=null&&r.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(d=>(n.key=d.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let s=this.emeController.loadKey(r);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,r))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(r)}loadKeyHTTP(e,t){let r=this.config,s=r.loader,n=new s(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:E,url:T}=m;if(!g.decryptdata||E!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(g,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,E.loader=null,a({frag:g,keyInfo:E})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Be({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){let{frag:t,keyInfo:r,url:s}=e,n=r.loader;t.keyLoader===n&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}};function RE(i){let{type:e}=i;switch(e){case Ae.AUDIO_TRACK:return X.AUDIO;case Ae.SUBTITLE_TRACK:return X.SUBTITLE;default:return X.MAIN}}function Af(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Bm=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(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,r=t.pLoader,s=t.loader,n=r||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:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ae.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:r,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:r,level:s,pathwayId:n,responseType:"text",type:Ae.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:r,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:r,groupId:s,level:null,responseType:"text",type:Ae.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:r,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:r,groupId:s,level:null,responseType:"text",type:Ae.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let r=this.loaders[Ae.LEVEL];if(r){let s=r.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(r.abort(),delete this.loaders[Ae.LEVEL])}}load(e){var t;let r=this.hls.config,s=this.getInternalLoader(e);if(s){let d=this.hls.logger,u=s.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===Ae.MANIFEST?n=r.manifestLoadPolicy.default:n=Ne({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),z((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Ae.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Ae.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Ae.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let u=d.partTarget,c=d.targetduration;if(u&&c){let h=Math.max(u*3,c*.8)*1e3;n=Ne({},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},l={onSuccess:(d,u,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=d.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(d,c,new Error("no EXTM3U delimiter"),h||null,u);return}u.parsing.start=performance.now(),Ds.isMediaPlaylist(m)||c.type!==Ae.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,s){let n=this.hls,a=e.data,o=Af(e,r),l=Ds.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,r,l.playlistParsingError,s,t);return}let{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m;let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":E}=Ds.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(y=>!y.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new et({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:E,contentSteering:d,url:o,stats:t,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,r,s,n){let a=this.hls,{id:o,level:l,type:d}=r,u=Af(e,r),c=z(l)?l:z(o)?o:0,h=RE(r),f=Ds.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Ae.MANIFEST){let m={attrs:new et({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+XE(f,0),a.trigger(v.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,s,n)}handleManifestParsingError(e,t,r,s,n){this.hls.trigger(v.ERROR,{type:ee.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===Ae.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,r=!1,s,n){let a=`A network ${r?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===Ae.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ae.AUDIO_TRACK||e.type===Ae.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=w.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Ae.MANIFEST:l=r?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,d=!0;break;case Ae.LEVEL:l=r?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,d=!1;break;case Ae.AUDIO_TRACK:l=r?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ae.SUBTITLE_TRACK:l=r?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:ee.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(s){let h=(t==null?void 0:t.url)||e.url;c.response=Be({url:h,data:void 0},s)}this.hls.trigger(v.ERROR,c)}handlePlaylistLoaded(e,t,r,s,n,a){let o=this.hls,{type:l,level:d,id:u,groupId:c,deliveryDirectives:h}=s,f=Af(t,s),m=RE(s),p=typeof s.level=="number"&&m===X.MAIN?d:void 0;if(!e.fragments.length){let E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(v.ERROR,{type:ee.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:r});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));let g=e.playlistParsingError;if(g){if(this.hls.logger.warn(g),!o.config.ignorePlaylistParsingErrors){o.trigger(v.ERROR,{type:ee.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:g,reason:g.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:r});return}e.playlistParsingError=null}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Ae.MANIFEST:case Ae.LEVEL:o.trigger(v.LEVEL_LOADED,{details:e,levelInfo:s.levelOrTrack||o.levels[0],level:p||0,id:u||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:l===Ae.MANIFEST});break;case Ae.AUDIO_TRACK:o.trigger(v.AUDIO_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:u||0,groupId:c||"",stats:r,networkDetails:n,deliveryDirectives:h});break;case Ae.SUBTITLE_TRACK:o.trigger(v.SUBTITLE_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:u||0,groupId:c||"",stats:r,networkDetails:n,deliveryDirectives:h});break}}},To=class i{static get version(){return fo}static isMSESupported(){return By()}static isSupported(){return Ak()}static getMediaSource(){return Br()}static get Events(){return v}static get MetadataSchema(){return zt}static get ErrorTypes(){return ee}static get ErrorDetails(){return w}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:mk}static set DefaultConfig(e){i.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 Ym,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=BI(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=gk(i.DefaultConfig,e,t);this.userConfig=e,r.progressive&&vk(r,t);let{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=r,d=new o(this),u=this.abrController=new s(this),c=new Mf(this),h=r.interstitialsController,f=h?this.interstitialsController=new h(this,i):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),E=new Bm(this),T=r.contentSteeringController,y=T?new T(this):null,b=this.levelController=new Nm(this,y),S=new Pm(this),k=new Fm(this.config),x=this.streamController=new Um(this,c,k),A=this.gapController=new wm(this,c);p.setStreamController(x),g.setStreamController(x);let L=[E,b,x];f&&L.splice(1,0,f),y&&L.splice(1,0,y),this.networkControllers=L;let I=[u,m,A,p,g,S,c];this.audioTrackController=this.createController(r.audioTrackController,L);let C=r.audioStreamController;C&&L.push(this.audioStreamController=new C(this,c,k)),this.subtitleTrackController=this.createController(r.subtitleTrackController,L);let P=r.subtitleStreamController;P&&L.push(this.subtititleStreamController=new P(this,c,k)),this.createController(r.timelineController,I),k.emeController=this.emeController=this.createController(r.emeController,I),this.cmcdController=this.createController(r.cmcdController,I),this.latencyController=this.createController(Om,I),this.coreComponents=I,L.push(d);let B=d.onErrorOut;typeof B=="function"&&this.on(v.ERROR,B,d),this.on(v.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){let r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,s){this._emitter.off(e,t,r,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;let s=e===v.ERROR;this.trigger(v.ERROR,{type:ee.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:s,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(v.ERROR,{type:ee.OTHER_ERROR,details:w.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,r=t?e.media:e,s=t?e:{media:r};this._media=r,this.trigger(v.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(v.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,r=this._url,s=this._url=$m.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&r&&(r!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[X.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[X.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[X.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=NR()),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){mx(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 r=e.length;for(let s=0;s<r;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,r)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=r)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 r=GE(t);return $E(e,r,navigator.mediaCapabilities)}};To.defaultConfig=void 0;var Ie=To,qe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},re={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},Ao=i=>i===qe.VIDEO?"playback":i,Hr=class bo extends Error{constructor(e,t=bo.MEDIA_ERR_CUSTOM,r,s){var n;super(e),this.name="MediaError",this.code=t,this.context=s,this.fatal=r!=null?r:t>=bo.MEDIA_ERR_NETWORK&&t<=bo.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=bo.defaultMessages[this.code])!=null?n:"")}};Hr.MEDIA_ERR_ABORTED=1,Hr.MEDIA_ERR_NETWORK=2,Hr.MEDIA_ERR_DECODE=3,Hr.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Hr.MEDIA_ERR_ENCRYPTED=5,Hr.MEDIA_ERR_CUSTOM=100,Hr.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 Y=Hr,xk=i=>i==null,up=(i,e)=>xk(e)?!1:i in e,sp={ANY:"any",MUTED:"muted"},ke={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},di={MSE:"mse",NATIVE:"native"},_o={HEADER:"header",QUERY:"query",NONE:"none"},Bn=Object.values(_o),mr={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},np={HLS:mr.M3U8},zP=Object.keys(np),QP=[...Object.values(mr),"hls","HLS"];var Lk="en",ap={code:Lk},dt=(i,e,t,r,s=i)=>{s.addEventListener(e,t,r),i.addEventListener("teardown",()=>{s.removeEventListener(e,t)},{once:!0})};function Rk(i,e,t){e&&t>e&&(t=e);for(let r=0;r<i.length;r++)if(i.start(r)<=t&&i.end(r)>=t)return!0;return!1}var ru=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),r=i.slice(e);return[t,r]},su=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return up(t,np)?np[t]:e}return kk(i)},zy=i=>i==="VOD"?ke.ON_DEMAND:ke.LIVE,Qy=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,kk=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=new URL(e).pathname}catch{console.error("invalid url")}let r=t.lastIndexOf(".");if(r<0)return Ck(i)?mr.M3U8:"";let s=t.slice(r+1).toUpperCase();return up(s,mr)?mr[s]:""},Dk="mux.com",Ck=({src:i,customDomain:e=Dk})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let r=t.protocol==="https:",s=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return r&&s&&a&&o},Gr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(atob(t).split("").map(function(s){return"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(r)}catch{return}},wk=({exp:i},e=Date.now())=>!i||i*1e3<e,Mk=({sub:i},e)=>i!==e,Pk=({aud:i},e)=>!i,Ok=({aud:i},e)=>i!==e,Xy="en";function te(i,e=!0){var t,r;let s=e&&(r=(t=ap)==null?void 0:t[i])!=null?r:i,n=e?ap.code:Xy;return new Nk(s,n)}var Nk=class{constructor(i,e=(t=>(t=ap)!=null?t:Xy)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var r;return(r=i[t])!=null?r:""})}toString(){return this.message}},Uk=Object.values(sp),$y=i=>typeof i=="boolean"||typeof i=="string"&&Uk.includes(i),Fk=(i,e,t)=>{let{autoplay:r}=i,s=!1,n=!1,a=$y(r)?r:!!r,o=()=>{s||dt(e,"playing",()=>{s=!0},{once:!0})};if(o(),dt(e,"loadstart",()=>{s=!1,o(),ip(e,a)},{once:!0}),dt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=!Number.isFinite(e.duration)),ip(e,a)},{once:!0}),t&&t.once(Ie.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&dt(e,"play",()=>{e.preload==="metadata"?t.once(Ie.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{s||(a=$y(l)?l:!!l,ip(e,a))}},ip=(i,e)=>{if(!e)return;let t=i.muted,r=()=>i.muted=t;switch(e){case sp.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(r)});break;case sp.MUTED:i.muted=!0,i.play().catch(r);break;default:i.play().catch(()=>{});break}},Bk=({preload:i,src:e},t,r)=>{let s=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!r)return s(i),s;let n=!1,a=!1,o=r.config.maxBufferLength,l=r.config.maxBufferSize,d=c=>{s(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(r.config.maxBufferLength=1,r.config.maxBufferSize=1):(r.config.maxBufferLength=o,r.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,r.loadSource(e))};return dt(t,"play",()=>{a=!0,r.config.maxBufferLength=o,r.config.maxBufferSize=l,u()},{once:!0}),d(i),d};function $k(i,e){var t;if(!("videoTracks"in i))return;let r=new WeakMap;e.on(Ie.Events.MANIFEST_PARSED,function(l,d){o();let u=i.addVideoTrack("main");u.selected=!0;for(let[c,h]of d.levels.entries()){let f=u.addRendition(h.url[0],h.width,h.height,h.videoCodec,h.bitrate);r.set(h,`${c}`),f.id=`${c}`}}),e.on(Ie.Events.AUDIO_TRACKS_UPDATED,function(l,d){a();for(let u of d.audioTracks){let c=u.default?"main":"alternative",h=i.addAudioTrack(c,u.name,u.lang);h.id=`${u.id}`,u.default&&(h.enabled=!0)}}),i.audioTracks.addEventListener("change",()=>{var l;let d=+((l=[...i.audioTracks].find(c=>c.enabled))==null?void 0:l.id),u=e.audioTracks.map(c=>c.id);d!=e.audioTrack&&u.includes(d)&&(e.audioTrack=d)}),e.on(Ie.Events.LEVELS_UPDATED,function(l,d){var u;let c=i.videoTracks[(u=i.videoTracks.selectedIndex)!=null?u:0];if(!c)return;let h=d.levels.map(f=>r.get(f));for(let f of i.videoRenditions)f.id&&!h.includes(f.id)&&c.removeRendition(f)});let s=l=>{let d=l.target.selectedIndex;d!=e.nextLevel&&(e.nextLevel=d)};(t=i.videoRenditions)==null||t.addEventListener("change",s);let n=()=>{for(let l of i.videoTracks)i.removeVideoTrack(l)},a=()=>{for(let l of i.audioTracks)i.removeAudioTrack(l)},o=()=>{n(),a()};e.once(Ie.Events.DESTROYING,o)}var rp=i=>"time"in i?i.time:i.startTime;function Hk(i,e){e.on(Ie.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(d==null?void 0:d.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;nu(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let s=Array.from(i.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:l,name:d,type:u,default:c})=>s.id==="default"&&c||l==s.language&&d===s.label&&u.toLowerCase()===s.kind);e.subtitleTrack=o}(s==null?void 0:s.id)===a&&s.cues&&Array.from(s.cues).forEach(o=>{s.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(Ie.Events.CUES_PARSED,(s,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(Ie.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(s=>{s.remove()})});let r=()=>{Array.from(i.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 l=i.querySelector(o),d=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",d)},0)}s.mode!=="hidden"&&(s.mode="hidden")}})};e.once(Ie.Events.MANIFEST_LOADED,r),e.once(Ie.Events.MEDIA_ATTACHED,r)}function nu(i,e,t,r,s,n){let a=document.createElement("track");return a.kind=e,a.label=t,r&&(a.srclang=r),s&&(a.id=s),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function Zy(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),r=>r.track===e);t==null||t.remove()}function So(i,e,t){var r;return(r=Array.from(i.querySelectorAll("track")).find(s=>s.track.label===e&&s.track.kind===t))==null?void 0:r.track}async function Jy(i,e,t,r){let s=So(i,t,r);return s||(s=nu(i,r,t),s.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),s.mode!=="hidden"&&(s.mode="hidden"),[...e].sort((n,a)=>rp(a)-rp(n)).forEach(n=>{var a,o;let l=n.value,d=rp(n);if("endTime"in n&&n.endTime!=null)s==null||s.addCue(new VTTCue(d,n.endTime,r==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(s==null?void 0:s.cues,m=>m.startTime>=d),c=(a=s==null?void 0:s.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=s==null?void 0:s.cues)==null?void 0:o[u-1];f&&(f.endTime=d),s==null||s.addCue(new VTTCue(d,h,r==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),s}var cp="cuepoints",eT=Object.freeze({label:cp});async function hp(i,e,t=eT){return Jy(i,e,t.label,"metadata")}var op=i=>({time:i.startTime,value:JSON.parse(i.text)});function tT(i,e={label:cp}){let t=So(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,r=>op(r)):[]}function fp(i,e={label:cp}){var t,r;let s=So(i,e.label,"metadata");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return op(s.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((r=s.activeCues)!=null?r:[],({startTime:o,endTime:l})=>o<=n&&l>n);return op(a||s.activeCues[0])}async function Gk(i,e=eT){return new Promise(t=>{dt(i,"loadstart",async()=>{let r=await hp(i,[],e);dt(i,"cuechange",()=>{let s=fp(i);if(s){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:s});i.dispatchEvent(n)}},{},r),t(r)})})}var mp="chapters",iT=Object.freeze({label:mp}),lp=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function pp(i,e,t=iT){return Jy(i,e,t.label,"chapters")}function rT(i,e={label:mp}){var t;let r=So(i,e.label,"chapters");return(t=r==null?void 0:r.cues)!=null&&t.length?Array.from(r.cues,s=>lp(s)):[]}function gp(i,e={label:mp}){var t,r;let s=So(i,e.label,"chapters");if(!((t=s==null?void 0:s.activeCues)!=null&&t.length))return;if(s.activeCues.length===1)return lp(s.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((r=s.activeCues)!=null?r:[],({startTime:o,endTime:l})=>o<=n&&l>n);return lp(a||s.activeCues[0])}async function Kk(i,e=iT){return new Promise(t=>{dt(i,"loadstart",async()=>{let r=await pp(i,[],e);dt(i,"cuechange",()=>{let s=gp(i);if(s){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:s});i.dispatchEvent(n)}},{},r),t(r)})})}function sT(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function nT(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var Fn={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},Vk=i=>{if(i===qe.VIDEO)return Fn.VIDEO;if(i===qe.DRM)return Fn.DRM},Wk=(i,e)=>{var t,r;let s=Ao(i),n=`${s}Token`;return(t=e.tokens)!=null&&t[s]?(r=e.tokens)==null?void 0:r[s]:up(n,e)?e[n]:void 0},tu=(i,e,t,r,s=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let E=te("Your device appears to be offline",s),T,y=Y.MEDIA_ERR_NETWORK,b=new Y(E,y,!1,T);return b.errorCategory=e,b.muxCode=re.NETWORK_OFFLINE,b.data=i,b}let l="status"in i?i.status:i.code,d=Date.now(),u=Y.MEDIA_ERR_NETWORK;if(l===200)return;let c=Ao(e),h=Wk(e,t),f=Vk(e),[m]=ru((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=Gr(h);if(h&&!p){let E=te("The {tokenNamePrefix}-token provided is invalid or malformed.",s).format({tokenNamePrefix:c}),T=te("Compact JWT string: {token}",s).format({token:h}),y=new Y(E,u,!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_TOKEN_MALFORMED,y.data=i,y}if(l>=500){let E=new Y("",u,r!=null?r:!0);return E.errorCategory=e,E.muxCode=re.NETWORK_UNKNOWN_ERROR,E}if(l===403)if(p){if(wk(p,d)){let E={timeStyle:"medium",dateStyle:"medium"},T=te("The video\u2019s secured {tokenNamePrefix}-token has expired.",s).format({tokenNamePrefix:c}),y=te("Expired at: {expiredDate}. Current time: {currentDate}.",s).format({expiredDate:new Intl.DateTimeFormat("en",E).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",E).format(d)}),b=new Y(T,u,!0,y);return b.errorCategory=e,b.muxCode=re.NETWORK_TOKEN_EXPIRED,b.data=i,b}if(Mk(p,m)){let E=te("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",s).format({tokenNamePrefix:c}),T=te("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",s).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),y=new Y(E,u,!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_TOKEN_SUB_MISMATCH,y.data=i,y}if(Pk(p,f)){let E=te("The {tokenNamePrefix}-token is formatted with incorrect information.",s).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",s).format({tokenNamePrefix:c,expectedAud:f}),y=new Y(E,u,!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_TOKEN_AUD_MISSING,y.data=i,y}if(Ok(p,f)){let E=te("The {tokenNamePrefix}-token is formatted with incorrect information.",s).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",s).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),y=new Y(E,u,!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_TOKEN_AUD_MISMATCH,y.data=i,y}}else{let E=te("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=te("Specified playback ID: {playbackId}",s).format({playbackId:m}),y=new Y(E,u,r!=null?r:!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_TOKEN_MISSING,y.data=i,y}if(l===412){let E=te("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",s),T=te("Specified playback ID: {playbackId}",s).format({playbackId:m}),y=new Y(E,u,r!=null?r:!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_NOT_READY,y.streamType=t.streamType===ke.LIVE?"live":t.streamType===ke.ON_DEMAND?"on-demand":"unknown",y.data=i,y}if(l===404){let E=te("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",s),T=te("Specified playback ID: {playbackId}",s).format({playbackId:m}),y=new Y(E,u,r!=null?r:!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_NOT_FOUND,y.data=i,y}if(l===400){let E=te("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),T=te("Specified playback ID: {playbackId}",s).format({playbackId:m}),y=new Y(E,u,r!=null?r:!0,T);return y.errorCategory=e,y.muxCode=re.NETWORK_INVALID_URL,y.data=i,y}let g=new Y("",u,r!=null?r:!0);return g.errorCategory=e,g.muxCode=re.NETWORK_UNKNOWN_ERROR,g.data=i,g},Hy=Ie.DefaultConfig.capLevelController,aT=class oT extends Hy{constructor(e){super(e)}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,r)=>this.isLevelAllowed(t)&&r<=e)}getMaxLevel(e){let t=super.getMaxLevel(e),r=this.getValidLevels(e);if(!r[t])return t;let s=Math.min(r[t].width,r[t].height),n=oT.minMaxResolution;return s>=n?t:Hy.getMaxLevelByMediaSize(r,n*(16/9),n)}};aT.minMaxResolution=720;var qk=aT,Yk=qk,Jd={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},jk=i=>{if(i.includes("fps"))return Jd.FAIRPLAY;if(i.includes("playready"))return Jd.PLAYREADY;if(i.includes("widevine"))return Jd.WIDEVINE},zk=i=>{let e=i.split(`
|
|
56
56
|
`).find((t,r,s)=>r&&s[r-1].startsWith("#EXT-X-STREAM-INF"));return fetch(e).then(t=>t.status!==200?Promise.reject(t):t.text())},Qk=i=>{let e=i.split(`
|
|
57
57
|
`).filter(r=>r.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let r of e){let s=Zk(r),n=s["DATA-ID"];n&&(t[n]={...s})}return{sessionData:t}},Xk=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function Zk(i){let e=[...i.matchAll(Xk)];return Object.fromEntries(e.map(([,t,r])=>[t,r]))}var Jk=i=>{var e,t,r;let s=i.split(`
|
|
58
|
-
`),n=(t=((e=s.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=zy(n),o=Qy(n),l;if(a===ke.LIVE){let d=s.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=s.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(r=u==null?void 0:u.split(":"))==null?void 0:r[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},eD=async(i,e)=>{if(e===mr.MP4)return{streamType:ke.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===mr.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let r=await t.text(),s=await zk(r);return{...Qk(r),...Jk(s)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},tD=async(i,e,t=su({src:i}))=>{var r,s,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await eD(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&vp((r=c.URI)!=null?r:c.VALUE,e),((s=it.get(e))!=null?s:{}).liveEdgeStartOffset=d,((n=it.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=it.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},vp=async(i,e)=>{var t,r;try{let s=await fetch(i);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 l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((r=it.get(e))!=null?r:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(s){console.error(s)}},iD=i=>{var e;let t=i.type,r=zy(t),s=Qy(t),n,a=!!((e=i.partList)!=null&&e.length);return r===ke.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:r,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},rD=(i,e,t)=>{var r,s,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=iD(i);if(c===ke.LIVE){m?(t.config.backBufferLength=(r=t.userConfig.backBufferLength)!=null?r:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var E;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(E=t.liveSyncPosition)!=null?E:e.seekable.end(g)}});((o=it.get(e))!=null?o:{}).seekable=p}((l=it.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=it.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=it.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Gy,Ky,sD=(Ky=(Gy=globalThis==null?void 0:globalThis.navigator)==null?void 0:Gy.userAgent)!=null?Ky:"",Vy,Wy,qy,nD=(qy=(Wy=(Vy=globalThis==null?void 0:globalThis.navigator)==null?void 0:Vy.userAgentData)==null?void 0:Wy.platform)!=null?qy:"",aD=sD.toLowerCase().includes("android")||["x11","android"].some(i=>nD.toLowerCase().includes(i)),it=new WeakMap,pr="mux.com",Yy,jy,lT=(jy=(Yy=Ie).isSupported)==null?void 0:jy.call(Yy),oD=aD,au=()=>id.utils.now(),lD=id.utils.generateUUID,Io=({playbackId:i,customDomain:e=pr,maxResolution:t,minResolution:r,renditionOrder:s,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=ru(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),r&&(m.searchParams.set("min_resolution",r),t&&+t.slice(0,-1)<+r.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",r,"maxResolution",t)),s&&m.searchParams.set("rendition_order",s),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},ou=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},lu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},dD=i=>{var e,t,r;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:vT(i)&&(r=(t=ou(i.playbackId))!=null?t:lu(i.src))!=null?r:i.src},Ep=i=>{var e;return(e=it.get(i))==null?void 0:e.error},dT=i=>{var e;return(e=it.get(i))==null?void 0:e.metadata},iu=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.streamType)!=null?t:ke.UNKNOWN},uT=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},du=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},cT=i=>{var e;let t=(e=it.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let r=du(i);return r.length?r.end(r.length-1)-t:Number.NaN},yp=.034,uD=(i,e,t=yp)=>Math.abs(i-e)<=t,hT=(i,e,t=yp)=>i>e||uD(i,e,t),cD=(i,e=yp)=>i.paused&&hT(i.currentTime,i.duration,e),fT=(i,e)=>{var t,r,s;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(r=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:r.details:(s=e.levels.find(c=>!!c.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},Tp=(i,e)=>i.ended||i.loop?i.ended:e&&fT(i,e)?!0:cD(i),mT=(i,e,t)=>{bp(e,t,i);let{metadata:r={}}=i,{view_session_id:s=lD()}=r,n=dD(i);r.view_session_id=s,r.video_id=n,i.metadata=r;let a=u=>{var c;(c=e.mux)==null||c.emit("hb",{view_drm_type:u})};i.drmTypeCb=a,it.set(e,{retryCount:0});let o=hD(i,e),l=Bk(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?Ie:void 0}):ED(i,e,o),yD(i,e,o),Gk(e),Kk(e);let d=Fk(i,e,o);return{engine:o,setAutoplay:d,setPreload:l}},bp=(i,e,t)=>{let r=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?r&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),r&&(r.detachMedia(),r.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",yT),i.removeEventListener("error",dp),i.removeEventListener("durationchange",ET),it.delete(i),i.dispatchEvent(new Event("teardown")))};function pT(i,e){var t;let r=su(i);if(r!==mr.M3U8)return!0;let s=!r||((t=e.canPlayType(r))!=null?t:!0),{preferPlayback:n}=i,a=n===di.MSE,o=n===di.NATIVE;return s&&(o||!(lT&&(a||oD)))}var hD=(i,e)=>{let{debug:t,streamType:r,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=i,l=su(i)===mr.M3U8,d=pT(i,e);if(l&&!d&&lT){let u={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},c=fD(r),h=mD(i),f=[_o.QUERY,_o.HEADER].includes(a)?{useHeaders:a===_o.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,m=new Ie({debug:t,startPosition:s,cmcd:f,xhrSetup:(p,g)=>{var E,T;if(a&&a!==_o.QUERY)return;let y=new URL(g);if(!y.searchParams.has("CMCD"))return;let b=((T=(E=y.searchParams.get("CMCD"))==null?void 0:E.split(","))!=null?T:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");y.searchParams.set("CMCD",b),p.open("GET",y)},capLevelController:Yk,...u,...c,...h,...o});return m.on(Ie.Events.MANIFEST_PARSED,async function(p,g){var E,T;let y=(E=g.sessionData)==null?void 0:E["com.apple.hls.chapters"];(y!=null&&y.URI||y!=null&&y.VALUE.toLocaleLowerCase().startsWith("http"))&&vp((T=y==null?void 0:y.URI)!=null?T:y==null?void 0:y.VALUE,e)}),m}},fD=i=>i===ke.LIVE?{backBufferLength:8}:{},mD=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:r}=i,s=ou(t);return!e||!s?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:eu(i,"fairplay"),serverCertificateUrl:gT(i,"fairplay")},"com.widevine.alpha":{licenseUrl:eu(i,"widevine")},"com.microsoft.playready":{licenseUrl:eu(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=jk(n);return r==null||r(l),o}))}},pD=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},gD=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let r=await t.arrayBuffer();return new Uint8Array(r)},vD=(i,e)=>{dt(e,"encrypted",async t=>{try{let r=t.initDataType;if(r!=="skd"){console.error(`Received unexpected initialization data type "${r}"`);return}if(!e.mediaKeys){let l=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[r],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(u=>{var c;return(c=i.drmTypeCb)==null||c.call(i,Jd.FAIRPLAY),u}).catch(()=>{let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),c=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0);c.errorCategory=qe.DRM,c.muxCode=re.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,li(e,c)});if(!l)return;let d=await l.createMediaKeys();try{let u=await pD(gT(i,"fairplay")).catch(c=>{if(c instanceof Response){let h=tu(c,qe.DRM,i);return console.error("mediaError",h==null?void 0:h.message,h==null?void 0:h.context),h?Promise.reject(h):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(c)});await d.setServerCertificate(u).catch(()=>{let c=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),h=new Y(c,Y.MEDIA_ERR_ENCRYPTED,!0);return h.errorCategory=qe.DRM,h.muxCode=re.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(h)})}catch(u){li(e,u);return}await e.setMediaKeys(d)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.addEventListener("keystatuseschange",()=>{n.keyStatuses.forEach(l=>{let d;if(l==="internal-error"){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");d=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0),d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_CDM_ERROR}else if(l==="output-restricted"||l==="output-downscaled"){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");d=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!1),d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_OUTPUT_RESTRICTED}d&&li(e,d)})});let a=await Promise.all([n.generateRequest(r,s).catch(()=>{let l=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),d=new Y(l,Y.MEDIA_ERR_ENCRYPTED,!0);d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_GENERATE_REQUEST_FAILED,li(e,d)}),new Promise(l=>{n.addEventListener("message",d=>{l(d.message)},{once:!0})})]).then(([,l])=>l),o=await gD(a,eu(i,"fairplay")).catch(l=>{if(l instanceof Response){let d=tu(l,qe.DRM,i);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 license key request"))}return Promise.reject(l)});await n.update(o).catch(()=>{let l=te("Failed to update DRM license. This may be an issue with the player or your protected content."),d=new Y(l,Y.MEDIA_ERR_ENCRYPTED,!0);return d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_UPDATE_LICENSE_FAILED,Promise.reject(d)})}catch(r){li(e,r);return}})},eu=({playbackId:i,tokens:{drm:e}={},customDomain:t=pr},r)=>{let s=ou(i);return`https://license.${t.toLocaleLowerCase().endsWith(pr)?t:pr}/license/${r}/${s}?token=${e}`},gT=({playbackId:i,tokens:{drm:e}={},customDomain:t=pr},r)=>{let s=ou(i);return`https://license.${t.toLocaleLowerCase().endsWith(pr)?t:pr}/appcert/${r}/${s}?token=${e}`},vT=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let r=window==null?void 0:window.location.href,s=new URL(e,r).hostname.toLocaleLowerCase();return s.includes(pr)||!!t&&s.includes(t.toLocaleLowerCase())},ED=(i,e,t)=>{var r;let{envKey:s,disableTracking:n,muxDataSDK:a=id,muxDataSDKOptions:o={}}=i,l=vT(i);if(!n&&(s||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((r=i==null?void 0:i.metadata)==null?void 0:r.video_title)||void 0},g=E=>typeof E.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(E):E;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?Ie:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...s?{env_key:s}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},yD=(i,e,t)=>{var r,s;let n=pT(i,e),{src:a,customDomain:o=pr}=i,l=()=>{e.ended||i.disablePseudoEnded||!Tp(e,t)||(fT(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=du(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(dt(e,"durationchange",c),e&&n){let h=su(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=lu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);vp(g.toString(),e)}let f=()=>{if(iu(e)!==ke.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),dt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>tD(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=tu(p,qe.VIDEO,i);if(g){li(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};dt(e,"play",p,{once:!0}),dt(e,"loadedmetadata",g,{once:!0})}else m();(r=i.tokens)!=null&&r.drm?vD(i,e):dt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new Y(p,Y.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=qe.DRM,g.muxCode=re.ENCRYPTED_MISSING_TOKEN,li(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((s=it.get(e))!=null?s:{}).startTime=i.startTime,e.addEventListener("durationchange",ET,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",yT),e.addEventListener("error",dp),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),dt(e,"pause",l),dt(e,"seeked",l),dt(e,"play",()=>{e.ended||hT(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(Ie.Events.LEVEL_LOADED,(h,f)=>{rD(f.details,e,t),c(),iu(e)===ke.LIVE&&!Number.isFinite(e.duration)&&(t.on(Ie.Events.LEVEL_UPDATED,c),dt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(Ie.Events.LEVELS_UPDATED,c)}))}),t.on(Ie.Events.ERROR,(h,f)=>{var m,p;let g=TD(f,i);if(g.muxCode===re.NETWORK_NOT_READY){let E=(m=it.get(e))!=null?m:{},T=(p=E.retryCount)!=null?p:0;if(T<6){let y=T===0?5e3:6e4,b=new Y(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(b,g),li(e,b),setTimeout(()=>{E.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);return}else{E.retryCount=0;let y=new Y('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(y,g),li(e,y);return}}li(e,g)}),t.on(Ie.Events.MANIFEST_LOADED,()=>{let h=it.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",dp),dt(e,"waiting",l),$k(i,t),Hk(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 ET(i){var e;let t=i.target,r=(e=it.get(t))==null?void 0:e.startTime;if(r&&Rk(t.seekable,t.duration,r)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=r,s&&(t.preload="auto")}}async function yT(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:r}=e.error,s=new Y(t,r);if(e.src&&r===Y.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Ep(e))!=null?n:e.error;(a==null?void 0:a.code)===Y.MEDIA_ERR_SRC_NOT_SUPPORTED&&li(e,s)},500);return}if(e.src&&(r!==Y.MEDIA_ERR_DECODE||r!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}li(e,s)}function li(i,e){var t;e.fatal&&(((t=it.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function dp(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof Y))return;let r=i.target,s=i.detail;!s||!s.fatal||(((e=it.get(r))!=null?e:{}).error=s,(t=r.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var TD=(i,e)=>{var t,r,s;console.error("getErrorFromHlsErrorData()",i);let n={[Ie.ErrorTypes.NETWORK_ERROR]:Y.MEDIA_ERR_NETWORK,[Ie.ErrorTypes.MEDIA_ERROR]:Y.MEDIA_ERR_DECODE,[Ie.ErrorTypes.KEY_SYSTEM_ERROR]:Y.MEDIA_ERR_ENCRYPTED},a=u=>[Ie.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,Ie.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?Y.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===Ie.ErrorTypes.KEY_SYSTEM_ERROR)return qe.DRM;if(u.type===Ie.ErrorTypes.NETWORK_ERROR)return qe.VIDEO},l,d=a(i);if(d===Y.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:qe.VIDEO;l=(r=tu(i.response,u,e,i.fatal))!=null?r:new Y("",d,i.fatal)}else if(d===Y.MEDIA_ERR_ENCRYPTED)if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_MISSING_TOKEN}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=te("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_CDM_ERROR}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_OUTPUT_RESTRICTED}else l=new Y(i.error.message,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_ERROR;else l=new Y("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
58
|
+
`),n=(t=((e=s.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=zy(n),o=Qy(n),l;if(a===ke.LIVE){let d=s.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=s.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(r=u==null?void 0:u.split(":"))==null?void 0:r[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},eD=async(i,e)=>{if(e===mr.MP4)return{streamType:ke.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===mr.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let r=await t.text(),s=await zk(r);return{...Qk(r),...Jk(s)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},tD=async(i,e,t=su({src:i}))=>{var r,s,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await eD(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&vp((r=c.URI)!=null?r:c.VALUE,e),((s=it.get(e))!=null?s:{}).liveEdgeStartOffset=d,((n=it.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=it.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},vp=async(i,e)=>{var t,r;try{let s=await fetch(i);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 l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((r=it.get(e))!=null?r:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(s){console.error(s)}},iD=i=>{var e;let t=i.type,r=zy(t),s=Qy(t),n,a=!!((e=i.partList)!=null&&e.length);return r===ke.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:r,targetLiveWindow:s,liveEdgeStartOffset:n,lowLatency:a}},rD=(i,e,t)=>{var r,s,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=iD(i);if(c===ke.LIVE){m?(t.config.backBufferLength=(r=t.userConfig.backBufferLength)!=null?r:4,t.config.maxFragLookUpTolerance=(s=t.userConfig.maxFragLookUpTolerance)!=null?s:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var E;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(E=t.liveSyncPosition)!=null?E:e.seekable.end(g)}});((o=it.get(e))!=null?o:{}).seekable=p}((l=it.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=it.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=it.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Gy,Ky,sD=(Ky=(Gy=globalThis==null?void 0:globalThis.navigator)==null?void 0:Gy.userAgent)!=null?Ky:"",Vy,Wy,qy,nD=(qy=(Wy=(Vy=globalThis==null?void 0:globalThis.navigator)==null?void 0:Vy.userAgentData)==null?void 0:Wy.platform)!=null?qy:"",aD=sD.toLowerCase().includes("android")||["x11","android"].some(i=>nD.toLowerCase().includes(i)),it=new WeakMap,pr="mux.com",Yy,jy,lT=(jy=(Yy=Ie).isSupported)==null?void 0:jy.call(Yy),oD=aD,au=()=>id.utils.now(),lD=id.utils.generateUUID,Io=({playbackId:i,customDomain:e=pr,maxResolution:t,minResolution:r,renditionOrder:s,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=ru(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),r&&(m.searchParams.set("min_resolution",r),t&&+t.slice(0,-1)<+r.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",r,"maxResolution",t)),s&&m.searchParams.set("rendition_order",s),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},ou=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},lu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},dD=i=>{var e,t,r;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:vT(i)&&(r=(t=ou(i.playbackId))!=null?t:lu(i.src))!=null?r:i.src},Ep=i=>{var e;return(e=it.get(i))==null?void 0:e.error},dT=i=>{var e;return(e=it.get(i))==null?void 0:e.metadata},iu=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.streamType)!=null?t:ke.UNKNOWN},uT=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},du=i=>{var e,t;return(t=(e=it.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},cT=i=>{var e;let t=(e=it.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let r=du(i);return r.length?r.end(r.length-1)-t:Number.NaN},yp=.034,uD=(i,e,t=yp)=>Math.abs(i-e)<=t,hT=(i,e,t=yp)=>i>e||uD(i,e,t),cD=(i,e=yp)=>i.paused&&hT(i.currentTime,i.duration,e),fT=(i,e)=>{var t,r,s;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(r=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:r.details:(s=e.levels.find(c=>!!c.details))==null?void 0:s.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},Tp=(i,e)=>i.ended||i.loop?i.ended:e&&fT(i,e)?!0:cD(i),mT=(i,e,t)=>{bp(e,t,i);let{metadata:r={}}=i,{view_session_id:s=lD()}=r,n=dD(i);r.view_session_id=s,r.video_id=n,i.metadata=r;let a=u=>{var c;(c=e.mux)==null||c.emit("hb",{view_drm_type:u})};i.drmTypeCb=a,it.set(e,{retryCount:0});let o=hD(i,e),l=Bk(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?Ie:void 0}):ED(i,e,o),yD(i,e,o),Gk(e),Kk(e);let d=Fk(i,e,o);return{engine:o,setAutoplay:d,setPreload:l}},bp=(i,e,t)=>{let r=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?r&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),r&&(r.detachMedia(),r.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",yT),i.removeEventListener("error",dp),i.removeEventListener("durationchange",ET),it.delete(i),i.dispatchEvent(new Event("teardown")))};function pT(i,e){var t;let r=su(i);if(r!==mr.M3U8)return!0;let s=!r||((t=e.canPlayType(r))!=null?t:!0),{preferPlayback:n}=i,a=n===di.MSE,o=n===di.NATIVE;return s&&(o||!(lT&&(a||oD)))}var hD=(i,e)=>{let{debug:t,streamType:r,startTime:s=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=i,l=su(i)===mr.M3U8,d=pT(i,e);if(l&&!d&&lT){let u={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},c=fD(r),h=mD(i),f=[_o.QUERY,_o.HEADER].includes(a)?{useHeaders:a===_o.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,m=o.capLevelToPlayerSize==null?{capLevelController:Yk}:{},p=new Ie({debug:t,startPosition:s,cmcd:f,xhrSetup:(g,E)=>{var T,y;if(a&&a!==_o.QUERY)return;let b=new URL(E);if(!b.searchParams.has("CMCD"))return;let S=((y=(T=b.searchParams.get("CMCD"))==null?void 0:T.split(","))!=null?y:[]).filter(k=>k.startsWith("sid")||k.startsWith("cid")).join(",");b.searchParams.set("CMCD",S),g.open("GET",b)},...m,...u,...c,...h,...o});return p.on(Ie.Events.MANIFEST_PARSED,async function(g,E){var T,y;let b=(T=E.sessionData)==null?void 0:T["com.apple.hls.chapters"];(b!=null&&b.URI||b!=null&&b.VALUE.toLocaleLowerCase().startsWith("http"))&&vp((y=b==null?void 0:b.URI)!=null?y:b==null?void 0:b.VALUE,e)}),p}},fD=i=>i===ke.LIVE?{backBufferLength:8}:{},mD=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:r}=i,s=ou(t);return!e||!s?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:eu(i,"fairplay"),serverCertificateUrl:gT(i,"fairplay")},"com.widevine.alpha":{licenseUrl:eu(i,"widevine")},"com.microsoft.playready":{licenseUrl:eu(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=jk(n);return r==null||r(l),o}))}},pD=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},gD=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let r=await t.arrayBuffer();return new Uint8Array(r)},vD=(i,e)=>{dt(e,"encrypted",async t=>{try{let r=t.initDataType;if(r!=="skd"){console.error(`Received unexpected initialization data type "${r}"`);return}if(!e.mediaKeys){let l=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[r],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(u=>{var c;return(c=i.drmTypeCb)==null||c.call(i,Jd.FAIRPLAY),u}).catch(()=>{let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),c=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0);c.errorCategory=qe.DRM,c.muxCode=re.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,li(e,c)});if(!l)return;let d=await l.createMediaKeys();try{let u=await pD(gT(i,"fairplay")).catch(c=>{if(c instanceof Response){let h=tu(c,qe.DRM,i);return console.error("mediaError",h==null?void 0:h.message,h==null?void 0:h.context),h?Promise.reject(h):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(c)});await d.setServerCertificate(u).catch(()=>{let c=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),h=new Y(c,Y.MEDIA_ERR_ENCRYPTED,!0);return h.errorCategory=qe.DRM,h.muxCode=re.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(h)})}catch(u){li(e,u);return}await e.setMediaKeys(d)}let s=t.initData;if(s==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.addEventListener("keystatuseschange",()=>{n.keyStatuses.forEach(l=>{let d;if(l==="internal-error"){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");d=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0),d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_CDM_ERROR}else if(l==="output-restricted"||l==="output-downscaled"){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");d=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!1),d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_OUTPUT_RESTRICTED}d&&li(e,d)})});let a=await Promise.all([n.generateRequest(r,s).catch(()=>{let l=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),d=new Y(l,Y.MEDIA_ERR_ENCRYPTED,!0);d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_GENERATE_REQUEST_FAILED,li(e,d)}),new Promise(l=>{n.addEventListener("message",d=>{l(d.message)},{once:!0})})]).then(([,l])=>l),o=await gD(a,eu(i,"fairplay")).catch(l=>{if(l instanceof Response){let d=tu(l,qe.DRM,i);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 license key request"))}return Promise.reject(l)});await n.update(o).catch(()=>{let l=te("Failed to update DRM license. This may be an issue with the player or your protected content."),d=new Y(l,Y.MEDIA_ERR_ENCRYPTED,!0);return d.errorCategory=qe.DRM,d.muxCode=re.ENCRYPTED_UPDATE_LICENSE_FAILED,Promise.reject(d)})}catch(r){li(e,r);return}})},eu=({playbackId:i,tokens:{drm:e}={},customDomain:t=pr},r)=>{let s=ou(i);return`https://license.${t.toLocaleLowerCase().endsWith(pr)?t:pr}/license/${r}/${s}?token=${e}`},gT=({playbackId:i,tokens:{drm:e}={},customDomain:t=pr},r)=>{let s=ou(i);return`https://license.${t.toLocaleLowerCase().endsWith(pr)?t:pr}/appcert/${r}/${s}?token=${e}`},vT=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let r=window==null?void 0:window.location.href,s=new URL(e,r).hostname.toLocaleLowerCase();return s.includes(pr)||!!t&&s.includes(t.toLocaleLowerCase())},ED=(i,e,t)=>{var r;let{envKey:s,disableTracking:n,muxDataSDK:a=id,muxDataSDKOptions:o={}}=i,l=vT(i);if(!n&&(s||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((r=i==null?void 0:i.metadata)==null?void 0:r.video_title)||void 0},g=E=>typeof E.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(E):E;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?Ie:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...s?{env_key:s}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},yD=(i,e,t)=>{var r,s;let n=pT(i,e),{src:a,customDomain:o=pr}=i,l=()=>{e.ended||i.disablePseudoEnded||!Tp(e,t)||(fT(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=du(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(dt(e,"durationchange",c),e&&n){let h=su(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=lu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);vp(g.toString(),e)}let f=()=>{if(iu(e)!==ke.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),dt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>tD(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=tu(p,qe.VIDEO,i);if(g){li(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};dt(e,"play",p,{once:!0}),dt(e,"loadedmetadata",g,{once:!0})}else m();(r=i.tokens)!=null&&r.drm?vD(i,e):dt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new Y(p,Y.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=qe.DRM,g.muxCode=re.ENCRYPTED_MISSING_TOKEN,li(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((s=it.get(e))!=null?s:{}).startTime=i.startTime,e.addEventListener("durationchange",ET,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",yT),e.addEventListener("error",dp),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),dt(e,"pause",l),dt(e,"seeked",l),dt(e,"play",()=>{e.ended||hT(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(Ie.Events.LEVEL_LOADED,(h,f)=>{rD(f.details,e,t),c(),iu(e)===ke.LIVE&&!Number.isFinite(e.duration)&&(t.on(Ie.Events.LEVEL_UPDATED,c),dt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(Ie.Events.LEVELS_UPDATED,c)}))}),t.on(Ie.Events.ERROR,(h,f)=>{var m,p;let g=TD(f,i);if(g.muxCode===re.NETWORK_NOT_READY){let E=(m=it.get(e))!=null?m:{},T=(p=E.retryCount)!=null?p:0;if(T<6){let y=T===0?5e3:6e4,b=new Y(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(b,g),li(e,b),setTimeout(()=>{E.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);return}else{E.retryCount=0;let y=new Y('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(y,g),li(e,y);return}}li(e,g)}),t.on(Ie.Events.MANIFEST_LOADED,()=>{let h=it.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",dp),dt(e,"waiting",l),$k(i,t),Hk(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 ET(i){var e;let t=i.target,r=(e=it.get(t))==null?void 0:e.startTime;if(r&&Rk(t.seekable,t.duration,r)){let s=t.preload==="auto";s&&(t.preload="none"),t.currentTime=r,s&&(t.preload="auto")}}async function yT(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:r}=e.error,s=new Y(t,r);if(e.src&&r===Y.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Ep(e))!=null?n:e.error;(a==null?void 0:a.code)===Y.MEDIA_ERR_SRC_NOT_SUPPORTED&&li(e,s)},500);return}if(e.src&&(r!==Y.MEDIA_ERR_DECODE||r!==void 0))try{let{status:n}=await fetch(e.src);s.data={response:{code:n}}}catch{}li(e,s)}function li(i,e){var t;e.fatal&&(((t=it.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function dp(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof Y))return;let r=i.target,s=i.detail;!s||!s.fatal||(((e=it.get(r))!=null?e:{}).error=s,(t=r.mux)==null||t.emit("error",{player_error_code:s.code,player_error_message:s.message,player_error_context:s.context}))}var TD=(i,e)=>{var t,r,s;console.error("getErrorFromHlsErrorData()",i);let n={[Ie.ErrorTypes.NETWORK_ERROR]:Y.MEDIA_ERR_NETWORK,[Ie.ErrorTypes.MEDIA_ERROR]:Y.MEDIA_ERR_DECODE,[Ie.ErrorTypes.KEY_SYSTEM_ERROR]:Y.MEDIA_ERR_ENCRYPTED},a=u=>[Ie.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,Ie.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?Y.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===Ie.ErrorTypes.KEY_SYSTEM_ERROR)return qe.DRM;if(u.type===Ie.ErrorTypes.NETWORK_ERROR)return qe.VIDEO},l,d=a(i);if(d===Y.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:qe.VIDEO;l=(r=tu(i.response,u,e,i.fatal))!=null?r:new Y("",d,i.fatal)}else if(d===Y.MEDIA_ERR_ENCRYPTED)if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_MISSING_TOKEN}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=te("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_CDM_ERROR}else if(i.details===Ie.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new Y(u,Y.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_OUTPUT_RESTRICTED}else l=new Y(i.error.message,Y.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=re.ENCRYPTED_ERROR;else l=new Y("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
59
59
|
`:""}${i.response&&(i.response.code||i.response.text)?`response: ${i.response.code}, ${i.response.text}
|
|
60
60
|
`:""}${i.reason?`failure reason: ${i.reason}
|
|
61
61
|
`:""}${i.level?`level: ${i.level}
|
|
@@ -2370,7 +2370,6 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2370
2370
|
flex-flow: row;
|
|
2371
2371
|
align-items: center;
|
|
2372
2372
|
justify-content: center;
|
|
2373
|
-
filter: drop-shadow(0 0 2px rgb(0 0 0 / 0.25)) drop-shadow(0 0 6px rgb(0 0 0 / 0.25));
|
|
2374
2373
|
paint-order: stroke;
|
|
2375
2374
|
stroke: rgba(102, 102, 102, 1);
|
|
2376
2375
|
stroke-width: 0.3px;
|
|
@@ -2384,6 +2383,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2384
2383
|
--media-control-hover-background: transparent;
|
|
2385
2384
|
--media-control-padding: 0;
|
|
2386
2385
|
width: 40px;
|
|
2386
|
+
filter: drop-shadow(0 0 2px rgb(0 0 0 / 0.25)) drop-shadow(0 0 6px rgb(0 0 0 / 0.25));
|
|
2387
2387
|
}
|
|
2388
2388
|
|
|
2389
2389
|
[breakpointsm] .center-controls media-play-button {
|
|
@@ -2403,6 +2403,9 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2403
2403
|
padding: 0;
|
|
2404
2404
|
margin: 0 20px;
|
|
2405
2405
|
width: max(33px, min(8%, 40px));
|
|
2406
|
+
text-shadow:
|
|
2407
|
+
0 0 2px rgb(0 0 0 / 0.25),
|
|
2408
|
+
0 0 6px rgb(0 0 0 / 0.25);
|
|
2406
2409
|
}
|
|
2407
2410
|
|
|
2408
2411
|
[breakpointsm]:not([audio]) .center-controls.pre-playback {
|